Snippets Collections
class Solution {
  public:
    bool dfs(int node,vector<int> adj[],vector<int> &vis){
        vis[node]=1;
        bool ans=true;
        for(auto i : adj[node]){
            if(vis[i])
                return false;
            ans &=dfs(i,adj,vis);
        }
        vis[node]=0;
        return ans;
    }
    
    vector<int> eventualSafeNodes(int V, vector<int> adj[]) {
        // code here
        vector<int> vis(V,0),ans;
        for(int i=0;i<V;i++){
            if(dfs(i,adj,vis))
                ans.push_back(i);
        }
        return ans;
    }
};
<!DOCTYPE html>
<html lang="en">
<head>
    <style>

body {
    background-color: lightblue;
  }
  h3{background-color: aliceblue;text-align: center;text-decoration: dotted;

  }
  h1{
    text-decoration: double;background-color: azure;
  }
div{
    align-items: center;
}
a{
    align-items: center;
}
div{
    text-align: left;background-color: aquamarine;position: static;align-items: right;
    border: 3px solid #73AD21;
}


    </style>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div style="position: fixed;right: 0px;">
     username: <input placeholder="enter user id">
    <br>
    <br>
    password: <input type="password" placeholder="enter your password">
    </div>
    <h1 style="color: red;text-align: center;"> PRODUCT DETAIL:- </h1>
    <h3 style="text-align:center;color: black;">Samsung Galaxy M34 5G (Midnight Blue, 6GB, 128GB Storage) | 120Hz sAMOLED Display | 50MP Triple No Shake Cam | 6000 mAh Battery | 12GB RAM with RAM Plus | Android 13 | Without Charger</h3>
    <h1 style="text-align: center;color: rgb(30, 32, 32);">name:-</h1>
    <p style="text-align: center;color: brown;"> samsung m3</p>
    <h2>About this item:-</h2>
    <p style="text-align: center;text-decoration: dotted; background-color: blueviolet;">
        Exynos 1280 Octa Core 2.4GHz with the 12 band support for a True 5G experience
        16.42 centimeters (6.5-inch) Super AMOLED Display, FHD+ resolution, 1080 x 2340 pixels protected by Gorilla Glass 5
        50MP+8MP+2MP Triple Camera Setup - True 50MP No Shake Cam (F1.8) Main Camera + 8MP (F2.2) + 2MP (F2.4)| 13MP (F2.0) Front Camera
        6000mAH lithium-ion battery, 1 year manufacturer warranty for device and 6 months manufacturer warranty for in-box accessories including batteries from the date of purchase
        4 Generations of OS Upgrades and 5 Years of Security Updates</p>
        <div>
    <a href="https://www.amazon.in/Samsung-Midnight-Storage-sAMOLED-Display/dp/B0C7BZX934/ref=lp_4363159031_1_1?sbo=RZvfv%2F%2FHxDF%2BO5021pAnSA%3D%3D"> <img style="align-items: center;" src="https://m.media-amazon.com/images/I/91fonhAtoAL._AC_UL320_.jpg" alt=""></a>
</div>
</html>
void print(TrieNode* root, string t,vector<string>& s ){
        int cnt_nulls = 0;
        for(int i = 0; i < 26; i++){
            if(root->v[i] != NULL){
                char c = (i + 'a');
                // cout << c << endl;
                t.push_back(c);
                print(root->v[i] , t, s);
                t.pop_back();
            }
            else cnt_nulls++;
        }
        if(cnt_nulls == 26)
            s.push_back(t);
    }
class Solution {
public:
    int numOfWays(vector<int>& nums) {
        int m = nums.size();
        
        table.resize( m + 1);
        for(int i = 0; i < m + 1; ++i){
            table[i] = vector<long long> (i+1, 1);
            for(int j = 1; j < i ; ++j)
                table[i][j] = (table[i-1][j-1] + table[i-1][j])%mod;
        }
        return (dfs(nums) - 1) % mod;
    }
private:
    vector<vector<long long>> table;
    long long mod = 1e9+7;
    
    long long dfs(vector<int>& nums){
        int m = nums.size();
        if( m  < 3)
            return 1;
        vector<int> leftNodes, rightNodes;
        for(int i = 1; i < m ; i++){
            if( nums[i] < nums[0])
                leftNodes.push_back(nums[i]);
            else
                rightNodes.push_back(nums[i]);
        }
        long long leftWays = dfs(leftNodes) % mod;
        long long rightWays = dfs(rightNodes) % mod;
        return (((leftWays * rightWays) % mod) * table[m-1][leftNodes.size()])%mod;
    }
};
#include <stdio.h>

