Snippets Collections
class Solution
{
	public:
	//Function to find the level of node X.
	using pi = pair<int,int>;
	int nodeLevel(int V, vector<int> adj[], int X) 
	{
	    // code here
	    vector<bool> vis(V, false);
	    queue<pi> q;
	    q.push({0, 0});
	    vis[0] = true;
	    while(!q.empty()){
	        auto curr = q.front();q.pop();
	        if(curr.first == X)
	            return curr.second;
	       for(auto adjV : adj[curr.first]){
	           if(!vis[adjV]){
	               vis[adjV] = true;
	               q.push({adjV , curr.second + 1});
	           }
	       }
	    }
	    return -1;
	}
};
class Solution{
    
    public:
    // Your are required to complete this function
    // function should return root of the modified BST
    void inorder(Node* root, vector<int>& bst){
        if(!root)
            return;
        inorder(root->left, bst);
        bst.push_back(root->data);
        inorder(root->right, bst);
    }
    
    Node* build(int l , int r, vector<int>& bst){
        if(l > r)
            return nullptr;
        if(l == r)
            return new Node(bst[l]);
        int m = (l + r)/2;
        Node* root = new Node(bst[m]);
        root->left = build(l, m-1,bst);
        root->right = build(m+1,r,bst);
        return root;
    }
    Node* buildBalancedTree(Node* root)
    {
    	// Code here
    	vector<int> bst;
    	inorder(root, bst);
    	return build(0, bst.size() - 1, bst);
    }
};
class Solution {
public:
	//assume you are standing at the ith index and you ask should I choose (i-1)th or (i-2)th to reach the ith position then choose whichever is lesser in cost.
	// ex - > [2,3,1,1,1,4,2,1,3]
	// we insert 0 at beginning and end
	// [0,2,3,1,1,1,4,2,1,3,0], n = 11
	//we start the iteration from 2nd index 
	// [0,2,_,_,_,_,_,_,_,_,_]
	// [0,2,3,_,_,_,_,_,_,_,_]
	// [0,2,3,3,_,_,_,_,_,_,_]
	// [0,2,3,3,4,_,_,_,_,_,_]
	// [0,2,3,3,4,4,_,_,_,_,_]
	// [0,2,3,3,4,4,8,_,_,_,_]
	// [0,2,3,3,4,4,8,6,_,_,_]
	// [0,2,3,3,4,4,8,6,7,_,_]
	// [0,2,3,3,4,4,8,6,7,9,_]
	// [0,2,3,3,4,4,8,6,7,9,7]
	// our answer is 7;

    int minCostClimbingStairs(vector<int>& cost) {
        cost.insert(cost.begin() + 0, 0);
        cost.push_back(0);
        vector<int> dp(cost);
        for(int i = 2; i < dp.size() ; i++)
            dp[i] = dp[i] + min(dp[i-1],dp[i-2]);
        return dp.back();
    }
};
star

Thu Oct 19 2023 07:20:10 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/level-of-nodes-1587115620/1

#bfs #graphs #easy
star

Sun Oct 15 2023 11:44:12 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/normal-bst-to-balanced-bst/1

#bst #balancebst #easy
star

Fri Oct 13 2023 04:00:28 GMT+0000 (Coordinated Universal Time)

#dyanammicprogramming #dp #minimumcoststairs #easy

Save snippets that work with our extensions

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