To Generate Permutation You Can Use These Codes-: Time Complexity
To Generate Permutation You Can Use These Codes-: Time Complexity
Sorting:-
1. Selection Sort
2. Bubble Sort
3. Insertion Sort
4. Merge Sort
5. Recursive Bubble Sort
6. Recursive Insertion Sort
7. Quick Sort
Arrays:-
1. Largest Element in an Array
2. Second Largest Element in an Array without sorting
3. Check if the array is sorted
4. Remove duplicates from Sorted array
5. Left Rotate an array by one place
6. Left rotate an array by D places
7. Move Zeros to end
8. Linear search
9. Find the Union
10. Find missing number in an array
11. Max consecutive one’s
12. Find the number that appears once, and the other numbers twice
13. Longest Subarray with given Sum K(Positives)
14. Longest Subarray with sum K | [Postives and Negatives]
15. Two sum
16. Sort an array of 0's 1's and 2's
17. Majority Element (>n/2 times)
18. Kadane’s Algorithm : Maximum Subarray Sum in an Array
19. print subarray with max subarray
20. Stock Buy And Sell
21. Rearrange Array Elements by Sign
22. next_permutation-find next lexicographically greater permutation
//Steps to find next permutation-
//1-Find the first pair index from behind which are in ascending order.
//2-if(index=-1)return the reversed array.
//3-Otherwise find the first element from behind which is greater than the
index and swap both the values and break the loop
//Finally reverse of this updated array from index+1 to end
Second approach->
Gap filling approach->
Time complexity-> if O((n+m)log(n+m))
Before merging the two sorted arrays- Just count the pairs and update the
answer.
To update the answer, you can use the below count code-
int counti(int l,int mid,int h,vector<int>&nums){
int i=l;
int j=mid+1;
int tempans=0;
while(i<=mid&&j<=h){
if(nums[i]>2*(long long)nums[j]){
tempans+=(mid-i+1);
j++;
}
else i++;
}
return tempans;
}
40. Maximum Product Subarray
Initilize the answer by maximum element
Go from left and right by maintaining the maximum product and
simultaneously update the answer.
If at any point, you encounters with 0 then just update product with 1 and
do continue;
Binary Search:-
1. Binary Search to find X in sorted array
2. Implement Lower Bound
3. Implement Upper Bound
4. Search insert position
5. Floor/Ceil in Sorted Array
6. First and Last Occurrences in Array
7. Count Occurrences in Sorted Array
8. Search in Rotated Sorted Array I
9. Search in Rotated Sorted Array II
10. Find minimum in Rotated Sorted Arra…
11. Minimum in rotated sorted array
12. Single element in a Sorted Array
13. Find peak element
14. Finding square root of a number in binary search
15. Nth root of a number in binary search
16. Koko Eating Bananas
17. Minimum days to make M bouquets
18. Find the smallest Divisor
19. Capacity to Ship Packages within D Days
20. Kth Missing Positive Number
21. Aggressive Cows
22. Book Allocation Problem
23. Split array - Largest Sum
24. Painter's partition
25. Minimise Maximum Distance between Gas Stations
26. Median of 2 sorted arrays
27. Kth element of 2 sorted arrays
28. Find the row with maximum number of 1’s
29. Search in a 2 D matrix
30. Find Peak Element (2D Matrix)
31. Matrix Median
32. Search in a row and column wise sorted matrix
Strings:-
1. Remove outermost parenthesis
2. Reverse Words in a String
3. Largest odd number in a string
4. Longest Common Prefix
5. Isomorphic String
6. check whether one string is a rotat…
7. Check if two Strings are anagrams of each other
8. Sort Characters by frequency
9. Maximum Nesting Depth of the Parentheses
10. Roman to Integer
11. Implement Atoi
12. Count Number of Substrings
13. Longest Palindromic Substring
14. Sum of Beauty of all substring
15. Reverse Every Word in A String
Linkedlist:-
1. Inserting a node in LinkedList
2. Deleting a node in LinkedList
3. Find the Length of a Linked List
4. Search an element in a Linked List
5. Insert a node in DLL
6. Delete a node in DLL
7. Reverse a DLL
8. Find middle element in a Linked List
9. Reverse a LinkedList [Iterative]
10. Reverse a LL [Recursive]
11. Detect a loop in LL
12. Starting point of loop in a Linked List
13. Length of Loop in LL
14. Check if LL is palindrome or not
15. Segregate odd and even nodes in LL
16. Remove N-th node from the end of a Linked List
17. Delete the middle node of LL
18. Sort LL
19. Sort linked list of 0s 1s 2s
20. Find intersection of Two Linked Lists
21. Add one to a number represented as Linked List
22. Add 2 numbers in LL
23. Delete all occurrences of a given key in a doubly linked list
24. Find pairs with given sum in doubly linked list
25. Remove duplicates from a sorted Doubly Linked List
26. Reverse List In K Groups
27. Rotate a Linked List
28. Flattening a Linked List
29. Clone a Linked List with random pointers
Recursion:-
1. String to Integer (atoi)
2. Implement Pow(x,n) | X raised to the power N
This is also known as Binary Exponentation
Observation:
if(!(temp.size()!=0&&a[i]==temp.back()))f(i+1,a,sum,us,temp);
}
return ans;
// write your code here.
}
Same code on coding ninjas is failing for last 5 test cases. Try to find out why in your
free time.
29. Expression Add Operators->
The multiplication recursive call is very important to understand->
// While doing the multiplication operation, we remove the previous operation and
update it with the multiplication operation
// This is done to follow the BODMAS rules for correct precedence
f(j+1,sumPath+'+'+tempPath,sum+number,number,num,target,result);
f(j+1,sumPath+'-'+tempPath,sum-number,-number,num,target,result);
f(j+1,sumPath+'*'+tempPath,sum-prev+(prev*number),prev*number,num,target
,result);
}
}
}
vector<string> addOperators(string num, int target) {
vector<string>result;
f(0,"",0,0,num,target,result);
return result;
}
int pop() {
stack<int>s2;
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
int ele=s2.top();
s2.pop();
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
return ele;
}
int peek() {
stack<int>s2;
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
int ele=s2.top();
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
return ele;
}
void pop() {
if(st.empty())return;
long long el=st.top();
st.pop();
if(el<mini){
mini=2LL*mini-el;
//M=2M-X
}
int top() {
if(st.empty())return -1;
long long el=st.top();
if(el<mini)return mini;
return el;
}
9. Infix to Postfix
Mujhse >=precedence walo ko nikalkr ans mai add kro because I can’t sit on the
top of these elements in the stack.
int pre(char c){
if(c=='+'||c=='-')return 1;
else if(c=='*'||c=='/')return 2;
else if(c=='^')return 3;
return -1;
}
string infixToPostfix(string exp){
// Write your code here
string ans="";
stack<char>st;
for(auto i:exp){
if((i>='a'&&i<='z')||(i>='A'&&i<='Z')||(i>='0'&&i<='9'))ans+=i;
else if(i=='(')st.push(i);
else if(i==')'){
while(st.size()!=0&&st.top()!='('){
ans+=st.top();
st.pop();
}
st.pop();
}
else{
while(st.size()!=0&&pre(i)<=pre(st.top())){
ans+=st.top();
st.pop();
}
st.push(i);
}
}
while(!st.empty()){
ans+=st.top();
st.pop();
}
return ans;
}
VVVVV Important
vector<int> nextGreaterElement(vector<int>& arr, int n)
{
//move from behind and agar mujhse >= stack mai then remove it
vector<int>ans(n);
stack<int>st;
for(int i=n-1;i>=0;i--){
while(!st.empty()&&st.top()<=arr[i])st.pop();
if(st.empty())ans[i]=-1;
else ans[i]=st.top();
st.push(arr[i]);
}
return ans;
}
int answer=INT_MIN;
for(int i=1;i<matrix.size();i++){
for(int j=0;j<matrix[0].size();j++){
matrix[i][j]=matrix[i][j]*(matrix[i-1][j]+matrix[i][j]);
//Multiplication of matrix[i][j] is done to reset the values if a zero if
found………. This is not very much intuitive and hence must remember this.
}
}
for(int i=0;i<matrix.size();i++){
int temp=largestRectangleArea(matrix[i]);
answer=max(answer,temp);
}
return answer;
}
}
int numberOfSubarrays(vector<int>& nums, int k) {
for(int i=0;i<nums.size();i++)nums[i]=nums[i]%2;
return countatmost(nums,k)-countatmost(nums,k-1);
}
Second one->
int numberOfSubstrings(string s) {
int i = 0;
int j = 0;
int cnt = 0;
unordered_map<int,int> mp;
while(j < s.length()){
mp[s[j]]++;
if(mp.size() == 3){
while(mp.size() == 3){
cnt += s.length()-j;//left se remove krenge so right wale
saare elements ko add krke bhi valid window bn skti
mp[s[i]]--;
if(mp[s[i]] == 0){
mp.erase(s[i]);
}
i++;
}
}
j++;
}
return cnt;
}
Bit Manipulation:-
1. You have a 32-bit unsigned integer called 'num' and
2. another integer called 'i'. You need to perform the
3. following operations on the 'num' integer based on the value of 'i':
4. Check whether K-th bit is set or not
5. You are given an integer 'N'.
6. Return 'odd' if the given number 'N' is odd, else return 'even'.
7. Power of Two
8. Count total set bits
This will help to find the number of set bits by continuously removing the
rightmost set bit.
In worst case it will take O(31) but as in most case all the bits of the number will
not be set bits and hence it will take O(log31) in average case.
int counti=0;
while(N){
N=N&(N-1); //This is used here to unset the rightmost set bit of N
counti++;
}
return counti;
}
The above code is best when you need to find number of set bits in som particular
numbers but for the case of range total of 1 to N. Use below approach->
The more optimized approach to find total number of set bits from 1 to N->
int countSetBits(int n)
{
if(n==0)return 0;
int x=floor(log2(n));
int y=x*(1<<(x-1));
int z=n-(1<<x);
return y+z+1+countSetBits(z);
}
15. L to R XOR
Very important question->
int findxor(int n){
if(n%4==1)return 1;
if(n%4==2)return n+1;
if(n%4==3) return 0;
return n;
}
int findXOR(int L, int R){
return findxor(L-1)^findxor(R);
}
Sliding Window:-
1. Longest Substring Without Repeating Characters
2. Max Consecutive Ones III
3. Fruit Into Baskets
4. Longest Repeating Substring
5. Count Subarrays With K Ones
6. Count number of nice subarrays
7. Count Substring With abc
8. Maximum Points From Cards
9. Longest Substring with At Most K Distinct Characters
10. Subarrays With ‘K’ Distinct Values
11. Minimum Window Substring
#include <bits/stdc++.h>
string smallestWindow(string s, string t)
{
unordered_map<char,int>um;
for(auto i:t)um[i]++;
int count=um.size();
string answer="";
int mini=1e9;
int i=0;
int j=0;
while(i<s.size()&&j<s.size()){
if(um.find(s[j])!=um.end()){
um[s[j]]--;
if(um[s[j]]==0)count--;
}
if(count==0){
if(mini>j-i+1){
answer=s.substr(i,j-i+1);
mini=j-i+1;
}
}
if(count==0){
while(i<s.size()&&count!=1){
if(um.find(s[i])!=um.end()){
um[s[i]]++;
if(um[s[i]]>0){
count++;
if (mini > j - i + 1) {
answer = s.substr(i, j - i + 1);
mini = j - i + 1;
}
}
}
i++;
}
}
j++;
}
return answer;
// Write your code here.
}
Heaps:-
Min heap is used for sorting in Decreasing order.
Max heap is used for sorting in increasing order.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int>arr={1,2,6,4,3,8,9,75};
cout<<"Available array:";
for(int i=0;i<arr.size();i++)cout<<arr[i]<<" ";
cout<<endl;
buildheap(arr,arr.size());
cout<<"The array after building heap";
for(int i=0;i<arr.size();i++)cout<<arr[i]<<" ";
cout<<endl;
sort(arr,arr.size());
cout<<"The array after sorting is by using inplace sorting algorithm heap sort:"<<endl;
for(int i=0;i<arr.size();i++)cout<<arr[i]<<" ";
return 0;
}
}
minHeap(int cap) {
capacity=cap;
// Write your code here.
}
void heapify(vector<int>&arr,int size,int i){
int index=i;
if(2*i+1<size&&arr[2*i+1]<arr[i])index=2*i+1;
if(2*i+2<size&&arr[2*i+2]<arr[index])index=2*i+2;
if(i!=index){
swap(arr[i],arr[index]);
heapify(arr, size, index);
}
}
void buildheap(vector<int>&arr,int size){
int p=(size/2)-1;
for(int i=p;i>=0;i--){
heapify(arr,size,i);
}
}
// Implement the function to remove minimum element.
int extractMinElement() {
if(heap.size()==0)return -1;
int ele=heap[0];
heap[0]=heap[heap.size()-1];
heap.pop_back();
heapify(heap,heap.size(),0);
return ele;
// Write you code here.
}
7. Jump Game
Try to Reach from Backward
bool canJump(vector<int>& nums) {
int index=nums.size()-1;
for(int i=nums.size()-1;i>=0;i--){
if(nums[i]+i>=index)index=i;
}
if(index==0)return true;
return false;
}
8. Jump Game 2
This is also not intuitive so remember how to solve this problem->
int jump(vector<int>& nums) {
int jump=0;
int farthest=0;
int current=0;
for(int i=0;i<nums.size()-1;i++){
farthest=max(farthest,nums[i]+i);
if(i==current){
current=farthest;
jump++;
}
}
return jump;
}
11. Candy
int candy(vector<int>& ratings) {
int n=ratings.size();
vector<int>left(n,1);
vector<int>right(n,1);
for(int i=1;i<n;i++){
if(ratings[i]>ratings[i-1])left[i]=1+left[i-1];
}
for(int i=n-2;i>=0;i--){
if(ratings[i]>ratings[i+1])right[i]=1+right[i+1];
}
int ans=0;
for(int i=0;i<n;i++){
ans+=max(left[i],right[i]);
}
return ans;
}
Binary Trees:-
1. Introduction to Trees
2. Binary Tree Representation in C++
Array to Tree Building->
Node *buildtree (int i,vector<int>&arr,int size) {
Node *temp = NULL;
if(i>=size)return temp;
else if (arr[i]){
temp = new Node(arr[i]);
temp->left = buildtree(2*i+1,arr,size);
temp->right = buildtree(2*i+2,arr,size);
}
else return temp;
}
12. Inorder,Preorder and postorder traversal using single stack for all three->
vector<vector<int>> getTreeTraversal(TreeNode *root){
// Write your code here.
vector<int>pre;
vector<int>pos;
vector<int>ino;
stack<pair<TreeNode*,int>>st;
st.push({root,1});
vector<vector<int>>ans;
if(root==NULL)return ans;
while(!st.empty()){
auto it=st.top();
st.pop();
if(it.second==1){
pre.push_back(it.first->data);
it.second=2;
st.push(it);
if(it.first->left)st.push({it.first->left,1});
}
else if(it.second==2){
ino.push_back(it.first->data);
it.second=3;
st.push(it);
if(it.first->right)st.push({it.first->right,1});
}
else pos.push_back(it.first->data);
}
ans.push_back(ino);
ans.push_back(pre);
ans.push_back(pos);
return ans;
}
#include<bits/stdc++.h>
void lef(TreeNode<int>* root,vector<int>&ans){
if(root==NULL)return;
if(root->left==NULL&&root->right==NULL)return;
ans.push_back(root->data);
if(root->left)lef(root->left,ans);
else lef(root->right,ans);
}
void level(TreeNode<int>*root,vector<int>&ans){
if(root==NULL)return;
if(root->left==NULL&&root->right==NULL){
ans.push_back(root->data);
return;
}
level(root->left,ans);
level(root->right,ans);
}
void rig(TreeNode<int>* root,stack<int>&st){
if(root==NULL)return;
if(root->left==NULL&&root->right==NULL)return;
st.push(root->data);
if(root->right)rig(root->right,st);
else rig(root->left,st);
}
vector<int> traverseBoundary(TreeNode<int> *root)
{
vector<int>ans;
if(root==NULL)return ans;
if(root->left||root->right)ans.push_back(root->data);
// ans.push_back(root->data);
lef(root->left,ans);
level(root,ans);
stack<int>st;
rig(root->right,st);
while(st.size()!=0){
ans.push_back(st.top());
st.pop();
}
return ans;
// Write your code here.
}
if(node->left)q.push({node->left,{p.second.first-1,p.second.second+1}});
if(node->right)q.push({node->right,{p.second.first+1,p.second.second+1}});
}
}
for(auto i:um){
vector<int>temp;
for(auto p:i.second){
temp.insert(temp.end(),p.second.begin(),p.second.end());
}
ans.push_back(temp);
}
return ans;
}
Left view->
Only first element on each horizontal level->
vector<int> printLeftView(BinaryTreeNode<int>* root) {
// Write your code here.
vector<int>ans;
// f(root,ans);
if(root==NULL)return ans;
map<int,int>um;
queue<pair<BinaryTreeNode<int>*,int>> q;
q.push({root,0});
while(!q.empty()){
int s=q.size();
for(int i=0;i<s;i++){
BinaryTreeNode<int>*node=q.front().first;
int level=q.front().second;
q.pop();
if(um.find(level)==um.end())um[level]=node->data;
if(node->left)q.push({node->left, level + 1});
if(node->right)q.push({node->right, level + 1});
}
}
for(auto i:um)ans.push_back(i.second);
return ans;
}
Right view->
Just one line change for->
Only last element on each horizontal level->
vector<int> rightSideView(TreeNode* root) {
vector<int>ans;
if(root==NULL)return ans;
map<int,int>um;
queue<pair<TreeNode*,int>>q;
q.push({root,0});
while(!q.empty()){
int s=q.size();
for(int i=0;i<s;i++){
TreeNode* node=q.front().first;
int level=q.front().second;
q.pop();
um[level]=node->val;
if(node->left)q.push({node->left,level+1});
if(node->right)q.push({node->right,level+1});
}
}
for(auto i:um)ans.push_back(i.second);
return ans;
}
Striver version->
If you can increase value by one as many times as we want->
29. All Nodes Distance K in Binary Tree
void markparents(TreeNode* root,unordered_map<TreeNode*,TreeNode*>&um){
if(root==NULL)return;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
int s=q.size();
for(int i=0;i<s;i++){
TreeNode* node=q.front();
q.pop();
if(node->left){
um[node->left]=node;
q.push(node->left);
}
if(node->right){
um[node->right]=node;
q.push(node->right);
}
}
}
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
unordered_map<TreeNode*,TreeNode*>um;//this will store parents
markparents(root,um);
queue<TreeNode*>q;
q.push(target);//starting the traversal fromt the target node
unordered_map<TreeNode*,bool>vis;
vis[target]=true;
int level=0;
while(!q.empty()){
if(level++==k)break;
int s=q.size();
for(int i=0;i<s;i++){
TreeNode* node=q.front();
q.pop();
if(node->left&&!vis[node->left]){
q.push(node->left);
vis[node->left]=true;
}
if(node->right&&!vis[node->right]){
q.push(node->right);
vis[node->right]=true;
}
if(um[node]&&!vis[um[node]]){
q.push(um[node]);
vis[um[node]]=true;
}
}
}
vector<int>ans;
while(!q.empty()){
ans.push_back(q.front()->val);
q.pop();
}
return ans;
}
root->left=build(prel+1,prel+leftcount,preoder,inl,indexroot-1,inorder,um
);
root->right=build(prel+leftcount+1,prer,preoder,indexroot+1,inr,inorder,u
m);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
map<int,int>um;
for(int i=0;i<inorder.size();i++){
um[inorder[i]]=i;
}
return
build(0,preorder.size()-1,preorder,0,inorder.size()-1,inorder,um);
}
root->left=build(inorder,inl,rootindex-1,postorder,posl,posl+leftcount-1,um);
root->right=build(inorder,rootindex+1,inr,postorder,posl+leftcount,posr-1,um);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
map<int,int>um;
for(int i=0;i<inorder.size();i++)um[inorder[i]]=i;
return
build(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1,um);
}
#include <map>
TreeNode<int>* build(vector<int>&postorder,int posl,int posr,vector<int>&inorder,int inl,int
inr,map<int,int>&um){
if(posl>posr||inl>inr)return NULL;
TreeNode<int>*root=new TreeNode<int>(postorder[posr]);
int rootindex=um[root->data];
int leftcount=rootindex-inl;
root->left=build(postorder,posl,posl+leftcount-1,inorder,inl,rootindex-1,um);
root->right=build(postorder,posl+leftcount,posr-1,inorder,rootindex+1,inr,um);
return root;
}
TreeNode<int>* getTreeFromPostorderAndInorder(vector<int>& postOrder, vector<int>& inOrder){
// Write your code here.
map<int,int>um;
for(int i=0;i<inOrder.size();i++)um[inOrder[i]]=i;
return build(postOrder,0,postOrder.size()-1,inOrder,0,inOrder.size()-1,um);
root->left=build(prel+1,prel+leftcount,preoder,inl,indexroot-1,inorder,um);
root->right=build(prel+leftcount+1,prer,preoder,indexroot+1,inr,inorder,um);
return root;
}
TreeNode* deserialize(string data) {
vector<int>preorder;
vector<int>inorder;
int ind=0;
while(ind<data.size()&&data[ind]!='+'){
string temp=to_string(data[ind]);
int value=stoi(temp)-48;
preorder.push_back(value);
ind++;
}
ind++;
while(ind<data.size()){
string temp=to_string(data[ind]);
int value=stoi(temp)-48;
inorder.push_back(value);
ind++;
}
map<int,int>um;
for(int i=0;i<inorder.size();i++){
um[inorder[i]]=i;
}
return
build(0,preorder.size()-1,preorder,0,inorder.size()-1,inorder,um);
}
According to the approach told by striver using Modified level order traversal->
string serialize(TreeNode* root) {
if(!root)return "";
string s="";
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
TreeNode* node=q.front();
q.pop();
if(node==NULL)s.append("#,");
else s.append(to_string(node->val)+',');
if(node){
q.push(node->left);
q.push(node->right);
}
}
return s;
}
}
return root;
}
38. Sum Tree GFG-> If root is the sum it’s left subtree nodes and right sub tree
nodes except the leaf nodes
int add(Node* root){
if(root==NULL)return 0;
return root->data+add(root->left)+add(root->right);
}
bool isSumTree(Node* root)
{
if(root==NULL)return true;
if(root->left==NULL&&root->right==NULL)return true;
int l=add(root->left);
int r=add(root->right);
return (root->data==l+r)&&isSumTree(root->left)&&isSumTree(root->right);
}
Binary Search Tree:-
1. Introduction to Binary Search Tree
Inorder traversal is always sorted-> L<Node<R in general
But if you want duplicates then either of two are the possibilities->
L<=Node<R more preferred over L<Node<=R
2. Search in a Binary Search Tree
TreeNode* searchBST(TreeNode* root, int val) {
if(root==NULL)return NULL;
if(root->val==val)return root;
if(root->val>val)return searchBST(root->left,val);
return searchBST(root->right,val);
}
Using Recursion->
void f(BinaryTreeNode<int>*node,int x,int &ans){
if(node==NULL)return;
if(node->data==x){
ans=x;
return;
}
else if(node->data>x){
ans=node->data;
f(node->left,x,ans);
}
else f(node->right,x,ans);
}
int findCeil(BinaryTreeNode<int> *node, int x){
int ans=-1;
f(node,x,ans);
return ans;
}
int ans=-1;
while(node){
if(node->data==input){
ans=node->data;
break;
}
else if(node->data<input){
ans=node->data;
node=node->right;
}
else node=node->left;
}
return ans;
}
}
else{
if(root->right==NULL){
root->right=new TreeNode(val);
return;
}
else insert(root->right,val);
}
}
TreeNode* insertIntoBST(TreeNode* root, int val){
insert(root,val);
return root;
}
Iterative->
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==NULL){
root=new TreeNode(val);
return root;
}
TreeNode* temp=root;
while(temp){
if(temp->val>val){
if(temp->left==NULL){
temp->left=new TreeNode(val);
break;
}
else temp=temp->left;
}
else{
if(temp->right==NULL){
temp->right=new TreeNode(val);
break;
}
else temp=temp->right;
}
}
return root;
}
The above same code with these changes will also work->
int maxi(TreeNode* root){
if(root->right==NULL)return root->val;
return maxi(root->right);
}
int mini(TreeNode* root){
if(root->left==NULL)return root->val;
return mini(root->left);
}
void deleteit(TreeNode* &root,int key){
if(root==NULL)return;
if(root->val==key){
if(root->left==NULL&&root->right==NULL){
root=NULL;
}
else if(root->left==NULL)root=root->right;
else if(root->right==NULL)root=root->left;
else{
root->val=maxi(root->left);
deleteit(root->left,root->val);
}
}
else if(root->val>key)deleteit(root->left,key);
else deleteit(root->right,key);
}
TreeNode* deleteNode(TreeNode* root, int key) {
deleteit(root,key);
return root;
}
The below Iterative code of above code done by me are not working -> Try to
find out why it is not working->
int maxi(TreeNode* root){
if(root->right==NULL)return root->val;
return maxi(root->right);
}
int mini(TreeNode* root){
if(root->left==NULL)return root->val;
return mini(root->left);
}
TreeNode* deleteNode(TreeNode* root1, int key) {
TreeNode* root=root1;
if(root1==NULL)return root1;
while(root){
if(root->val==key){
if(root->left==NULL&&root->right==NULL){
root=NULL;
}
else if(root->left==NULL){
root->val=mini(root->right);
root=root->right;
key=root->val;
}
else{
root->val=maxi(root->left);
root=root->left;
key=root->val;
}
}
else if(root->val>key)root=root->left;
else root=root->right;
}
return root1;
}
Also this below code is not working->
int maxi(TreeNode* root){
if(root->right==NULL)return root->val;
return maxi(root->right);
}
int mini(TreeNode* root){
if(root->left==NULL)return root->val;
return mini(root->left);
}
Iterative->
Taught by striver but it is also using the recursive method->
Watch the video again and try to solve it by striver method->
This method is important as it’s deleting the node and not doing the task by just altering
the values.
8. Find K-th smallest/largest element
void inorder(TreeNode* root,vector<int>&pre){
if(root==NULL)return;
inorder(root->left,pre);
pre.push_back(root->val);
inorder(root->right,pre);
}
int kthSmallest(TreeNode* root, int k) {
vector<int>ino;
inorder(root,ino);
return ino[k-1];
}
For kth largest->
You can solve for N-Kth smallest
OR
You can solve for getting the descending order traversal of BST which can be easily
obtained by changing/ swapping the recursive calls in the inorder function.
9. Check if a tree is a BST or BT
Use Range concept
if(root==NULL||(p->val>=root->val&&q->val<=root->val)||(p->val<=root->val&&q->v
al>=root->val))return root;
if(p->val>root->val)return lowestCommonAncestor(root->right,p,q);
return lowestCommonAncestor(root->left,p,q);
}
Striver way->
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL)return root;
if(root->val<p->val&&root->val<q->val)return
lowestCommonAncestor(root->right,p,q);
if(root->val>p->val&&root->val>q->val)return
lowestCommonAncestor(root->left,p,q);
return root;
}
root->left=build(preorder,prel+1,prel+leftlength+1,inorder,inl,index-1,um);
root->right=build(preorder,prel+leftlength+1,prer,inorder,index+1,inr,um);
return root;
}
TreeNode* bstFromPreorder(vector<int>& preorder) {
vector<int>inorder=preorder;
sort(inorder.begin(),inorder.end());
map<int,int>um;
for(int i=0;i<inorder.size();i++)um[inorder[i]]=i;
return
build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1,um);
}
}
TreeNode *preOrderTree(vector<int> &preOrder)
{
int i=0;
return build(i,INT_MAX,preOrder);
// Write your code here.
}
vector<int>nums3;
merge(nums3,nums2,nums1);
return nums3;
}
int next() {
int ans=st.top()->val;
TreeNode* temp=st.top()->right;
st.pop();
while(temp){
st.push(temp);
temp=temp->left;
}
return ans;
}
bool hasNext() {
return !st.empty();
}
};
class BSTIterator {
public:
stack<TreeNode*>st;
bool reverse=true;
BSTIterator(TreeNode* root,bool rev) {
reverse=rev;
push(root);
}
void push(TreeNode* root){
while(root){
st.push(root);
if(reverse==false)root=root->left;
else root=root->right;
}
}
int next() {
TreeNode* temp=st.top();
st.pop();
if(!reverse)push(temp->right);
else push(temp->left);
return temp->val;
}
bool hasNext() {
return !st.empty();
}
};
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
BSTIterator obj1(root,true);
BSTIterator obj2(root,false);
int val1=obj1.next();
int val2=obj2.next();
while(obj1.hasNext()&&obj2.hasNext()&&val1!=val2){
if(val1+val2==k)return true;
else if(val1+val2>k){
val1=obj1.next();
}
else val2=obj2.next();
}
return false;
}
};
Strings:-
1. Minimum Add to Make Parentheses Valid
2. Count and say
3. Hashing In Strings | Theory
4. Rabin Karp
5. Z-Function
6. KMP algo / LPS(pi) array
7. Shortest Palindrome
8. Longest happy prefix
9. Count palindromic subsequence
Graphs:-
1. Counting Graphs
4. BFS in Graph
First make it visited before Putting it in queue.
9. Flood fill
Both are correct-> “Jb bhi queue mai daalo usse phle color kro” OR “Jb bhi queue se
pop kro tb color kro”
}
}
return image;
}
}
}
return image;
}
if(row>0&&!vis[row-1][col])q.push({{row-1,col},tempans+1});
if(col>0&&!vis[row][col-1])q.push({{row,col-1},tempans+1});
if(row<mat.size()-1&&!vis[row+1][col])q.push({{row+1,col},tempans+1});
if(col<mat[0].size()-1&&!vis[row][col+1])q.push({{row,col+1},tempans+1})
;
}
}
return ans;
}
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
vector<vector<int>>vis(mat.size(),vector<int>(mat[0].size(),0));
for(int i=0;i<mat.size();i++){
for(int j=0;j<mat[0].size();j++){
if(mat[i][j]!=0)mat[i][j]=bfs(i,j,vis,mat);
}
}
return mat;
}
if(col>0&&!vis[row][col-1])q.push({{row,col-1},tempans+1});
if(row<mat.size()-1&&!vis[row+1][col])q.push({{row+1,col},tempans+1});
if(col<mat[0].size()-1&&!vis[row][col+1])q.push({{row,col+1},tempans+1})
;
}
// }
return ans;
}
A different way using the method jb queue mai daalu usse phle visit mark
kr->
vector < vector < int > > nearest(vector < vector < int >> & mat, int n, int m) {
// Write your code here.
vector<vector<int>>ans(n,vector<int>(m,0));
vector<vector<int>>vis(n,vector<int>(m,0));
queue<pair<pair<int,int>,int>>q;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(mat[i][j]==1){
q.push({{i,j},0});
vis[i][j]=1;
}
}
}
while(!q.empty()){
int i=q.front().first.first;
int j=q.front().first.second;
int tempans=q.front().second;
q.pop();
ans[i][j]=tempans;
if(i>0&&!vis[i-1][j]){
vis[i-1][j]=1;
q.push({{i - 1, j}, tempans + 1});
}
if(j>0&&!vis[i][j-1]){
vis[i][j-1]=1;
q.push({{i, j - 1}, tempans + 1});
}
if(i<n-1&&!vis[i+1][j]){
vis[i+1][j]=1;
q.push({{i + 1, j}, tempans + 1});
}
if(j<m-1&&!vis[i][j+1]){
vis[i][j+1]=1;
q.push({{i, j + 1}, tempans + 1});
}
}
return ans;
}
if(i<board.size()-1&&!vis[i+1][j]&&board[i+1][j]=='O')dfs(i+1,j,board,vis);
if(j<board[0].size()-1&&!vis[i][j+1]&&board[i][j+1]=='O')dfs(i,j+1,board,vis);
}
void solve(vector<vector<char>>& board) {
int m=board.size();
int n=board[0].size();
vector<vector<int>>vis(m,vector<int>(n,0));
for(int i=0;i<m;i++){
if(!vis[i][0]&&board[i][0]=='O')dfs(i,0,board,vis);
if(!vis[i][n-1]&&board[i][n-1]=='O')dfs(i,n-1,board,vis);
}
for(int j=0;j<n;j++){
if(!vis[0][j]&&board[0][j]=='O')dfs(0,j,board,vis);
if(!vis[m-1][j]&&board[m-1][j]=='O')dfs(m-1,j,board,vis);
}
int counti=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j]=='O'&&!vis[i][j])board[i][j]='X';
}
}
}
if(j<grid[0].size()-1&&!vis[i][j+1]&&grid[i][j+1]==1)dfs(i,j+1,vis,grid);
}
int numEnclaves(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
vector<vector<int>>vis(m,vector<int>(n,0));
for(int i=0;i<m;i++){
if(!vis[i][0]&&grid[i][0]==1)dfs(i,0,vis,grid);
if(!vis[i][n-1]&&grid[i][n-1]==1)dfs(i,n-1,vis,grid);
}
for(int j=0;j<n;j++){
if(!vis[0][j]&&grid[0][j]==1)dfs(0,j,vis,grid);
if(!vis[m-1][j]&&grid[m-1][j]==1)dfs(m-1,j,vis,grid);
}
int ans=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==1&&!vis[i][j])ans++;
}
}
return ans;
}
I can also use BFS in the above problems.
15. Word ladder - 1
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
set<string>us(wordList.begin(),wordList.end());
queue<pair<string,int>>q;
q.push({beginWord,1});
while(!q.empty()){
auto p=q.front();
string s=p.first;
int number=p.second;
if(s==endWord)return number;
q.pop();
for(int i=0;i<s.size();i++){
for(char c='a';c<='z';c++){
string temps=s;
temps[i]=c;
if(us.find(temps)!=us.end()){
q.push({temps,number+1});
us.erase(temps);
}
}
}
}
return 0;
}
Second Observation->
If a graph has an odd length cycle then it’s not a bipartite graph.
Or simply run a dfs and if the new node is already colored with the same color then return false;
}
bool isBipartite(vector<vector<int>>& graph) {
vector<int>color(graph.size(),-1);
for(int i=0;i<graph.size();i++){
if(color[i]==-1){
if(dfs(i,0,color,graph)==false)return false;
}
}
return true;
}
Maintain a stack and put into the stack when you go back.
USING DFS->
#include<stack>
void dfs(int i,vector<int>&vis,vector<int>adj[],stack<int>&st){
vis[i]=1;
for(auto node:adj[i]){
if(!vis[node])dfs(node,vis,adj,st);
}
st.push(i);
}
vector<int> topologicalSort(vector<vector<int>> &graph, int edges, int nodes) {
// Write your code here!
vector<int>adj[nodes];
for(auto i:graph){
adj[i[0]].push_back(i[1]);
}
stack<int>st;
vector<int>vis(nodes,0);
for(int i=0;i<nodes;i++){
if(!vis[i])dfs(i,vis,adj,st);
}
vector<int>ans;
while(!st.empty()){
ans.push_back(st.top());
st.pop();
}
return ans;
}
21. Kahn's Algorithm-> SAME AS TOPO SORT BUT USING BFS WITH INDEGREE
QUEUE->
#include<queue>
vector<int> topologicalSort(vector<vector<int>> &graph, int edges, int nodes) {
// Write your code here!
vector<int>adj[nodes];
for(auto i:graph){
adj[i[0]].push_back(i[1]);
}
vector<int>indegree(nodes,0);
for(int i=0;i<nodes;i++){
for(auto node:adj[i])indegree[node]++;
}
vector<int>ans;
queue<int>q;
for(int i=0;i<nodes;i++){
if(indegree[i]==0)q.push(i);
}
while(!q.empty()){
int node=q.front();
q.pop();
ans.push_back(node);
for (auto it : adj[node]) {
indegree[it]--;
if (indegree[it] == 0)
q.push(it);
}
}
return ans;
}
#include<queue>
int detectCycleInDirectedGraph(int nodes, vector < pair < int, int >> & edges) {
vector<int>adj[nodes+1];
for(auto i:edges){
adj[i.first].push_back(i.second);
}
vector<int>indegree(nodes+1,0);
for(int i=0;i<nodes+1;i++){
for(auto node:adj[i])indegree[node]++;
}
int counti=0;
queue<int>q;
for(int i=0;i<nodes+1;i++){
if(indegree[i]==0)q.push(i);
}
while(!q.empty()){
int node=q.front();
q.pop();
counti++;
for (auto it : adj[node]) {
indegree[it]--;
if (indegree[it] == 0)
q.push(it);
}
}
if(counti==nodes+1)return 0;
return 1;
}
vector<int>indegree(nodes,0);
for(int i=0;i<nodes;i++){
for(auto node:adj[i])indegree[node]++;
}
int counti=0;
queue<int>q;
for(int i=0;i<nodes;i++){
if(indegree[i]==0)q.push(i);
}
while(!q.empty()){
int node=q.front();
q.pop();
counti++;
for (auto it : adj[node]) {
indegree[it]--;
if (indegree[it] == 0)
q.push(it);
}
}
if(counti==nodes)return true;
return false;
}
for(int i=0;i<n;i++){
for(auto it:graph[i]){
adj[it].push_back(i);
indegree[i]++;
}
}
queue<int>q;
for(int i=0;i<n;i++){
if(indegree[i]==0)q.push(i);
}
vector<int>ans;
while(!q.empty()){
int node=q.front();
q.pop();
ans.push_back(node);
for(auto i:adj[node]){
indegree[i]--;
if(indegree[i]==0)q.push(i);
}
}
sort(ans.begin(),ans.end());
return ans;
}
return ans;
}
#include<bits/stdc++.h>
int shortestPathBinaryMatrix(vector<vector<int>> &matrix, pair<int, int> src, pair<int, int> dest)
{
// Write your code here
if(matrix[src.first][src.second]==0)return -1;
int n=matrix.size();
int m=matrix[0].size();
vector<vector<int>>dis(n,vector<int>(m,1e9));
//
priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>>
pq;
//No need to use priority key as we are exploring, the distance is increasing by 1 only and not
randomly and hence in queue the distance will always lie in sorted order.
queue<pair<int,pair<int,int>>>pq;
pq.push({0,src});
dis[src.first][src.second]=0;
while(!pq.empty()){
auto p=pq.front();
pq.pop();
int d=p.first;
int r=p.second.first;
int c=p.second.second;
if(r>0&&matrix[r-1][c]==1&&dis[r-1][c]>d+1){
dis[r-1][c]=d+1;
pq.push({d+1,{r-1,c}});
}
if(c>0&&matrix[r][c-1]==1&&dis[r][c-1]>d+1){
dis[r][c-1]=d+1;
pq.push({d+1,{r,c-1}});
}
if(r<n-1&&matrix[r+1][c]==1&&dis[r+1][c]>d+1){
dis[r+1][c]=d+1;
pq.push({d+1,{r+1,c}});
}
if(c<m-1&&matrix[r][c+1]==1&&dis[r][c+1]>d+1){
dis[r][c+1]=d+1;
pq.push({d+1,{r,c+1}});
}
}
if(dis[dest.first][dest.second]==1e9)return -1;
return dis[dest.first][dest.second];
}
Using the above thing to solve this problem easily for leetcode version->
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
int n=grid.size();
if(grid[0][0]==1||grid[n-1][n-1]==1)return -1;
vector<vector<int>>dis(n,vector<int>(n,1e9));
queue<pair<int,pair<int,int>>>q;
dis[0][0]=1;
q.push({1,{0,0}});
while(!q.empty()){
auto p=q.front();
q.pop();
int d=p.first;
int i=p.second.first;
int j=p.second.second;
int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
for (int k=0;k<8;++k){
int x = i + dx[k];
int y = j + dy[k];
if (x >= 0 && x < n && y >= 0 && y < n
&&grid[x][y]==0&&dis[x][y]>d+1) {
dis[x][y]=d+1;
q.push({d+1,{x,y}});
}
}
}
if(dis[n-1][n-1]==1e9)return -1;
return dis[n-1][n-1];
}
34. Path with minimum effort->
Very interesting and very important twisted version of Dijkstra algorithm.
#include<bits/stdc++.h>
int minimumTimeTakingPath(vector<vector<int>> &heights)
{
int n=heights.size();
int m=heights[0].size();
vector<vector<int>>dis(n,vector<int>(m,1e9));
dis[0][0]=0;
priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>>
pq;
pq.push({0, {0, 0}});
int dr[] ={-1,0,1,0};
int dc[]={0,1,0,-1};
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
int d = p.first;
int i = p.second.first;
int j = p.second.second;
for(int k=0;k<4;k++){
int r=i+dr[k];
int c=j+dc[k];
if(r>=0&&c>=0&&r<n&c<m){
int effort=max(d,abs(heights[i][j]-heights[r][c]));
if(effort<dis[r][c]){
dis[r][c]=effort;
pq.push({effort, {r, c}});
}
}
}
}
if(dis[n-1][m-1]==1e9)return -1;
return dis[n-1][m-1];
}
A twisted line to save time->
int minimumEffortPath(vector<vector<int>>& heights) {
int n=heights.size();
int m=heights[0].size();
vector<vector<int>>dis(n,vector<int>(m,1e9));
dis[0][0]=0;
priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<
pair<int,pair<int,int>>>>pq;
pq.push({0, {0, 0}});
int dr[] ={-1,0,1,0};
int dc[]={0,1,0,-1};
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
int d = p.first;
int i = p.second.first;
int j = p.second.second;
if(i==n-1&&j==m-1)return d;
for(int k=0;k<4;k++){
int r=i+dr[k];
int c=j+dc[k];
if(r>=0&&c>=0&&r<n&c<m){
int effort=max(d,abs(heights[i][j]-heights[r][c]));
if(effort<dis[r][c]){
dis[r][c]=effort;
pq.push({effort, {r, c}});
}
}
}
}
return -1;
}
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>
>q;
dis[source]=0;
q.push({0,source});
while(!q.empty()){
auto p=q.top();
q.pop();
int node=p.second;
int d=p.first;
for(auto i:adj[node]){
int adjnode=i.first;
int adjdis=i.second;
if(d+adjdis<dis[adjnode]){
dis[adjnode]=d+adjdis;
q.push({dis[adjnode],adjnode});
}
}
}
int mx=*max_element(dis.begin()+1,dis.end());
return mx==INT_MAX?-1:mx;
}
};
}
else if(d+adjdis==dis[adjnode]){
ways[adjnode]=(ways[adjnode]%mod+ways[node])%mod;
}
}
}
return ways[n-1]%mod;
}
Check why coding ninja version is giving wrong answer.
#include<bits/stdc++.h>
int minimumOperations(int n, int start, int end, vector<int> &a)
{
// queue<pair<int,int>>q;
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>q;
q.push({0,start});
vector<int>dis(1000,1e9);
dis[start]=0;
int mod=1000;
while(!q.empty()){
int node=q.top().second;
int steps=q.top().first;
q.pop();
if(node==end)return dis[node];
for(auto i:a){
int num=(i*node)%mod;
if(steps+1<dis[num]){
dis[num]=steps+1;
q.push({steps+1,num});
}
}
}
return -1;
}
40. Bellman Ford Algorithm-> Single source shortest Path algorithm
Do n-1 iteration in Directed Graph.
If on nth iteration the relaxation is done and the distance array still got updated hence
there is a cycle with negative edge.
vector<int> bellmonFord(int n, int m, int src, vector<vector<int>> &edges) {
// Write your code here.
vector<int>dis(n+1,1e8);
dis[src]=0;
for(int i=0;i<n-1;i++){
for(auto edge:edges){
int u=edge[0];
int v=edge[1];
int w=edge[2];
if(dis[u]+w<dis[v]){
dis[v]=dis[u]+w;
}
}
}
return dis;
}
Now if you run for(auto) loop once again and the if condition is satisfied then it means
the directed graph has a cycle with negative edge.
41. Floyd Warshal Algorithm-> Multi source shortest path algorithm->
Tries:-
1. Trie Implementation
2. Implement Trie - 2 (Prefix Tree)
3. Number of Distinct Substrings in a String Using Trie
4. Bitwise Basic Operations
5. Maximum XOR of Two Numbers in an Array
6. Maximum Xor Queries | Trie
Extra questions other than sheet->