struct Item {
    char name[50];
    float price;
    int quantity;
};

float calculateTotal(struct Item items[], int itemCount) {
    float total = 0.0;
    for (int i = 0; i < itemCount; i++) {
        total += items[i].price * items[i].quantity;
    }
    return total;
}

float calculateDiscountedTotal(float total, float discount) {
    return total - (total * discount / 100);
}

float calculateRemainingCash(float total, float cashInput) {
    return cashInput - total;
}

void displayBill(struct Item items[], int itemCount, float total, float discount, float cashInput, float remainingCash) {
    printf("\n********** BILL **********\n");
    printf("Item\t\tPrice\tQuantity\n");
    printf("----------------------------\n");
    for (int i = 0; i < itemCount; i++) {
        printf("%s\t\t%.2f\t%d\n", items[i].name, items[i].price, items[i].quantity);
    }
    printf("----------------------------\n");
    printf("Total: %.2f\n", total);
    printf("Discount: %.2f%%\n", discount);
    printf("Discounted Total: %.2f\n", calculateDiscountedTotal(total, discount));
    printf("Cash Input: %.2f\n", cashInput);
    printf("Remaining Cash: %.2f\n", remainingCash);
    printf("****************************\n");
}

int main() {
    int itemCount;
    printf("Enter the number of items: ");
    scanf("%d", &itemCount);

    struct Item items[itemCount];

    printf("Enter the details of each item:\n");
    for (int i = 0; i < itemCount; i++) {
        printf("Item %d:\n", i + 1);
        printf("Name: ");
        scanf("%s", items[i].name);
        printf("Price: ");
        scanf("%f", &items[i].price);
        printf("Quantity: ");
        scanf("%d", &items[i].quantity);
    }

    float total = calculateTotal(items, itemCount);

    float discount;
    printf("Enter discount percentage: ");
    scanf("%f", &discount);

    float cashInput;
    printf("Enter cash input: ");
    scanf("%f", &cashInput);

    float remainingCash = calculateRemainingCash(calculateDiscountedTotal(total, discount), cashInput);

    displayBill(items, itemCount, total, discount, cashInput, remainingCash);

    return 0;
}
#include <stdio.h>

void printArray(int *A, int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d ", A[i]);
    }
    printf("\n");
}

void merge(int A[], int mid, int low, int high)
{
    int i, j, k, B[100];
    i = low;
    j = mid + 1;
    k = low;

    while (i <= mid && j <= high)
    {
        if (A[i] < A[j])
        {
            B[k] = A[i];
            i++;
            k++;
        }
        else
        {
            B[k] = A[j];
            j++;
            k++;
        }
    }
    while (i <= mid)
    {
        B[k] = A[i];
        k++;
        i++;
    }
    while (j <= high)
    {
        B[k] = A[j];
        k++;
        j++;
    }
    for (int i = low; i <= high; i++)
    {
        A[i] = B[i];
    }
    
}

void mergeSort(int A[], int low, int high){
    int mid; 
    if(low<high){
        mid = (low + high) /2;
        mergeSort(A, low, mid);
        mergeSort(A, mid+1, high);
        merge(A, mid, low, high);
    }
}

int main()
{
    // int A[] = {9, 14, 4, 8, 7, 5, 6};
    int A[] = {9, 1, 4, 14, 4, 15, 6};
    int n = 7;
    printArray(A, n);
    mergeSort(A, 0, 6);
    printArray(A, n);
    return 0;
}
#include<stdio.h>
#include<stdlib.h>

int graph[10][10], visited[10],total,arr[30];
static int k=0,count=0;
void DFS(int);
main()
{
	int i,j;
	printf("\nEnter the total number of vertices in graph\n");
	scanf("%d",&total);
	/*Adjacency matrix input*/
	printf("\nEnter the adjacency matrix\n");
	for(i=0;i<total;i++)
	{
		for(j=0;j<total;j++)
		{
			scanf("%d",&graph[i][j]);
		}
	}
	for(i=0;i<total;i++)
	{
		visited[i] = 0;
	}
	printf("\nDFS traversal is \n");
	DFS(0);
}
void DFS(int vertex)
{
	int j,c=0;
	count++;
	printf("%d\t",vertex);
	visited[vertex] = 1;
	for(j=0;j<total;j++)
	{
		if(!visited[j] && graph[vertex][j] == 1)
		{
			arr[++k] = j;
			c=1;
		}
		if(count == total)
		{
			exit(0);
		}
	}
	if(c==1)
	{
		DFS(arr[k]);
	}
	else
	{
		k--;
		DFS(arr[k]);
	}	
}
class Solution {
    public:
    vector<int> dx{0, 1, -1, 0},dy{1, 0, 0, -1};
    bool isVisitable(int x, int y, int N, int M){
        return x>=0 && y>=0 && x<N && y<M;
    }
    void dfs(int i, int j, int N, int M, vector<vector<int>>& matrix){
        for(int k =0 ; k <4; k++){
            int x = i + dx[k], y = j + dy[k];
            if( isVisitable(x, y, N, M) && matrix[x][y] != 0)
                matrix[x][y]=0,dfs(x, y, N, M, matrix);
        }
    }
    int closedIslands(vector<vector<int>>& matrix, int N, int M) {
        // Code here
        for(int i = 0; i < N; i++){
            for(int j = 0; j < M ; j++){
                if( (i == 0 || j == 0 || i == N -1 || j == M - 1 )&& matrix[i][j] == 1){
                    //check if 1 exists on the edges of matrix
                    //if yes visit all the cells that have 1 and are 
                    //reachable from current cell and mark them visited by making 0
                    matrix[i][j] = 0;
                    dfs(i, j, N, M,matrix);
                }
            }
        }
        
        int ans = 0;
        for(int i = 0 ; i < N; i++){
            for(int j = 0; j < M ; j++){
                if(matrix[i][j] == 1){
                    //whatever cells not visited in previous case 
                    //we visit now and mark visited(0) and increment the 
                    //the answer
                    matrix[i][j] = 0;
                    dfs(i, j ,N, M, matrix);
                    ans++;
                }
            }
        }
        return ans;
    }
};
class Tree(object):
    def __init__(self, value, left=None, right=None):
        self.val = value
        self.left = left
        self.right = right 
 
tx = Tree(4, Tree(1, Tree(-2, None, Tree(3, None, None))), Tree(3, Tree(1, None, None), Tree(2, Tree(-4, None, None), Tree(-3, None, None))))


def find_paths(root, required_sum):
    allPaths = []
  
    def find_paths_recursive(currentNode, required_sum, currentPath, allPaths):
      if currentNode is None:
        return
    
      # add the current node to the path
      currentPath.append(currentNode.val)
    
      # if the current node is a leaf and its value is equal to required_sum, save the current path
      if currentNode.val == required_sum and currentNode.left is None and currentNode.right is None:
        allPaths.append(list(currentPath))
      else:
        # traverse the left sub-tree
        find_paths_recursive(currentNode.left, required_sum -
                             currentNode.val, currentPath, allPaths)
        # traverse the right sub-tree
        find_paths_recursive(currentNode.right, required_sum -
                             currentNode.val, currentPath, allPaths)
    
      # remove the current node from the path to backtrack,
      # we need to remove the current node while we are going up the recursive call stack.
      del currentPath[-1]
    
    find_paths_recursive(root, required_sum, [], allPaths)
    
    return allPaths

find_paths(tx, 5)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        #order of first two conditionals is important 
        if not subRoot: return True 
        if not root: return False 
        if self.sameTree(root, subRoot): return True 
        
        return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
        
        
    def sameTree(self, s, t): 
        if not s and not t: return True 
        if s and t and s.val == t.val: 
            return self.sameTree(s.left, t.left) and self.sameTree(s.right, t.right) 

        return False 
        
        
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q: return True 
        if not p or not q: return False 
        if p.val != q.val: return False 
        
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        
star

Wed Oct 18 2023 17:40:55 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/eventual-safe-states/1

#graph #dfs #eventualsafestates
star

Wed Aug 23 2023 17:03:49 GMT+0000 (Coordinated Universal Time)

#algo #search #dfs
star

Sat Jun 24 2023 05:07:28 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/prefix-match-with-other-strings/1

#dfs #c++ #print_trie
star

Fri Jun 16 2023 07:57:40 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/

#c++ #dfs #bst #dynamic_programming #combinatorics
star

Fri May 26 2023 11:18:16 GMT+0000 (Coordinated Universal Time)

#algo #search #dfs
star

Tue May 23 2023 18:14:51 GMT+0000 (Coordinated Universal Time)

#algo #search #dfs
star

Mon May 22 2023 12:45:36 GMT+0000 (Coordinated Universal Time)

#algo #search #dfs
star

Thu May 18 2023 19:36:49 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/find-number-of-closed-islands/1

#dfs #closedislands
star

Mon Jul 18 2022 22:17:42 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/same-tree/submissions/

#python #tree #recursion #dfs #neetcode

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension