Repository: Prince-1501/Hello_world-Competiitve-Programming Branch: master Commit: 6bab395fbefe Files: 212 Total size: 192.6 KB Directory structure: gitextract_md51_btr/ ├── 35_hacker_two_strings.cpp ├── 36_codechef_Encoding_message.cpp ├── 37_codechef_spell_bob.cpp ├── 38_codechef_fits_square_in_triangle.cpp ├── 39_codechef_chef_and_Eid.cpp ├── 40_codechef_chef_judges_competition.cpp ├── 41_codechef_chef_and_glove.cpp ├── 42_codechef_the_great_run.cpp ├── 43_codechef_attendance.cpp ├── 44_codechef_making_a_meal.cpp ├── 45_codechef_uncle_johny.cpp ├── 46_drink_codeforce.cpp ├── 47_candles_codeforces.cpp ├── 49_two_buttons_codeforces.cpp ├── 50_vanya_and_books_codeforces.cpp ├── 51_eleven_codeforces.cpp ├── 52_codechef_flatland.cpp ├── 53_codeforces_MUH_and_sticks.cpp ├── 54_print_subset_of_size_k_of_array.cpp ├── 55_codechef_Easy_Fibonacci.cpp ├── 56_codechef_Chef_and_Interesting_Subsequences.cpp ├── 57_codechef_A-books.cpp ├── 58_codechef_phone_prices.cpp ├── 59_codechef_operations_on_a_matrix.cpp ├── 60_Adding_one_to_the_numbers.cpp ├── Chef and Price Control.cpp ├── Data Structures/ │ ├── Add a node at the Middle of linked list.cpp │ ├── Add a node at the end of linked list.cpp │ ├── Add a node at the front of linked list.cpp │ ├── Array_in_data_structures.cpp │ ├── Circular Linked List data_structure.cpp │ ├── Delete a node of a linked list.cpp │ ├── Doubly Linked list.cpp │ ├── Find the middle of a given linked list.cpp │ ├── Insert Node at the End of Doubly Linked List.cpp │ ├── Insert Node in Middle of Doubly Linkedlist.cpp │ ├── LinkedList_Code_Practice.cpp │ ├── Vectors_in_STL_data_structure.cpp │ ├── main.cpp │ └── structure_in_c++.cpp ├── Kadane's_algorithm.cpp ├── Kadane's_algorithm.pptx ├── Lecture - 15.cpp ├── Lecture - 16.cpp ├── Lecture - 17.cpp ├── Lecture - 18.cpp ├── Lecture - 19.cpp ├── Lecture - 20.cpp ├── Lecture - 21.cpp ├── Lecture - 22.cpp ├── Lecture - 24.cpp ├── Lecture - 25.cpp ├── Lecture - 26.cpp ├── Lecture - 27.cpp ├── Lecture - 31.cpp ├── Lecture - 32.cpp ├── Lecture - 33.cpp ├── Lecture - 34.cpp ├── Leetcode/ │ ├── Add Digits.cpp │ ├── Add Two Numbers Leetcode Solutions in Linkedlist.cpp │ ├── Binary Search leetcode Solution.cpp │ ├── Boolean Matrix.cpp │ ├── Count the Number of Consistent Strings.cpp │ ├── Graph/ │ │ ├── All Paths From Source to Target.cpp │ │ ├── Course Schedule.cpp │ │ ├── Detect cycle in a directed graph.cpp │ │ ├── Find Eventual Safe States.cpp │ │ ├── Find if Path Exists in Graph.cpp │ │ ├── Find the Town Judge.cpp │ │ ├── Flood Fill.cpp │ │ ├── Keys and Rooms.cpp │ │ ├── Max Area of Island.cpp │ │ ├── Minimum Time to Collect All Apples in a Tree.cpp │ │ ├── Number of Enclaves.cpp │ │ ├── Number of Islands.cpp │ │ ├── Number of Provinces.cpp │ │ ├── Number of closed Islands.cpp │ │ ├── Rotting Oranges.cpp │ │ ├── Steps by Knight.cpp │ │ ├── Surrounded Regions.cpp │ │ ├── Time Needed to Inform All Employees.cpp │ │ ├── Topological sort .cpp │ │ └── Topological sort using dfs.cpp │ ├── Hashing/ │ │ ├── Check if two arrays are equal or not.cpp │ │ ├── Custom Sort String.cpp │ │ ├── First Repeating Element.cpp │ │ ├── Group Anagrams.cpp │ │ ├── Intersection of two arrays.cpp │ │ ├── Key Pair.cpp │ │ ├── LFU Cache.cpp │ │ ├── Non-Repeating Element.cpp │ │ ├── Pairs with Positive Negative values.cpp │ │ ├── Relative Sort Array.cpp │ │ ├── Sort Array by Increasing Frequency.cpp │ │ ├── Subarray with 0 sum.cpp │ │ ├── Winner of an election.cpp │ │ ├── unordered_map.cpp │ │ └── unordered_set.cpp │ ├── Interchanging the rows of a Matrix.cpp │ ├── Majority Element Geeksforgeeks leetcode Moore's Voting Algorithm.cpp │ ├── Median of Two sorted arrays.cpp │ ├── Middle of the Linked List Leetcode.cpp │ ├── Middle of the Linked List.cpp │ ├── Move Zeroes.cpp │ ├── Multiply two matrices.cpp │ ├── Naive Pattern Search.cpp │ ├── Next Greater Element.cpp │ ├── Non Repeating Character.cpp │ ├── Peak element.cpp │ ├── Rearrange Array Alternately Geeksforgeeks.cpp │ ├── Recursion/ │ │ ├── 0-1 Knapsack Problem Top down.cpp │ │ ├── Best Time to Buy and Sell Stock.cpp │ │ ├── Climbing Stairs.cpp │ │ ├── Decode Ways.cpp │ │ ├── Delete middle element of a stack.cpp │ │ ├── Divisor Game.cpp │ │ ├── Factorial.cpp │ │ ├── Fibonacci Number.cpp │ │ ├── House Robber.cpp │ │ ├── Largest Element in Array.cpp │ │ ├── Min Cost Climbing Stairs.cpp │ │ ├── Nth Fibonacci Number.cpp │ │ ├── Partition Equal Subset Sum.cpp │ │ ├── Perfect Squares.cpp │ │ ├── Perfect Sum Problem.cpp │ │ ├── Power Of Numbers.cpp │ │ ├── Print 1 To N Without Loop.cpp │ │ ├── Reverse a String.cpp │ │ ├── Subset Sum Problem.cpp │ │ ├── Sum of Array.cpp │ │ ├── Target Sum.cpp │ │ └── Tower Of Hanoi.cpp │ ├── Reverse Linked List.cpp │ ├── Rotate Array Leetcode.cpp │ ├── Rotate List.cpp │ ├── Search in a row-column sorted Matrix.cpp │ ├── Single Number Leetcode solution.cpp │ ├── Sort Array By Parity.cpp │ ├── Sort Colors.cpp │ ├── Spirally traversing a matrix.cpp │ ├── Square root.cpp │ ├── Subarray sum equals K.cpp │ ├── Trapping Rain Water.cpp │ ├── Tree/ │ │ ├── Balanced Binary Tree.cpp │ │ ├── Binary Tree Inorder Traversal.cpp │ │ ├── Binary Tree Right Side View.cpp │ │ ├── Binary Tree Zigzag Level Order Traversal.cpp │ │ ├── Children Sum Parent.cpp │ │ ├── Construct Binary Tree from Preorder and Inorder Traversal.cpp │ │ ├── Diameter of Binary Tree.cpp │ │ ├── Invert Binary Tree.cpp │ │ ├── Level Order Traversal.cpp │ │ ├── Lowest Common Ancestor of a Binary Tree.cpp │ │ ├── Maximum Depth of Binary Tree.cpp │ │ ├── Populating Next Right Pointers in Each Node.cpp │ │ ├── Subtree of Another Tree.cpp │ │ ├── Symmetric Tree.cpp │ │ ├── Vertical Width of a Binary Tree .cpp │ │ └── same Tree.cpp │ ├── count 1's in binary array.cpp │ ├── linked-list-cycle.cpp │ ├── linkedlist/ │ │ ├── Copy List with Random Pointer.cpp │ │ ├── Delete Node in a Linked List.cpp │ │ ├── Intersection of Two Linked Lists.cpp │ │ ├── Linked List Cycle II.cpp │ │ ├── Merge Two Sorted Lists.cpp │ │ ├── Palindrome Linked List.cpp │ │ ├── Remove Duplicates from Sorted List.cpp │ │ ├── Remove Nth Node From End of List.cpp │ │ ├── Remove duplicates from an unsorted linked list.cpp │ │ ├── Reverse Linked List.cpp │ │ ├── Sort List.cpp │ │ ├── Swap Nodes in Pairs.cpp │ │ └── Swapping Nodes in a Linked List.cpp │ ├── stack/ │ │ ├── Evaluate Reverse Polish Notation.cpp │ │ ├── Implement Queue using Stacks.cpp │ │ ├── Implement Stack using Queues.cpp │ │ ├── Largest Rectangle in Histogram.cpp │ │ ├── Min Stack.cpp │ │ ├── Next Greater Element I.cpp │ │ ├── Online Stock Span.cpp │ │ ├── Remove All Adjacent Duplicates In String.cpp │ │ ├── Remove All Adjacent Duplicates in String II.cpp │ │ ├── Reverse First K elements of Queue.cpp │ │ └── Valid Parentheses.cpp │ ├── string/ │ │ ├── Find the Index of the First Occurrence in a String.cpp │ │ ├── Gas Station.cpp │ │ └── Maximum Ice Cream Bars.cpp │ └── sum of numbers in string.cpp ├── README.md ├── STL/ │ ├── Array_Algorithms_in_stl.cpp │ ├── Binary search in STL.cpp │ ├── List_in_STL.cpp │ ├── Queue_in_STL.cpp │ ├── Vectors_Functions_in_STL.cpp │ ├── What is STL.cpp │ ├── deque_in_STL.cpp │ ├── pair_in_STL.cpp │ ├── priority Queue in STL.cpp │ ├── sort_in_STL.cpp │ └── stack in STL data structure.cpp ├── Templates_in_c++.cpp ├── Tree/ │ ├── Binary seacrh tree │ ├── Binary_tree.cpp │ ├── Code of Deletion of Node in BST.cpp │ ├── Code of Inorder Traversal.cpp │ ├── Insertion in BST.cpp │ ├── code of Hashing in C++.cpp │ └── code of preorer and Postorder traversal.cpp ├── chef and Icecream.cpp ├── chef and string.cpp └── map_in_c++ ================================================ FILE CONTENTS ================================================ ================================================ FILE: 35_hacker_two_strings.cpp ================================================ // // main.cpp // Lecture 34 // // Created by Prince Kumar on 17/04/19. // Copyright © 2019 Prince Kumar. All rights reserved. // // HACKER EARTH // --- ** Problems on Two Strings ** --- // #include using namespace std; int main() { int T; cin>>T; while(T--) { string s1,s2; cin>>s1>>s2; // declare array for s1 and s2; // for s1 int a[26]={0}; // for s2 int b[26]={0}; // length of string int k = (int)s1.size(); for(int i=0;i using namespace std; int main() { int T; cin>>T; while(T--) { int n; cin>>n; // lenght of string string s; cin>>s; // 1st step of encoding if(n%2==0) { // even for(int i=0;i 0 to 5 { char z = s[i+1]; // z='h' s[i+1] = s[i] ; // s[i]=z; } } else { // odd for(int i=0;i 98 //int index = s[i]-97; int index = c-97; // 1 int req = 25-index; // 24 // range 97 to 122 req = req + 97; char y = (char)req; // real ASCII code cout< using namespace std; int main() { int T; cin>>T; while(T--) { string s1,s2; cin>>s1>>s2; int a[3]={0}; // b count for(int i=0;i<3;i++) // 'b' present or not { if(s1[i]=='b' || s2[i]=='b') a[i]=1; } int b_count=0; for(int i=0;i<3;i++) { if(a[i]==1) b_count++; } if(b_count<=1) cout<<"no"< using namespace std; int main() { int T; cin>>T; while(T--) { int b; cin>>b; if(b==1 || b==2 ||b==3) cout<<"0"< #include #include using namespace std; int main() { int T;cin>>T; while(T--) { int n ; cin>>n; vector v; for(int i=0;i>v[i]; int x; cin>>x; v.push_back(x); } sort(v.begin(),v.end()); // sort vector res; for(int i=0;i #include using namespace std; int main() { int T;cin>>T; while(T--) { int n; cin>>n; int a[n] ; // for ALICE int b[n] ; // for BOB for(int i=0;i>a[i]; } for(int i=0;i>b[i]; } // sorting in ARRAY sort(a,a+n); sort(b,b+n); int suma =0; int sumb = 0; for(int i=0;i using namespace std; int main() { int T; cin>>T; while(T--) { int n; cin>>n; // numbering 1 to n int len[n+1]; // length of finger int glov [n+1]; // lenght of sheath for(int i=1;i>len[i]; } for(int i=1;i>glov[i]; } // front int front=0; for(int i=1;i 8+1-1 = 8 back++; // i=2 --> 8+1-2 =7 } if(front==n && back==n) { cout<<"both"< using namespace std; int main() { int T; cin>>T; while(T--){ int n,k; cin>>n>>k; int a[n]; // no. of girls per km for(int i=0;i>a[i]; } // we get values of girls int max=0; for(int i=0;i<=n-k;i++) { int sum=0; for(int j=i;j using namespace std; int main() { int T;cin>>T; while(T--) { int n; cin>>n; string f[n]; string l[n]; for(int i=0;i>f[i]>>l[i]; // first name and last name } int a[n]; for(int i=0;i to 0 for(int i=0;i #include #include using namespace std; int main() { int T;cin>>T; while(T--) { int n;cin>>n; int bowl[26]={0}; for(int i=0;i>s; for(int j=0;j v; v.push_back(bowl[2]/2); // for 'c' v.push_back(bowl[3]/1); // for 'd' v.push_back(bowl[4]/2); // for 'e' v.push_back(bowl[5]/1); // for 'f' v.push_back(bowl[7]/1); // for 'h' v.push_back(bowl[14]/1); // for 'o' sort(v.begin(),v.end()); cout< #include #include using namespace std; int main() { int T; cin>>T; while(T--) { int n; cin>>n; vector v; for(int i=0;i>x; v.push_back(x); // v.push_back(cin); } int k; cin>>k; // index of jhony unle song // vector use --> indexing start from 0 int val = v[k-1]; // uncle jhony sort(v.begin(),v.end()); for(int i=0;i using namespace std; int main() { int n; cin>>n; // p[i] = how much ml of orange juice int p[n]; for(int i=0;i>x; x = x*10; p[i] = x; } // we calculate total orange juice int tot_orange = 0; for(int i=0;i using namespace std; int main() { int a,b; cin>>a>>b; int x = a; while(a>=b) { x = x + (a/b); a = (a/b) + (a%b); } cout< Code-forces #include using namespace std; int main() { int n,m; cin>>n>>m; if(n>=m) { // 10 1 cout<n) { if(m%2==0) {m/=2; count++;} else { m+=1; count++; } } cout< Vanya and Books #include #include #define ll long long using namespace std; int main() { ll int n; cin>>n; ll int a[13]={0}; for(int i=1;i<13;i++) { a[i]=pow(10,i)-1; } for(int i=2;i<13;i++) { for(int j=1;j<=i-1;j++) { a[i] = a[i]-a[j]; } } // for(int i=1;i<13;i++) // { // cout<=0) { count+=a[i]*i; n=n-a[i]; } else { count+=n*i; break; } } cout< ELEVEN from Codeforces #include #include #define ll long long using namespace std; int main() { ll int a[20]={0}; // store fibonacci series a[0]=a[1]=a[2]=1; for(int i=3;i<20;i++) { a[i]=a[i-1]+a[i-2]; } //cout<>n; int b[n+1]; memset(b,0,sizeof(b)); // 1 represent 'O' // 0 represent 'o' for(int i=1;i<20;i++) { if(a[i]<=n) { b[a[i]]=1; } } for(int i=1;i<=n;i++) { if(b[i]==1) cout<<"O"; else cout<<"o"; } cout< using namespace std; int main() { int a[36]; for(int i=1;i<36;i++) { a[i]=i*i; } // we got a array of perfect square int T;cin>>T; while(T--) { int n;cin>>n; int count=0; while(n!=0) { for(int i=1;i<36;i++) { if(a[i]<=n && a[i+1]>n) { n=n-a[i]; unt++; } } } cout< MUH and Sticks #include using namespace std; int main() { int a[10]={0}; for(int i=1;i<=6;i++) { int x; cin>>x; a[x]++; } int leg =0; int leg_value=0; for(int i=1;i<=9;i++) { if(a[i]>=4) { leg=1; leg_value=i; a[i]=a[i]-4; break; } } int body=0; int body_value=0; for(int i=1;i<=9;i++) { if(a[i]>=1) { body=1; body_value=i; a[i]=a[i]-1; break; } } int head=0; int head_value=0; for(int i=1;i<=9;i++) { if(a[i]>=1) { head=1; head_value=i; a[i]=a[i]-1; break; } } // we got leg leg_value / body body_value / head head_value if(leg==1 && body==1 && head==1) { if(leg_value!=head_value && leg_value!=body_value && head_value!=body_value) cout<<"Bear"< #include #include #include using namespace std; int main() { cout<<"Enter number of elemnets in array : "<>n; cout<<"Enter the size of subset : "<>k; int a[n]; cout<<"Enter the numbers : "<>a[i]; } for(int i=1;i v; int x=i; // x=8 while(x>0) { int z = x%2; // 0 0 0 1 v.push_back(z); x=x/2; // 4 2 1 0 } int p = n- (int)v.size(); for(int j=1;j<=p;j++) { v.push_back(0); } reverse(v.begin(), v.end()); int count=0; for(int i=0;i #include using namespace std; int main() { int T; cin>>T; while(T--) { long long int x; cin>>x; long long int z = log2((long double)x); if(z==0) cout<<"0"< #include #include #define ll long long using namespace std; ll int gcd(ll int a, ll int b) { if(b==0) return a; else return gcd(b,a%b); } void nCr(int n, int r) { // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... long long p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) r = n - r; if (r != 0) { while (r) { p *= n; k *= r; // gcd of p, k long long m = gcd(p, k); // dividing by gcd, to simplify product // division by their gcd saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else p = 1; // if our approach is correct p = ans and k =1 cout << p << endl; } int main() { int T; cin>>T; while(T--) { vector v; int n,k;cin>>n>>k; for(int i=0;i>x; v.push_back(x); } sort(v.begin(),v.end()); int last_index_of_k = v[k-1]; int count=0; for(int i=0;i A-Books --- #include using namespace std; int main() { int T; cin>>T; while(T--) { int n; cin>>n; int a[n]; int b[1000001]={0}; // in b[] we store last index of elements for(int i=0;iindex { int x; cin>>x; a[i]=x; b[x]=i; // cin>>a[i]; // b[a[i]]=i; } for(int i=0;i using namespace std; int main() { int T; cin>>T; while(T--) { int n; cin>>n; int a[n+1]; for(int i=1;i<=n;i++){cin>>a[i];} // we have now prices on respective days int count=1; for(int i=2;i<=n;i++) { int price = a[i]; if(i==2) { if(price #include #include #include #define ll long long using namespace std; int main() { ll int T; cin>>T; while(T--) { ll int n,m,q;cin>>n>>m>>q; ll int a[n+1]; memset(a,0,sizeof(a)); // row ll int c[m+1]; memset(c,0,sizeof(c)); // column for(ll int i=0;i>a1>>a2; a[a1]++; c[a2]++; } ll int odd=0,even=0,a_zero=0; for(ll int i=1;i<=n;i++) {// row if(a[i]>0) { if(a[i]%2!=0) odd++; else even++; } else a_zero++; } // for column ll int count=0; for(ll int i=1;i<=m;i++) { if(c[i]>0) { if(c[i]%2!=0) { count+=even+a_zero; } else { // even count+=odd; } } else count+=odd; } cout< #include #include using namespace std; int main(){ cout<<"Enter The size of Vector : "<>n; vector v; v.push_back(0); for(int i=0;i>x; v.push_back(x); } // check conditions int k = (int)v.size() - 1; if(v[k]<9){ v[k]+=1; // v[k] = v[k] + 1; }else{ while(v[k]==9){ v[k]=0; k= k-1; } v[k]= v[k]+1; } // Print the result // we have to omit the leading zero's int s = 0; for(int i=0;i<(int)v.size() ;i++){ if(v[i]!=0){ s=i; // here we store index break; } } for (int i=s;i<(int)v.size();i++){ cout< using namespace std; int main(){ int T; cin>>T; while(T--){ int n, k; cin>>n>>k; int prev_amt=0; int ori_amt=0; // 2 3 4 7 10 5 for(int i=0;i>x; // x = 2 prev_amt+=x; // profit initially prev_Amt = 2 if(x>k){ x=k; } // x= 5 ori_amt+=x; // ori_amt = 2 } cout<>a[i]; // prev_amt+=a[i]; // } // for(int i=0;ik){ // a[i]=k; // } // ori_amt+=a[i]; // } } } ================================================ FILE: Data Structures/Add a node at the Middle of linked list.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 23/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** INSERTION OF NODE IN LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; /* ----- Linked list Node ------ */ struct node{ int data; node *next; }; /* ------- Print the Linked List -------*/ void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in linked list is : "< data = newData; newNode -> next = *head_ref; *head_ref = newNode; } /* ------ INSERTION OF NODE AT MIDDLE OF LINKED LIST --------*/ void insertAfter(node *prev_node , int newData){ node *newNode = new node(); newNode->data = newData; newNode->next = prev_node->next; prev_node->next = newNode; } int main(){ node *head = NULL; push(&head , 5); push(&head , 7); push(&head , -3); // -3 7 5 insertAfter(head->next,79); printList(head); } ================================================ FILE: Data Structures/Add a node at the end of linked list.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 24/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** INSERTION OF NODE IN LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; /* ----- Linked list Node ------ */ struct node{ int data; node *next; }; /* ------- Print the Linked List -------*/ void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in linked list is : "< data = newData; newNode -> next = *head_ref; *head_ref = newNode; } /* ------ INSERTION OF NODE AT MIDDLE OF LINKED LIST --------*/ void insertAfter(node *prev_node , int newData){ node *newNode = new node(); newNode->data = newData; newNode->next = prev_node->next; prev_node->next = newNode; } /* ------ INSERTION OF NODE AT END OF LINKED LIST --------*/ void append(node **head_ref, int newData){ node *newNode = new node(); newNode->data = newData; newNode->next = NULL; node *last = *head_ref; if(*head_ref == NULL){ *head_ref = newNode; return; } while(last->next != NULL){ last = last->next; } last->next = newNode; return; } int main(){ node *head = NULL; push(&head , 5); push(&head , 7); push(&head , -3); // -3 7 5 insertAfter(head->next,79); // -3 7 79 5 append(&head, 90); printList(head); } ================================================ FILE: Data Structures/Add a node at the front of linked list.cpp ================================================ // DATA STRUCTURES.cpp // // Created by Prince Kumar on 22/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** INSERTION OF NODE IN LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; /* ----- Linked list Node ------ */ struct node{ int data; node *next; }; /* ------- Print the Linked List -------*/ void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in linked list is : "< data = newData; // newNode -> next = head; // head = newNode; // return head; //} void push(node **head_ref , int newData){ node *newNode = new node(); newNode -> data = newData; newNode -> next = *head_ref; *head_ref = newNode; } int main(){ node *head = NULL; push(&head , 5); push(&head , 7); push(&head , -3); printList(head); } ================================================ FILE: Data Structures/Array_in_data_structures.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 08/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** ARRAYS in C++ **--- #include using namespace std; int main(){ //1st method // int arr[5]; // arr[0] = 4; // arr[1] = 3; // arr[2] = -10; // arr[3] = 8; // arr[4] = -6; // 2nd method int arr[5] = {4 , 3, -10, 8,-9}; int arr1[] = {4 , 3, -10, 8,7 , 4, 2 , 11}; //int arr2[]; cout< using namespace std; //Linked list Node struct node{ int data; node *next; }; void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in linked list is : "<data<next; // this changes in temp while(temp != first){ cout<data<next; } } } int main(){ // /* Make A linked List */ node *head = new node(); node *second = new node(); node *third = new node(); node *four = new node(); node *five = new node(); node *six = new node(); node *seven = new node(); node *eight = new node(); node *nine = new node(); head -> data = 5; head -> next = second; second->data = 1; second ->next = third; third -> data = -3; third ->next = four; four -> data = 11; four -> next = five; five->data = 10; five ->next = six; six -> data = 2; six ->next = seven; seven -> data = 7; seven -> next = eight; eight->data = 9; eight ->next = nine; nine -> data = 18; nine ->next = head; printCircularList(four); } ================================================ FILE: Data Structures/Delete a node of a linked list.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 25/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** DELETION OF NODE IN LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; /* ----- Linked list Node ------ */ struct node{ int data; node *next; }; /* ------- Print the Linked List -------*/ void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in linked list is : "< data = newData; newNode -> next = *head_ref; *head_ref = newNode; } /* ------ DELETION OF NODE IN LINKED LIST --------*/ void deleteNode(node **head_ref , int key){ // initialise prev and temp node *prev, *temp; //store head to the temp; temp = *head_ref; //if key is present in head if(temp!=NULL && temp->data == key){ *head_ref = temp->next; free(temp); return; } //we traverse the linkedlist and keep track og prev node // because we have to perform prev->next while(temp!=NULL && temp->data!=key){ prev=temp; temp = temp->next; } // we travserse whole linked list and we didn't got the key if(temp==NULL) return; // but, if we found the key prev->next = temp->next; free(temp); } int main(){ node *head = NULL; push(&head , 5); push(&head , 7); push(&head , -3); push(&head , 2); push(&head , 9); printList(head); deleteNode(&head, 2); printList(head); } ================================================ FILE: Data Structures/Doubly Linked list.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 27/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** INSETION OF NODE IN DOUBLY LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; /* ----- Doubly Linked list Node ------ */ struct node{ int data; node *next; node *prev; }; /*------- Print the Douubly Linked List ------- */ void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in Doubly linked list is : "<data= new_data; new_node->next = *head_ref; new_node->prev = NULL; if((*head_ref) != NULL){ (*head_ref)->prev = new_node; } (*head_ref) = new_node; } int main(){ node *head= NULL; push(&head, 4); push(&head, 11); push(&head, -3); // -3 11 4 printList(head); } ================================================ FILE: Data Structures/Find the middle of a given linked list.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 20/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; //Linked list Node struct node{ int data; node *next; }; void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in linked list is : "<next!=NULL){ fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } cout<<"Middle Element is : "<data< data = 5; head -> next = second; second->data = 1; second ->next = third; third -> data = -3; third ->next = four; four -> data = 11; four -> next = five; five->data = 10; five ->next = six; six -> data = 2; six ->next = seven; seven -> data = 7; seven -> next = eight; eight->data = 9; eight ->next = nine; nine -> data = 18; nine ->next = NULL; //printList(head); // node *start = head; // for(int i=0;i<5;i++){ // cout<data<next; // } printMiddleElement(head); } ================================================ FILE: Data Structures/Insert Node at the End of Doubly Linked List.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 30/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** INSETION OF NODE IN DOUBLY LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; /* ----- Doubly Linked list Node ------ */ struct node{ int data; node *next; node *prev; }; /*------- Print the Doubly Linked List ------- */ void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in Doubly linked list is : "<data= new_data; new_node->next = *head_ref; new_node->prev = NULL; if((*head_ref) != NULL){ (*head_ref)->prev = new_node; } (*head_ref) = new_node; } /*------- Insert node in Middle of Doubly Linked List ------- */ void insertAfter(node *prev_node, int new_data){ if(prev_node == NULL){ cout<<"given prev node can't be null"<data = new_data; new_node->next = prev_node->next; prev_node->next = new_node; new_node->prev = prev_node; if(new_node->next != NULL){ new_node->next->prev = new_node; } } /*------- Insert node in End of Doubly Linked List ------- */ void append(node **head_ref, int new_data){ node *new_node = new node(); new_node->data = new_data; new_node->next = NULL; node *last = *head_ref; //head if(*head_ref == NULL){ new_node->prev = NULL; *head_ref = new_node; return; } while(last->next != NULL){ last = last->next; } last->next = new_node; new_node->prev = last; return; } int main(){ node *head= NULL; push(&head, 4); push(&head, 11); push(&head, -3); // -3 11 4 insertAfter(head->next, 10); // -3 11 10 4 append(&head, 9); // -3 11 10 4 9 printList(head); } ================================================ FILE: Data Structures/Insert Node in Middle of Doubly Linkedlist.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 30/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** INSETION OF NODE IN DOUBLY LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; /* ----- Doubly Linked list Node ------ */ struct node{ int data; node *next; node *prev; }; /*------- Print the Doubly Linked List ------- */ void printList (node *n){ int count=0; while(n!=NULL){ cout<data<next; count++; } cout<<"No. of element in Doubly linked list is : "<data= new_data; new_node->next = *head_ref; new_node->prev = NULL; if((*head_ref) != NULL){ (*head_ref)->prev = new_node; } (*head_ref) = new_node; } /*------- Insert node in Middle of Doubly Linked List ------- */ void insertAfter(node *prev_node, int new_data){ if(prev_node == NULL){ cout<<"given prev. node can't be null"<data = new_data; new_node->next = prev_node->next; prev_node->next = new_node; new_node->prev = prev_node; if(new_node->next != NULL){ new_node->next->prev = new_node; } } int main(){ node *head= NULL; push(&head, 4); push(&head, 11); push(&head, -3); // -3 11 4 insertAfter(head->next, 10); // -3 11 10 4 printList(head); } ================================================ FILE: Data Structures/LinkedList_Code_Practice.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 15/05/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** LINKED LIST in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; //Linked list Node struct node{ int data; node *next; }; void printList (node *n){ while(n!=NULL){ cout<data<next; } } int main(){ node *head = new node(); node *second = new node(); node *third = new node(); head -> data = 5; head -> next = second; second->data = 1; second ->next = third; third -> data = 3; third ->next = NULL; printList(head); } ================================================ FILE: Data Structures/Vectors_in_STL_data_structure.cpp ================================================ // // DATA STRUCTURES.cpp // // Created by Prince Kumar on 3/06/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** STANDARD TEMPLATE LIBRARY (STL) in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include #include using namespace std; int main(){ vector v; /* 3 10 7*/ vector :: iterator it; v.push_back(3); v.push_back(10); v.push_back(7); auto a = v.begin(); // it provides iterator which points first element of vector cout<<"first element : "< using namespace std; struct student{ int roll; string name; int age; void studentDetails(){ cout<<"name is : "< #include #include using namespace std; int main(){ cout<<"Enter the size of Array : "<>n; int a[n]; for(int i=0;i>a[i]; } int max_so_far = a[0], max_ending_here =0; // It store sum int start = 0 , end=0 , s=0; // it store index for(int i=0;i #include #include using namespace std; int main() { vector v; v.push_back(10); v.push_back(23); v.push_back(22); v.push_back(78); v.push_back(98); // iterators // pointers // sort // ascending to descending... sort(v.begin(),v.end()); // important v.pop_back(); int k = (int)v.size(); // k=5 for(int i=0;i #include using namespace std; int main() { int T; cin>>T; while(T--) { int n; cin>>n; // int n= 7929024 ostringstream str1; str1< using namespace std; int main() { int T; cin>>T; while(T--) { int a,b,c,d; cin>>a>>b>>c>>d; if((a==c && b==d)|| (a==b && c==d)||(a==d && c==b)) cout<<"YES"< using namespace std; int main() { int T;cin>>T; while(T--) { int n; cin>>n; int k ; cin>>k; string s; cin>>s; int cap=0; int small=0; for(int i=0;i=65 && p<=90) cap++; else small++; } // we have no. of small and capital letters. if(cap==small) { if(k>=cap) cout<<"both"<cap) { if(k>=small) cout<<"both"<small) { if(k>=cap) cout<<"both"< using namespace std; int main() { string s; cin>>s; int a[26]={0}; // we put the value 0 in all the blocks int len = (int)s.size(); // length of string for(int i=0;i>n; for(int i=0;i>k; // k--> words for(int j=0;j0) cout<<"No"< #include using namespace std; int main() { string s; //cin>>s; getline(cin,s); cout<>word) { cout< #include using namespace std; int main() { // problem 1. /*int a[10]={0}; cout<>n; int a[n]={0}; cout<>n; int a[n]; // block name --- a memset(a,0 ,sizeof(a)); // value --> 0 & -1 cout< using namespace std; int main() { int n; cout<<"Enter value of n upto which you want to print prime number : "<>n; for(int i=2;i<=n;i++) /// 10 { int x = i; // 10 int count=0; for(int j=1;j<=x;j++) // j=1 to j=10 { if(x%j==0) // 10%2==0 count++; } if(count==2) cout< #include using namespace std; void seive( int n) { // create boolean array bool prime[n+1]; memset(prime, true ,sizeof(prime)); for(int p=2;p*p<=n;p++) { // if prime[p] --> false --> it is not prime if(prime[p]==true) { for(int i=p*p;i<=n;i=i+p) { prime[i]=false; } } } // print prime numbers for(int j=2;j<=n;j++) { if(prime[j]==true) cout<>n; seive(n); } ================================================ FILE: Lecture - 25.cpp ================================================ // // main.cpp // hbhbhbs // // Created by Prince Kumar on 29/03/19. // Copyright © 2019 Prince Kumar. All rights reserved. // // ** --- Euclidean Algorithm -- for finding GCD of 2 number **// #include using namespace std; int gcd(int a, int b) { if(a==0) return b; else return gcd(b%a ,a); } int main() { int a,b; cout<<"Enter two numbers "<>a>>b; int result = gcd(a,b); cout< using namespace std; int main() { int T; cin>>T; while(T--) { string s; cin>>s; int count=0; for(int i=0;i using namespace std; int main() { int T; cin>>T; while(T--) { int x; cin>>x; if(x%10==0) cout<<"0"< using namespace std; int main() { cout<<"Enter the number "<>x; int a = x & (x-1); if(a==0) cout<<"Number is the power of 2"< using namespace std; int main() { cout<<"Enter the number :"<>n; int x = n & (n-1); int count=1; while(x!=0) { count++; x = x & (x-1); } cout<>n; n = n & (n-1); int count=1; while(n!=0) { count++; n = n & (n-1); } */ } ================================================ FILE: Lecture - 33.cpp ================================================ // // main.cpp // lecture 33 // // Created by Prince Kumar on 05/04/19. // Copyright © 2019 Prince Kumar. All rights reserved. // -- ** code of --> Check the ith bit is set in the binary form of given number ** --- // #include using namespace std; int main() { cout<<"Enter the number : "<>n; bool a = n & ( 1<<3); if(a==true) cout<<"Yes, bit is set"< Train Partner -- ANKTRAIN * -// #include using namespace std; int main() { int T; cin>>T; while(T--) { int n; // berth number cin>>n; if(n%8==0) {cout< 9){ num = addDigitsHelper(num); } return num; } }; ================================================ FILE: Leetcode/Add Two Numbers Leetcode Solutions in Linkedlist.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * https://leetcode.com/problems/add-two-numbers/ * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *ans = new ListNode(0); ListNode *p = l1, *q=l2, *curr = ans; int carry=0; while(p!=NULL || q!=NULL){ int x = (p!=NULL) ? p->val : 0; int y = (q!=NULL) ? q->val : 0; int sum = carry + x+ y; carry = sum/10; curr->next = new ListNode(sum%10); curr = curr->next; if(p!=NULL) p = p->next; if(q!=NULL) q = q->next; } if(carry>0){ curr->next = new ListNode(carry); } return ans->next; } }; ================================================ FILE: Leetcode/Binary Search leetcode Solution.cpp ================================================ // https://leetcode.com/problems/binary-search/ class Solution { public: int search(vector& nums, int target) { int n = (int)nums.size(); int low = 0; int high = n-1; while(low<=high){ int mid = (low+high)/2; if(nums[mid] == target){ return mid; }else if(nums[mid] < target ){ low = mid+1; }else{ high = mid-1; } } return -1; } }; ================================================ FILE: Leetcode/Boolean Matrix.cpp ================================================ // Boolean Matrix: https://practice.geeksforgeeks.org/problems/boolean-matrix-problem-1587115620/1# void booleanMatrix(vector > &matrix) { // code here int row = matrix.size(); int col = matrix[0].size(); bool arr_row[row]; fill(arr_row, arr_row+row, false); bool arr_col[col]; fill(arr_col, arr_col+col, false); for(int i=0;i& words) { unordered_set s; for(auto x: allowed) s.insert(x); int count = 0; for(auto word: words){ bool status = true; for(int i=0; i>& graph, vector>& ans, vector&path, int curr){ path.push_back(curr); if(curr == graph.size()-1){ ans.push_back(path); } else{ for(auto x: graph[curr]){ dfs(graph, ans, path, x); } } path.pop_back(); } vector> allPathsSourceTarget(vector>& graph) { vector> ans; vectorpath; dfs(graph, ans, path, 0); return ans; } }; ================================================ FILE: Leetcode/Graph/Course Schedule.cpp ================================================ // https://leetcode.com/problems/course-schedule/ class Solution { public: bool DFSRec(int s, vector&visited, vector&currVisited, vectoradj[]){ visited[s] = true; currVisited[s] = true; vectordata = adj[s]; for(auto x: data){ if(!visited[x]){ if(DFSRec(x, visited, currVisited, adj)){ return true; } } else if(visited[x] && currVisited[x]){ return true; } } currVisited[s] = false; return false; } bool canFinish(int numCourses, vector>& prerequisites) { int n = numCourses; vectorvisited(n, false), currVisited(n, false); vectoradj[n]; for(auto x: prerequisites){ vectordata = x; int a = data[0]; int b = data[1]; adj[a].push_back(b); } for(int i=0; i&visited, vector&currVisited, vector adj[]){ visited[s] = true; currVisited[s] = true; for(auto x: adj[s]){ if(!visited[x]){ if(cycle(x, visited, currVisited, adj)) return true; } else if(visited[x] == true && currVisited[x] == true){ return true; } } currVisited[s] = false; return false; } bool isCyclic(int V, vector adj[]) { // code here vectorvisited(V, false), currVisited(V, false); for(int i=0; i&visited, vector&dfsVisited, vector>& graph, vector &present_cycle){ visited[s] = true; dfsVisited[s] = true; vectordata = graph[s]; for(auto x: data){ if(!visited[x]){ if(DFSRec(x, visited, dfsVisited, graph, present_cycle)){ return present_cycle[s] = true; } } else if(visited[x] && dfsVisited[x]){ return present_cycle[s] = true; } } dfsVisited[s] = false; return false; } vector eventualSafeNodes(vector>& graph) { vector ans; int n = graph.size(); vectorvisited(n, false), dfsVisited(n, false); vector present_cycle(n, false); for(int i=0; i>& edges, int start, int end) { unordered_map> umap; for(auto x: edges){ vectortemp = x; int u = temp[0]; int v = temp[1]; umap[u].push_back(v); umap[v].push_back(u); } vectorvisited(n+1, false); queueq; q.push(start); visited[start] = true; while(!q.empty()){ int v = q.front(); q.pop(); vectortemp = umap[v]; for(int i=0; i>& trust) { vectordata(n+1, 0); for(auto x: trust) { data[x[0]]--; data[x[1]]++; } for(int i=1; i<=n; i++){ int x = data[i]; if(x == n-1) return i; } return -1; } }; ================================================ FILE: Leetcode/Graph/Flood Fill.cpp ================================================ // https://leetcode.com/problems/flood-fill/ class Solution { public: bool isValid(vector>& image, int i, int j, int n, int m , int color){ if(i>=0 && i=0 && j>& image, int i, int j, int n, int m , int color, int newColor){ image[i][j] = newColor; if(isValid(image, i+1, j, n, m , color)) floodFillRec(image, i+1, j, n, m , color, newColor); if(isValid(image, i-1, j, n, m , color)) floodFillRec(image, i-1, j, n, m , color, newColor); if(isValid(image, i, j+1, n, m , color)) floodFillRec(image, i, j+1, n, m , color, newColor); if(isValid(image, i, j-1, n, m , color)) floodFillRec(image, i, j-1, n, m , color, newColor); } vector> floodFill(vector>& image, int sr, int sc, int newColor) { int n = image.size(); int m = image[0].size(); int color = image[sr][sc]; if(color == newColor) return image; floodFillRec(image, sr, sc, n, m, color, newColor); return image; } }; ================================================ FILE: Leetcode/Graph/Keys and Rooms.cpp ================================================ // https://leetcode.com/problems/keys-and-rooms/ class Solution { public: bool canVisitAllRooms(vector>& rooms) { int n = rooms.size(); vectorvisited(n, false); queueq; q.push(0); visited[0] = true; while(!q.empty()){ int room = q.front(); q.pop(); for(auto key : rooms[room]){ if(!visited[key]){ visited[key] = true; q.push(key); } } } for(auto x: visited){ if(!x) return x; } return true; } }; ================================================ FILE: Leetcode/Graph/Max Area of Island.cpp ================================================ // https://leetcode.com/problems/max-area-of-island/ class Solution { public: bool isValid(int i, int j, int n, int m, vector>& grid){ if(i>=0 && i=0 && j>& grid, int i, int j, int n, int m, int &area){ area++; grid[i][j] = 0; if(isValid(i+1, j, n, m, grid)){ dfs(grid, i+1, j, n, m, area); } if(isValid(i-1, j, n, m, grid)){ dfs(grid, i-1, j, n, m, area); } if(isValid(i, j+1, n, m, grid)){ dfs(grid, i, j+1, n, m, area); } if(isValid(i, j-1, n, m, grid)){ dfs(grid, i, j-1, n, m, area); } } int maxAreaOfIsland(vector>& grid) { int n = grid.size(); int m = grid[0].size(); int ans = 0; for(int i=0; ivisited; int dfs(vector>&adj, int node, int mycost, vector& hasApple){ if(visited[node]) return 0; visited[node]= true; int childCost = 0; for(auto x: adj[node]){ childCost += dfs(adj, x, 2, hasApple); } if(childCost == 0 && !hasApple[node]) return 0; return childCost + mycost; } int minTime(int n, vector>& edges, vector& hasApple) { vector>adj(n, vector(0, -1)); for(auto x: edges){ adj[x[0]].push_back(x[1]); adj[x[1]].push_back(x[0]); } for(int i=0; i>& grid){ int n = grid.size(); int m = grid[0].size(); int ans = 0; for(int i=0; i>& grid){ if(i>=0 && i=0 && j>& grid){ grid[i][j] = 0; int ax[4] = {1, -1, 0, 0}; int ay[4] = {0, 0, 1, -1}; for(int k=0; k<4; k++){ int nx = i + ax[k]; int ny = j + ay[k]; if(isValid(nx,ny, n, m, grid)){ dfs(nx, ny, n, m, grid); } } } int numEnclaves(vector>& grid) { int n = grid.size(); int m = grid[0].size(); // boundary travers for(int i=0; i>& grid){ if(i>=0 && i=0 && j>& grid){ grid[i][j] = '0'; if(isValid(i+1, j, n, m , grid)) numIslandsRec(i+1, j, n, m, grid); if(isValid(i-1, j, n, m , grid)) numIslandsRec(i-1, j, n, m, grid); if(isValid(i, j+1, n, m , grid)) numIslandsRec(i, j+1, n, m, grid); if(isValid(i, j-1, n, m , grid)) numIslandsRec(i, j-1, n, m, grid); } int numIslands(vector>& grid) { int n = grid.size(); int m = grid[0].size(); int ans = 0; for(int i=0; i>& isConnected, vector&visited){ visited[s] = true; // s = 1 // 0 1 2 3 4 -- index // 1 2 3 4 5 -- city name // 1 1 0 1 0 -- connection vectoradj; for(int i=0; i>& isConnected) { int n = isConnected.size(); vectorvisited(n, false); int count = 0; for(int i=0; i>& grid){ if(i>=0 && i=0 && j>& grid){ grid[i][j] = 1; int ax[4] = {1, -1, 0, 0}; int ay[4] = {0, 0, 1, -1}; for(int k =0; k<4; k++){ int nx = i + ax[k]; int ny = j + ay[k]; if(isValid(nx, ny, n, m, grid)){ dfs(nx, ny, n, m, grid); } } } int closedIsland(vector>& grid) { int n = grid.size(); int m = grid[0].size(); // boundary DFS for(int i=0; i>& grid){ if(i>=0 && i=0 && j>& grid) { int n = grid.size(); int m = grid[0].size(); int fresh = 0, time = 0; queue>q; for(int i=0; ip = q.front(); q.pop(); int x1 = p.first; int y1 = p.second; int ax[4] = { 1, -1, 0, 0}; int ay[4] = { 0, 0 , 1 , -1}; for(int i=0; i<4; i++){ int x = ax[i] + x1; int y = ay[i] + y1; if(isValid(x, y, n, m, grid)){ temp++; grid[x][y] = 2; q.push({x, y}); } } size_q--; } if(temp != 0) time++; } // we checked if any fresh oranges are still there for(int i=0; i>&visited){ if(i>=0 && i=0 && j&KnightPos,vector&TargetPos,int N) { // Code here int n = N; int tx = TargetPos[0]-1, ty = TargetPos[1]-1; int x1 = KnightPos[0]-1, y1 = KnightPos[1]-1; if(x1 == tx && y1 == ty) return 0; vector>visited(n, vector(n, false)); queue>q; q.push({x1, y1}); visited[x1][y1] = true; int ans = 0; while(!q.empty()){ int size = q.size(); ans++; while(size != 0){ pairp = q.front(); q.pop(); int xx = p.first; int yy = p.second; int ax[8] = {1, 1, -1, -1, 2, -2, 2, -2}; int ay[8] = {2, -2, 2, -2, 1, 1, -1, -1}; for(int i=0; i<8; i++){ int nx = xx + ax[i]; int ny = yy + ay[i]; if(nx == tx && ny == ty) return ans; if(isValid(nx, ny, n, visited)){ visited[nx][ny] = true; q.push({nx, ny}); } } size--; } } return ans; } }; ================================================ FILE: Leetcode/Graph/Surrounded Regions.cpp ================================================ // https://leetcode.com/problems/surrounded-regions/ class Solution { public: void convert(vector>& board){ int n = board.size(); int m = board[0].size(); for(int i=0; i>& board){ if(i>=0 && i=0 && j>& board, int i , int j, int n, int m){ board[i][j] = 'B'; if(isValid(i+1, j, n, m, board)){ dfs(board, i+1, j, n, m); } if(isValid(i-1, j, n, m, board)){ dfs(board, i-1, j, n, m); } if(isValid(i, j+1, n, m, board)){ dfs(board, i, j+1, n, m); } if(isValid(i, j-1, n, m, board)){ dfs(board, i, j-1, n, m); } } void solve(vector>& board) { int n = board.size(); int m = board[0].size(); for(int i=0; i top bottom int j =0; if(board[i][j] == 'O'){ dfs(board, i, j, n, m); } j = m-1; // right -> top bootm if(board[i][j] == 'O'){ dfs(board, i, j, n, m); } } for(int j=0; j left right int i =0; if(board[i][j] == 'O'){ dfs(board, i, j, n, m); } i = n-1; // bottom -> left right if(board[i][j] == 'O'){ dfs(board, i, j, n, m); } } convert(board); } }; ================================================ FILE: Leetcode/Graph/Time Needed to Inform All Employees.cpp ================================================ // https://leetcode.com/problems/time-needed-to-inform-all-employees/ class Solution { public: unordered_map>umap; int ans =0 , mx= 0; void dfs(int manager, vector& informTime){ mx = max(mx, ans); for(auto employee : umap[manager]){ ans += informTime[manager]; dfs(employee, informTime); ans -= informTime[manager]; } } int numOfMinutes(int n, int headID, vector& manager, vector& informTime) { // Fill umap for(int i=0; i topoSort(int V, vector adj[]) { // code here vector ans; queueq; vector indegree(V, 0); for(int i=0; i data = adj[i]; for(auto x: data){ indegree[x]++; } } for(int i=0; i using namespace std; // } Driver Code Ends class Solution { public: //Function to return list containing vertices in Topological order. void DFSRec(int s, stack&st, vector&visited, vector adj[]){ visited[s] = true; vectordata = adj[s]; for(auto v: data){ if(!visited[v]){ DFSRec(v, st, visited, adj); } } st.push(s); } vector topoSort(int V, vector adj[]) { // code here stackst; vectorvisited(V, false); for(int i=0; ians; while(!st.empty()){ int x = st.top(); st.pop(); ans.push_back(x); } return ans; } }; ================================================ FILE: Leetcode/Hashing/Check if two arrays are equal or not.cpp ================================================ // Question Link: https://practice.geeksforgeeks.org/problems/check-if-two-arrays-are-equal-or-not3847/1 class Solution{ public: //Function to check if two arrays are equal or not. bool check(vector A, vector B, int n) { //code here unordered_mapumap; for(int i=0;isecond>0) itr->second--; else return false; }else return false; } return true; } }; ================================================ FILE: Leetcode/Hashing/Custom Sort String.cpp ================================================ // https://leetcode.com/problems/custom-sort-string/ class Solution { public: string customSortString(string order, string str) { mapmp; string ans = ""; for(auto x: str) mp[x]++; for(auto x: order){ if(mp.find(x)!=mp.end()){ auto temp = mp.find(x); int count = temp->second; // c-> 5 || ccccc string s(count, x); ans+=s; mp.erase(x); } } for(auto x: mp){ string s(x.second, x.first); ans+=s; } return ans; } }; ================================================ FILE: Leetcode/Hashing/First Repeating Element.cpp ================================================ // Question Link: https://practice.geeksforgeeks.org/problems/first-repeating-element4018/1 class Solution{ public: //Function to return the position of the first repeating element. int firstRepeated(int arr[], int n) { //code here unordered_map umap; for(int i=0;isecond; if(val >1) return i+1; } return -1; } }; ================================================ FILE: Leetcode/Hashing/Group Anagrams.cpp ================================================ // https://leetcode.com/problems/group-anagrams/ class Solution { public: vector> groupAnagrams(vector& strs) { vector> ans; unordered_map>umap; for(auto x: strs){ string temp = x; sort(x.begin(), x.end()); umap[x].push_back(temp); } for(auto x : umap){ ans.push_back(x.second); } return ans; } }; ================================================ FILE: Leetcode/Hashing/Intersection of two arrays.cpp ================================================ // Question Link: https://practice.geeksforgeeks.org/problems/intersection-of-two-arrays2404/1 int NumberofElementsInIntersection (int a[], int b[], int n, int m ) { // Your code goes here unordered_sets; for(int i=0;i umap; for(int i=0;ifirst; int val = itr->second; int pair = x-key; if(pair==key){ if(val>1) return true; }else{ if(umap.find(pair)!=umap.end()) return true; } } return false; } }; ================================================ FILE: Leetcode/Hashing/LFU Cache.cpp ================================================ /* https://leetcode.com/problems/lfu-cache/ */ class LFUCache { public: int capacity, minFreq; unordered_map>keyVal; unordered_map> freqList; unordered_map::iterator > pos; void updateFreq(int key){ // update the Frequency // -- delete key from curr_freq // -- increment freq // -- insert key in new freq // -- update new pos of key // -- check for minFreq int curr_freq = keyVal[key].second; freqList[curr_freq].erase(pos[key]); keyVal[key].second++; curr_freq = keyVal[key].second; freqList[curr_freq].push_back(key); pos[key] = --freqList[curr_freq].end(); if(freqList[minFreq].empty()){ minFreq++; } } LFUCache(int capacity) { this->capacity = capacity; minFreq = 0; } int get(int key) { if(keyVal.find(key) == keyVal.end()){ return -1; } updateFreq(key); return keyVal[key].first; } void put(int key, int value) { if(capacity == 0) return; if(keyVal.find(key) != keyVal.end()){ // update Case keyVal[key].first = value; updateFreq(key); return; } if(keyVal.size() == capacity){ // Find the LRU; int delKey = freqList[minFreq].front(); keyVal.erase(delKey); pos.erase(delKey); freqList[minFreq].pop_front(); } keyVal[key] = {value, 1}; freqList[1].push_back(key); pos[key] = --freqList[1].end(); minFreq = 1; } }; /** * Your LFUCache object will be instantiated and called as such: * LFUCache* obj = new LFUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */ ================================================ FILE: Leetcode/Hashing/Non-Repeating Element.cpp ================================================ // Question Link: https://practice.geeksforgeeks.org/problems/non-repeating-element3958/1 class Solution{ public: int firstNonRepeating(int arr[], int n) { // Complete the function unordered_map umap; for(int i=0;isecond ==1) return key; } return 0; } }; ================================================ FILE: Leetcode/Hashing/Pairs with Positive Negative values.cpp ================================================ // https://practice.geeksforgeeks.org/problems/pairs-with-positive-negative-values3719/1 class Solution{ public: vector PosNegPair(int a[], int n) { vectorv, ans; mapmp; for(int i=0;i=0 ; i--){ int data = abs(v[i]); if(mp[data]>0){ ans.push_back(v[i]); ans.push_back(data); mp[data]-=1; } } return ans; } }; ================================================ FILE: Leetcode/Hashing/Relative Sort Array.cpp ================================================ // https://leetcode.com/problems/relative-sort-array/ class Solution { public: vector relativeSortArray(vector& arr1, vector& arr2) { vector ans; mapmp; for(auto x: arr1) mp[x]++; for(auto temp : arr2){ if(mp.find(temp)!=mp.end()){ auto x = mp.find(temp); int count = x->second; // 5->2 vectorv(count, temp); // v = 5 5 ans.insert(ans.end(), v.begin(), v.end()); mp.erase(temp); } } for(auto x : mp){ int ele = x.first; int count = x.second; vectorv(count, ele); ans.insert(ans.end(), v.begin(), v.end()); } return ans; } }; ================================================ FILE: Leetcode/Hashing/Sort Array by Increasing Frequency.cpp ================================================ // https://leetcode.com/problems/sort-array-by-increasing-frequency/ class Solution { public: vector frequencySort(vector& nums) { unordered_mapumap; for(auto x: nums){ umap[x]++; } sort(nums.begin(), nums.end() , [&](int a , int b) { return umap[a] != umap[b] ? umap[a] < umap[b] : a > b ; } ); return nums; } }; ================================================ FILE: Leetcode/Hashing/Subarray with 0 sum.cpp ================================================ // Link: https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1 class Solution{ public: //Complete this function //Function to check whether there is a subarray present with 0-sum or not. bool subArrayExists(int arr[], int n) { //Your code here unordered_sets; int pre_sum=0; for(int i=0;i winner(string arr[],int n) { // Your code here // Return the string containing the name and an integer // representing the number of votes the winning candidate got unordered_mapumap; for(int i=0;ifirst; int val = itr->second; if(val>max_vote){ max_vote = val; name = key; } else if(val == max_vote){ if(key ans; ans.push_back(name); string temp = to_string(max_vote); ans.push_back(temp); return ans; } }; ================================================ FILE: Leetcode/Hashing/unordered_map.cpp ================================================ #include #include using namespace std; int main(){ unordered_map umap; umap["prince"] = 44; umap["gfg"] = 56; umap["helloworld"] = 90; for(auto x : umap) cout<first<second<first<<" "<second< umaped; for(int i=0;i<15;i++){ int key = arr[i]; umaped[key]++; } for(auto itr = umaped.begin() ; itr!=umaped.end() ; itr++) cout<first<<" "<second< #include using namespace std; int main(){ unordered_set s; s.insert(10); s.insert(5); s.insert(15); s.insert(20); for(auto it = s.begin() ; it!=s.end() ;it++) cout<<(*it)< > &matrix) { // code here int row = matrix.size(); int col = matrix[0].size(); for(int i=0;i<(row/2);i++){ for(int j=0;j using namespace std; // Function to find majority element in the array int majorityElement(int arr[], int n) { int count=1; int res=0; for(int i=1; i> t; while(t--){ int n; cin >> n; int arr[n]; for(int i = 0;i> arr[i]; } cout << majorityElement(arr, n) << endl; } return 0; } ================================================ FILE: Leetcode/Median of Two sorted arrays.cpp ================================================ // https://practice.geeksforgeeks.org/problems/median-of-two-sorted-arrays1618/1/?track=DSASP-Searching&batchId=154 // arr : given array with size n // brr : given array with size m int findMedian(int arr[], int n, int brr[], int m){ // code here int begin1 = 0 ; int end1 = n; while(begin1<=end1){ int i1 = (begin1+end1)/2; int i2 = (n+m+1)/2 - i1; int min1 = (i1==n) ? INT_MAX : arr[i1]; int max1 = (i1==0) ? INT_MIN : arr[i1-1]; int min2 = (i2==m) ? INT_MAX : brr[i2]; int max2 = (i2==0) ? INT_MIN : brr[i2-1]; if((max1<=min2) && (max2<=min1) ){ if((n+m)%2==0){ return ((double) (max(max1,max2) + min(min1, min2)) / 2) ; }else{ return ((double) max(max1, max2)); } } else if(max1>min2){ end1 = i1-1; }else{ begin1 = i1+1; } } } ================================================ FILE: Leetcode/Middle of the Linked List Leetcode.cpp ================================================ // https://leetcode.com/problems/middle-of-the-linked-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int size(ListNode* head){ int n=0; while(head != NULL){ n++; head = head->next; } return n; } ListNode* middleNode(ListNode* head) { int n = size(head); n = (n/2) + 1; int i=0; while(head != NULL){ i++; if(i==n) return head; head = head->next; } return head; } }; ================================================ FILE: Leetcode/Middle of the Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* middleNode(ListNode* head) { vector v = {head}; while(v.back()->next!=NULL){ v.push_back(v.back()->next); } return v[(int)v.size()/2]; // int count=0; // ListNode* temp = head; // while(temp!=NULL){ // count++; // temp = temp->next; // } // count/=2; // int i=0; // ListNode* ans; // while(i<=count){ // ans = head; // head = head->next; // i++; // } // return ans; } }; ================================================ FILE: Leetcode/Move Zeroes.cpp ================================================ // https://leetcode.com/problems/move-zeroes/ class Solution { public: void moveZeroes(vector& nums) { int n = nums.size(); int j=0; for(int i=0; i > multiplyMatrix( const vector >& A, const vector >& B) { // code here int n1,m1, n2, m2; n1 = A.size(); n2 = B.size(); //col m1 = A[0].size(); m2 = B[0].size(); vector> ans; if(m1 == n2){ for(int i=0;i temp; for(int j=0; j nextLargerElement(vector arr, int n){ // Your code here stack st; vectorans; ans.push_back(-1); st.push(arr[n-1]); for(long long i= n-2; i>=0; i--){ while(!st.empty() && st.top() <= arr[i]) st.pop(); long long next = (st.empty()) ? -1 : st.top(); ans.push_back(next); st.push(arr[i]); } reverse(ans.begin(), ans.end()); return ans; } }; ================================================ FILE: Leetcode/Non Repeating Character.cpp ================================================ // Complete this function char nonrepeatingCharacter(string s) { int chars = 256; int n = s.size(); int arr[chars]; fill(arr, arr+chars, 0); for(int i=0;i=arr[mid-1]) && (mid == n-1 || arr[mid]>=arr[mid+1]) ){ return mid; } else if(arr[mid]<=arr[mid+1]){ low = mid+1; }else{ high = mid-1; } } return -1; } ================================================ FILE: Leetcode/Rearrange Array Alternately Geeksforgeeks.cpp ================================================ // https://practice.geeksforgeeks.org/problems/-rearrange-array-alternately/0 #include using namespace std; void rearrange(long long int arr[], int n){ int max_index = n-1; int min_index = 0; int max = arr[n-1]+1; for(int i=0;i> t; while(t--){ //size of array int n; cin >> n; long long int arr[n]; //adding elements to the array for(int i = 0;i> arr[i]; } //calling rearrange() function rearrange(arr, n); //printing the elements for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } return 0; } ================================================ FILE: Leetcode/Recursion/0-1 Knapsack Problem Top down.cpp ================================================ // https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem0945/1 class Solution { public: //Function to return max value that can be put in knapsack of capacity W. int knapSack(int W, int wt[], int val[], int n) { // Your code here vector>dp(n+1, vector(W+1, -1)); for(int i=0; i<=n; i++){ dp[i][0] = 0; } for(int i=0; i<=W; i++){ dp[0][i] = 0; } for(int i=1; i<=n; i++){ for(int j=1; j<=W; j++){ if(wt[i-1] <= j){ dp[i][j] = max( val[i-1] + dp[i-1][j-wt[i-1]], dp[i-1][j] ); }else{ dp[i][j] = dp[i-1][j]; } } } return dp[n][W]; } }; ================================================ FILE: Leetcode/Recursion/Best Time to Buy and Sell Stock.cpp ================================================ // https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ class Solution { public: int maxProfit(vector& prices) { int i=1, profit = 0, min_price = prices[0], n = prices.size(); while(idp(46, -1); class Solution { public: int climbStairs(int n) { if(dp[n] != -1) return dp[n]; if(n<=2){ return dp[n] = n; } return dp[n] = climbStairs(n-1) + climbStairs(n-2); } }; ================================================ FILE: Leetcode/Recursion/Decode Ways.cpp ================================================ // https://leetcode.com/problems/decode-ways/ vectordp(101, -1); class Solution { public: int n = 0; int numDecodingsHelper(string s, int pos){ if(pos == n) return 1; if(s[pos] == '0') return 0; if(dp[pos] != -1) return dp[pos]; int count = numDecodingsHelper(s , pos+1); if(pos < n-1 && s.substr(pos, 2) < "27"){ count += numDecodingsHelper(s, pos+2); } return dp[pos] = count; } int numDecodings(string s) { n = s.size(); fill(dp.begin(), dp.end(), -1); return numDecodingsHelper(s, 0); } }; ================================================ FILE: Leetcode/Recursion/Delete middle element of a stack.cpp ================================================ // https://practice.geeksforgeeks.org/problems/delete-middle-element-of-a-stack/1 class Solution { public: //Function to delete middle element of a stack. void deleteMidHelper(stack&st, int count, int &pos){ if(st.empty()) return; if(count == pos) {st.pop(); return;} int top = st.top(); st.pop(); deleteMidHelper(st, count+1, pos); st.push(top); } void deleteMid(stack&s, int sizeOfStack) { // code here.. int pos = ceil((sizeOfStack+1)/2.0); deleteMidHelper(s, 1, pos); } }; ================================================ FILE: Leetcode/Recursion/Divisor Game.cpp ================================================ // https://leetcode.com/problems/divisor-game/ class Solution { public: bool divisorGame(int n) { // if(n<=1) return false; // for(int x=1; xdp(101, -1); class Solution { public: int fun(vector& nums, int n){ if(n<=0) return 0; if(dp[n] != -1) return dp[n]; return dp[n] = max( fun(nums, n-1), nums[n-1] + fun(nums, n-2) ); } int rob(vector& nums) { int n = nums.size(); fill(dp.begin(), dp.end(), -1); return fun(nums, n); } }; ================================================ FILE: Leetcode/Recursion/Largest Element in Array.cpp ================================================ // https://practice.geeksforgeeks.org/problems/largest-element-in-array4009/1 class Solution { public: int largest(vector &arr, int n) { if(n==1) return arr[0]; return max( largest(arr, n-1), arr[n-1] ); } }; ================================================ FILE: Leetcode/Recursion/Min Cost Climbing Stairs.cpp ================================================ // https://leetcode.com/problems/min-cost-climbing-stairs/ vectordp(1001, -1); class Solution { public: int minCost(vector& cost, int n){ if(dp[n] != -1) return dp[n]; if(n<=1) return dp[n] = 0; if(n==2) return dp[n] = min(cost[0], cost[1]); return dp[n] = min( minCost(cost, n-1) + cost[n-1], minCost(cost, n-2) + cost[n-2] ); } int minCostClimbingStairs(vector& cost) { int n = cost.size(); fill(dp.begin(), dp.end(), -1); return minCost(cost, n); } }; ================================================ FILE: Leetcode/Recursion/Nth Fibonacci Number.cpp ================================================ // https://practice.geeksforgeeks.org/problems/nth-fibonacci-number1335/1 vectordp(1001, -1); class Solution { public: int mod = 1000000007; long long int nthFibonacci(long long int n){ if(dp[n] != -1) return dp[n]; // code here if(n<=1){ return dp[n] = n; }; return dp[n] = (nthFibonacci(n-1)%mod + nthFibonacci(n-2)%mod)%mod; } }; ================================================ FILE: Leetcode/Recursion/Partition Equal Subset Sum.cpp ================================================ // https://leetcode.com/problems/partition-equal-subset-sum/ /****************************** RECURSION *************************************************/ /****************************** TIME LIMIT EXCEEDED *************************************************/ class Solution { public: bool subsetSum(vector& nums, int n, int sum){ if(n==0) return false; if(sum==0) return true; if(nums[n-1] <= sum){ return subsetSum(nums, n-1, sum-nums[n-1]) || subsetSum(nums, n-1, sum); }else{ return subsetSum(nums, n-1, sum); } } bool canPartition(vector& nums) { int n = nums.size(); int sum = 0; for(auto x: nums){ sum += x; } if(sum%2 != 0) return false; sum = sum/2; return subsetSum(nums, n, sum); } }; /****************************** MEMOIZATION *************************************************/ class Solution { public: bool subsetSum(vector& nums, int n, int sum, vector>&dp){ if(dp[n][sum] != -1) return dp[n][sum]; if(nums[n-1] <= sum){ return dp[n][sum] = subsetSum(nums, n-1, sum-nums[n-1], dp) || subsetSum(nums, n-1, sum, dp); }else{ return dp[n][sum] = subsetSum(nums, n-1, sum, dp); } } bool canPartition(vector& nums) { int n = nums.size(); int sum = 0; for(auto x: nums){ sum += x; } if(sum%2 != 0) return false; sum = sum/2; vector>dp(n+1, vector(sum+1, -1)); for(int i=0; i<=sum; i++){ dp[0][i] = false; } for(int i=0; i<=n; i++){ dp[i][0] = true; } return subsetSum(nums, n, sum, dp); } }; /****************************** TOP DOWN *************************************************/ class Solution { public: bool canPartition(vector& nums) { int sum = 0, n = nums.size(); for(auto x: nums) sum += x; if(sum % 2 != 0) return false; sum /= 2; vector>t(n+1, vector(sum+1, false)); for(int i=0; idp(10001, -1); class Solution { public: int solve(int n){ if(n<=0) return 0; int ans = INT_MAX; if(dp[n] != -1) return dp[n]; for(int i=1; i*i<=n; i++){ int sqnum = i*i; int count = 1+ solve(n-sqnum); ans = min(ans, count); } return dp[n] = ans; } int numSquares(int n) { return solve(n); } }; ================================================ FILE: Leetcode/Recursion/Perfect Sum Problem.cpp ================================================ // https://practice.geeksforgeeks.org/problems/perfect-sum-problem5633/1 /****************************** RECURSION *************************************************/ /****************************** TIME LIMIT EXCEEDED *************************************************/ class Solution{ public: int mod = 1e9+7; // 1000000007 int countSubset(int arr[], int n, int sum){ if(n==0 and sum > 0) return 0; else if(n==1){ if(sum==0){ if(arr[0] == 0) return 2; else return 1; }else{ if(arr[0] == sum) return 1; else return 0; } } else if(n==0 and sum==0) return 1; if(arr[n-1] <= sum){ return countSubset(arr,n-1, sum-arr[n-1]) + countSubset(arr, n-1, sum); }else return countSubset(arr, n-1, sum); } int perfectSum(int arr[], int n, int sum) { // Your code goes here return countSubset(arr, n, sum); } }; /****************************** MEMOIZATION *************************************************/ class Solution{ public: int mod = 1e9+7; // 1000000007 int countSubset(int arr[], int n, int sum, vector>&dp){ if(dp[n][sum] != -1) return dp[n][sum]; if(n==0 and sum > 0) return 0; else if(n==1){ if(sum==0){ if(arr[0] == 0) return 2; else return 1; }else{ if(arr[0] == sum) return 1; else return 0; } } else if(n==0 and sum==0) return 1; int ans = countSubset(arr, n-1, sum, dp) % mod; if(arr[n-1] <= sum){ ans+=countSubset(arr,n-1, sum-arr[n-1], dp); ans %= mod; } return dp[n][sum] = ans; } int perfectSum(int arr[], int n, int sum) { // Your code goes here vector>dp(n+1, vector(sum+1, -1)); return countSubset(arr, n, sum, dp) % mod; } }; ================================================ FILE: Leetcode/Recursion/Power Of Numbers.cpp ================================================ // https://practice.geeksforgeeks.org/problems/power-of-numbers-1587115620/1 class Solution{ public: //You need to complete this fucntion long long power(int N,int R) { int MOD = 1e9+7; //Your code here if(N==0) return 0; if(R==0) return 1; if(R%2==0){ long long ans = power(N, R/2); return ( ans%MOD * ans%MOD )%MOD; }else{ long long ans = power(N, (R-1)/2); return ( ans%MOD * ans%MOD * N%MOD)%MOD; } } }; ================================================ FILE: Leetcode/Recursion/Print 1 To N Without Loop.cpp ================================================ // https://practice.geeksforgeeks.org/problems/print-1-to-n-without-using-loops-1587115620/1 class Solution{ public: //Complete this function void printNos(int N) { //Your code here if(N==0) return; printNos(N-1); cout<arr, int n, int sum){ if(n==0) return false; if(sum==0) return true; if(arr[n-1] <= sum){ return subsetSum(arr, n-1, sum-arr[n-1]) || subsetSum(arr, n-1, sum); }else{ return subsetSum(arr, n-1, sum); } } bool isSubsetSum(vectorarr, int sum){ // code here int n = arr.size(); return subsetSum(arr, n, sum); } }; /****************************** MEMOIZATION *************************************************/ class Solution{ public: bool subsetSum(vectorarr, int n, int sum, vector>&dp){ if(dp[n][sum] != -1) return dp[n][sum]; if(arr[n-1] <= sum){ return dp[n][sum] = subsetSum(arr, n-1, sum-arr[n-1], dp) || subsetSum(arr, n-1, sum, dp); }else{ return dp[n][sum] = subsetSum(arr, n-1, sum, dp); } } bool isSubsetSum(vectorarr, int sum){ // code here int n = arr.size(); vector>dp(n+1, vector(sum+1, -1)); for(int i=0; i<=sum; i++){ dp[0][i] = false; } for(int i=0; i<=n; i++){ dp[i][0] = true; } return subsetSum(arr, n, sum, dp); } }; ================================================ FILE: Leetcode/Recursion/Sum of Array.cpp ================================================ // https://practice.geeksforgeeks.org/problems/sum-of-array2326/1 class Solution{ public: // function to return sum of elements // in an array of size n int sum(int arr[], int n) { // code here if(n == 0) return 0; return arr[n-1] + sum(arr, n-1); } }; ================================================ FILE: Leetcode/Recursion/Target Sum.cpp ================================================ // https://leetcode.com/problems/target-sum/ class Solution { public: int countSubset(vector& nums, int n, int sum, vector>&dp){ if(dp[n][sum] != -1) return dp[n][sum]; if(n==0 and sum > 0) return 0; else if(n==1){ if(sum==0){ if(nums[0] == 0) return 2; else return 1; }else{ if(nums[0] == sum) return 1; else return 0; } } else if(n==0 and sum==0) return 1; int ans = countSubset(nums, n-1, sum, dp); if(nums[n-1] <= sum){ ans+=countSubset(nums,n-1, sum-nums[n-1], dp); } return dp[n][sum] = ans; } int findTargetSumWays(vector& nums, int target) { int n = nums.size(); int sum = 0; for(auto x: nums) {sum += x;} if(sum < abs(target) || (target + sum) % 2 !=0 ) return 0; sum = (sum+target)/2; vector>dp(n+1, vector(sum+1, -1)); return countSubset(nums, n, sum, dp); } }; ================================================ FILE: Leetcode/Recursion/Tower Of Hanoi.cpp ================================================ // https://practice.geeksforgeeks.org/problems/tower-of-hanoi-1587115621/1 class Solution{ public: // You need to complete this function // avoid space at the starting of the string in "move disk....." long long count = 0; void TOHHelper(int N, int from, int to, int aux){ if(N>0){ TOHHelper(N-1, from, aux, to); cout << "move disk " << N << " from rod " << from << " to rod " << to << endl; count++; TOHHelper(N-1, aux, to, from); } } long long toh(int N, int from, int to, int aux) { // Your code here TOHHelper(N, from, to , aux); return count; } }; ================================================ FILE: Leetcode/Reverse Linked List.cpp ================================================ // https://leetcode.com/problems/reverse-linked-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* new_head = NULL; while( head != NULL){ ListNode* temp = head; head = head->next; temp->next = new_head; new_head = temp; } return new_head; } }; ================================================ FILE: Leetcode/Rotate Array Leetcode.cpp ================================================ class Solution { public: void reverse(vector &num, int low, int high){ while(low < high){ swap(num[low], num[high]); low++; high--; } } void rotate(vector& nums, int k) { int n = (int)nums.size(); k = k%n; reverse(nums, 0, n-k-1); reverse(nums, n-k, n-1); reverse(nums, 0, n-1); } }; ================================================ FILE: Leetcode/Rotate List.cpp ================================================ // https://leetcode.com/problems/rotate-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int size(ListNode* head){ int n = 0; while(head != NULL){ n++; head = head->next; } return n; } ListNode* rotateRight(ListNode* head, int k) { if(head == NULL) return head; int n = size(head); int loop = k % n; loop = n - loop; if( n == 1 || loop == n) return head; int j=0; ListNode* temp = head; ListNode* firstAddress = head; while(temp != NULL){ j++; if(j == loop){ firstAddress = temp->next; temp->next = NULL; break; } temp = temp->next; } temp = firstAddress; while(temp->next != NULL){ temp = temp->next; } temp->next = head; return firstAddress; } }; ================================================ FILE: Leetcode/Search in a row-column sorted Matrix.cpp ================================================ // https://practice.geeksforgeeks.org/problems/search-in-a-matrix-1587115621/1 bool search(vector > matrix, int n, int m, int x) { // code here int row=0; for(int i=0;i x) { row = i-1; break; }else{ row = i; } } if(row>=0){ for(int i=0;i& nums) { int n = (int)nums.size(); int a=0; for(int i=0;i sortArrayByParity(vector& A) { vector odd; vector even; int n = (int)A.size(); for(int i=0;i& nums) { // Method 1: //sort(nums.begin(), nums.end()); // Method 2: /* int n = (int)nums.size(); int f=0, s=0,t=0; for(int i=0;i spirallyTraverse(vector > matrix, int r, int c) { // code here int top = 0; int bottom = r-1; int left = 0; int right = c-1; vector ans; while(top<=bottom && left<=right){ for(int i=left; i<=right ; i++) ans.push_back(matrix[top][i]); top++; for(int i=top;i<=bottom;i++) ans.push_back(matrix[i][right]); right--; if(top<=bottom){ for(int i=right;i>=left;i--) ans.push_back(matrix[bottom][i]); bottom--; } if(left<=right){ for(int i=bottom;i>=top;i--) ans.push_back(matrix[i][left]); left++; } } return ans; } }; ================================================ FILE: Leetcode/Square root.cpp ================================================ // https://practice.geeksforgeeks.org/problems/square-root/1 #include using namespace std; long long int floorSqrt(long long int x); // Function to find square root // x: element to find square root long long int floorSqrt(long long int x) { // Your code goes here int low = 1; int high = x; int ans = -1; while(low<=high){ long long int mid = (low+high)/2; long long int sqr = mid*mid; if(sqr == x) return mid; else if(sqr < x){ ans = mid; low = mid+1; }else{ high = mid-1; } } return ans; } int main() { int t; cin>>t; while(t--) { long long n; cin>>n; cout << floorSqrt(n) << endl; } return 0; } ================================================ FILE: Leetcode/Subarray sum equals K.cpp ================================================ class Solution { public: int subarraySum(vector& nums, int k) { int n =(int)nums.size(); int count=0; unordered_map prevSum; int sum=0; for(int i=0;i using namespace std; // function to find the trapped water in between buildings // arr: input array // n: size of array int trappingWater(int arr[], int n){ int lmax[n]; lmax[0] = arr[0]; for(int i=1;i=0 ;i--){ int temp = max(arr[i], rmax[i+1]); rmax[i] = temp; } int water=0; for(int i=1;i> t; while(t--){ int n; //size of array cin >> n; int a[n]; //adding elements to the array for(int i =0;i> a[i]; } //calling trappingWater() function cout << trappingWater(a, n) << endl; } return 0; } // } Driver Code Ends ================================================ FILE: Leetcode/Tree/Balanced Binary Tree.cpp ================================================ // https://leetcode.com/problems/balanced-binary-tree/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int height(TreeNode* root){ if(root == NULL) return 0; else return max( height(root->left), height(root->right) ) +1; } void inorderUtil(TreeNode* root, bool & ans){ if(root!=NULL){ inorderUtil(root->left, ans); int lh = height(root->left); int rh = height(root->right); if(abs(lh-rh) >1) ans = ans && false; inorderUtil(root->right, ans); } } bool isBalanced(TreeNode* root) { bool ans = true; inorderUtil(root, ans); return ans; } }; ================================================ FILE: Leetcode/Tree/Binary Tree Inorder Traversal.cpp ================================================ // https://leetcode.com/problems/binary-tree-inorder-traversal/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void preorder(TreeNode* root, vector &ans){ if(root!=NULL){ ans.push_back(root->val); preorder(root->left, ans); preorder(root->right, ans); } } vector inorderTraversal(TreeNode* root) { vector ans; preorder(root, ans); return ans; } }; ================================================ FILE: Leetcode/Tree/Binary Tree Right Side View.cpp ================================================ // https://leetcode.com/problems/binary-tree-right-side-view/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector rightSideView(TreeNode* root) { vector ans; queueq; q.push(root); if(root == NULL) return ans; while(1){ int size = q.size(); if(size==0) return ans; int data = 0; while(size>0){ TreeNode* temp = q.front(); q.pop(); data = (temp->val); if(temp->left!=NULL) q.push(temp->left); if(temp->right!=NULL) q.push(temp->right); size--; } ans.push_back(data); } return ans; } }; ================================================ FILE: Leetcode/Tree/Binary Tree Zigzag Level Order Traversal.cpp ================================================ // https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ vector> zigzagLevelOrder(TreeNode* root) { vector> ans; queue q; q.push(root); int count = 0; if(root == NULL) return ans; while(1){ int size = q.size(); if(size == 0) return ans; count++; vectordata; while(size>0){ TreeNode* temp = q.front(); q.pop(); data.push_back(temp->val); if(temp->left != NULL) q.push(temp->left); if(temp->right != NULL) q.push(temp->right); size--; } if(count%2==0) reverse(data.begin(), data.end()); ans.push_back(data); } return ans; } ================================================ FILE: Leetcode/Tree/Children Sum Parent.cpp ================================================ // https://practice.geeksforgeeks.org/problems/children-sum-parent/1/ int isSumProperty(Node *root) { if( root == NULL || (root->left == NULL && root->right==NULL)) return 1; int left_sum = 0, right_sum = 0; if(root->left != NULL) left_sum = root->left->data; if(root->right != NULL) right_sum = root->right->data; if( root->data == (left_sum+right_sum) && isSumProperty(root->left) && isSumProperty(root->right) ){ return 1; } else return 0; } ================================================ FILE: Leetcode/Tree/Construct Binary Tree from Preorder and Inorder Traversal.cpp ================================================ // https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int preIndex = 0; TreeNode* buildTreeUtil(vector& preorder, vector& inorder, int is, int ie){ if(is > ie) return NULL; TreeNode* root = new TreeNode(preorder[preIndex]); preIndex++; int inIndex; for(int i=is; i<=ie; i++){ if(inorder[i] == root->val){ inIndex = i; break; } } root->left = buildTreeUtil(preorder, inorder, is, inIndex-1); root->right = buildTreeUtil(preorder, inorder, inIndex+1, ie); return root; } TreeNode* buildTree(vector& preorder, vector& inorder) { TreeNode* ans = buildTreeUtil(preorder, inorder, 0, inorder.size()-1); return ans; } }; ================================================ FILE: Leetcode/Tree/Diameter of Binary Tree.cpp ================================================ // https://leetcode.com/problems/diameter-of-binary-tree/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int res = 0; int height(TreeNode* root){ if(root == NULL) return 0; int lh = height( root-> left); int rh = height( root-> right); res = max(res, 1+lh+rh); return 1+ max(lh, rh); } int diameterOfBinaryTree(TreeNode* root) { int data = height(root); return res-1; } }; ================================================ FILE: Leetcode/Tree/Invert Binary Tree.cpp ================================================ // https://leetcode.com/problems/invert-binary-tree/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* invertTree(TreeNode* root) { stack st; st.push(root); while(!st.empty()){ TreeNode* node = st.top(); st.pop(); if(node != NULL){ st.push(node->left); st.push(node->right); swap(node->left, node->right); } } return root; } }; ================================================ FILE: Leetcode/Tree/Level Order Traversal.cpp ================================================ // https://leetcode.com/problems/binary-tree-level-order-traversal/ vector> levelOrder(TreeNode* root) { vector> ans; queueq; q.push(root); if(root == NULL) return ans; while(1){ int size = q.size(); if(size==0) return ans; vectordata; while(size>0){ TreeNode* temp = q.front(); q.pop(); data.push_back(temp->val); if(temp->left!=NULL) q.push(temp->left); if(temp->right!=NULL) q.push(temp->right); size--; } ans.push_back(data); } return ans; } ================================================ FILE: Leetcode/Tree/Lowest Common Ancestor of a Binary Tree.cpp ================================================ // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ // METHOD - 01 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool findPath(TreeNode* root, vector &path, TreeNode* n){ if(root == NULL) return false; path.push_back(root); if(root == n) return true; if( findPath(root->left, path, n) || findPath(root->right, path, n) ) return true; path.pop_back(); return false; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector path1, path2; if( !findPath(root, path1, p) || !findPath(root, path2, q) ) return NULL; TreeNode* ans = NULL; for(int i=0; ileft, p, q); TreeNode* lca2 = lowestCommonAncestor(root->right, p, q); if(lca1 != NULL && lca2 != NULL) return root; if(lca1 != NULL) return lca1; else return lca2; } }; ================================================ FILE: Leetcode/Tree/Maximum Depth of Binary Tree.cpp ================================================ // https://leetcode.com/problems/maximum-depth-of-binary-tree/ class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; else return max( maxDepth(root->left), maxDepth(root->right) ) + 1; } }; ================================================ FILE: Leetcode/Tree/Populating Next Right Pointers in Each Node.cpp ================================================ // https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ /* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; */ class Solution { public: Node* connect(Node* root) { if(root == NULL) return root; queueq; q.push(root); while(!q.empty()){ int size = q.size(); if( size == 0) return root; while(size>0){ Node* temp; if(size>1){ temp = q.front(); q.pop(); Node* nextAdd = q.front(); temp->next = nextAdd; } else{ temp = q.front(); q.pop(); } if(temp->left != NULL) q.push(temp->left); if(temp->right != NULL) q.push(temp->right); size--; } } return root; } }; ================================================ FILE: Leetcode/Tree/Subtree of Another Tree.cpp ================================================ // https://leetcode.com/problems/subtree-of-another-tree/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool ans = false; bool match(TreeNode* root, TreeNode* subRoot){ if(root!=NULL && subRoot!=NULL){ bool a = match(root->left, subRoot->left); bool b = match(root->right, subRoot->right); if( (root->val == subRoot->val) && a && b ){ return true; }else return false; } else if(root==NULL && subRoot==NULL) return true; else return false; } void inorder(TreeNode* root, TreeNode* subRoot){ if(root!=NULL){ inorder(root->left, subRoot); bool x = match(root, subRoot); if(x){ans = x;} inorder(root->right, subRoot); } } bool isSubtree(TreeNode* root, TreeNode* subRoot) { inorder(root, subRoot); return ans; } }; ================================================ FILE: Leetcode/Tree/Symmetric Tree.cpp ================================================ // https://leetcode.com/problems/symmetric-tree/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool match(TreeNode* root1, TreeNode* root2){ if(root1 != NULL && root2 != NULL){ bool a = match(root1->left, root2->right); bool b = match(root1->right, root2->left); if((root1->val == root2->val) && a && b) return true; else return false; } else if(root1 == NULL && root2 == NULL){ return true; }else return false; } bool isSymmetric(TreeNode* root) { if(root == NULL) return true; return match(root->left, root->right); } }; ================================================ FILE: Leetcode/Tree/Vertical Width of a Binary Tree .cpp ================================================ // https://practice.geeksforgeeks.org/problems/vertical-width-of-a-binary-tree/1 /*Structure of node of binary tree is as follows struct Node { int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; } }; */ unordered_setst; void inorderUtil(Node* root, int hd){ if(root != NULL){ inorderUtil(root->left, hd-1); st.insert(hd); inorderUtil(root->right, hd+1); } } //Function to find the vertical width of a Binary Tree. int verticalWidth(Node* root) { // Code here st.clear(); inorderUtil(root, 0); return st.size(); } ================================================ FILE: Leetcode/Tree/same Tree.cpp ================================================ // https://leetcode.com/problems/same-tree/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void inorder(TreeNode* root, vector&v){ if(root!=NULL){ inorder(root->left, v); v.push_back(root->val); inorder(root->right, v); }else v.push_back(100000); } void preorder(TreeNode* root, vector&v){ if(root!=NULL){ v.push_back(root->val); preorder(root->left, v); preorder(root->right, v); }else v.push_back(100000); } bool isSameTree(TreeNode* p, TreeNode* q) { vector inp, inq, prep, preq; inorder(p, inp); inorder(q, inq); preorder(p, prep); preorder(q, preq); if(inp == inq && prep == preq) return true; else return false; } }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Recursive Solution class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p==NULL && q==NULL) return true; if(p==NULL || q==NULL) return false; return ( p->val == q->val && isSameTree( p->left, q->left ) && isSameTree( p->right, q->right ) ); } }; ================================================ FILE: Leetcode/count 1's in binary array.cpp ================================================ // https://practice.geeksforgeeks.org/problems/count-1s-in-binary-array-1587115620/1 #include using namespace std; // Function to count number of Ones // arr: input array // N: size of input array int countOnes(int arr[], int N) { // Your code here int low=0; int high=N-1; while(low<=high){ int mid = (low+high)/2; if(arr[mid]==0){ high = mid-1; } else{ if(arr[mid+1]==0 || mid==N-1){ return mid+1; }else{ low = mid+1; } } } return 0; } int main() { int t; cin>>t; while(t--) { int n; cin>>n; int *arr = new int[n]; for(int i = 0; i < n; i++) cin>>arr[i]; cout < using namespace std; // Function to count number of Ones // arr: input array // N: size of input array int countOnes(int arr[], int N) { // Your code here int low= 0; int high = N-1; while(low<=high){ int mid = (low+high) /2; if(arr[mid]==0){ if(arr[mid-1]==1 || mid == 0){ return mid; }else{ high = mid-1; } } else{ if(arr[mid+1]==0 || mid == N-1){ return mid+1; }else{ low = mid+1; } } } return 0; } int main() { int t; cin>>t; while(t--) { int n; cin>>n; int *arr = new int[n]; for(int i = 0; i < n; i++) cin>>arr[i]; cout <next == NULL){ return false; } ListNode *slow = head; ListNode *fast = head->next; while(slow!=fast){ if(fast==NULL || fast->next == NULL){ return false; } slow = slow->next; fast = fast->next->next; } return true; } }; ================================================ FILE: Leetcode/linkedlist/Copy List with Random Pointer.cpp ================================================ // https://leetcode.com/problems/copy-list-with-random-pointer/ /* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { public: Node* copyRandomList(Node* head) { if( head == NULL) return head; Node* newhead = new Node(0); Node* new_curr = newhead; Node* curr = head; unordered_map umap; while(curr){ Node* temp = new Node(curr->val); umap.insert({curr, temp}); new_curr->next = temp; new_curr = new_curr->next; curr = curr->next; } curr = head; new_curr = newhead->next; while(curr){ Node* random = curr->random; Node* newNode = umap[random]; new_curr->random = newNode; new_curr = new_curr->next; curr = curr->next; } return newhead->next; } }; ================================================ FILE: Leetcode/linkedlist/Delete Node in a Linked List.cpp ================================================ // https://leetcode.com/problems/delete-node-in-a-linked-list/ class Solution { public: void deleteNode(ListNode* node) { ListNode* curr = node->next; node->val = curr->val; node->next = curr->next; } }; ================================================ FILE: Leetcode/linkedlist/Intersection of Two Linked Lists.cpp ================================================ // https://leetcode.com/problems/intersection-of-two-linked-lists/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode* curr = headA; int a =0, b=0; while(curr){ a++; curr = curr->next; } curr =headB; while(curr){ b++; curr = curr->next; } int diff = abs(a-b); if(anext; } }else{ while(diff--){ headA = headA->next; } } while(headA and headB){ if(headA == headB){ return headA; } headA = headA->next; headB = headB->next; } return NULL; } }; ================================================ FILE: Leetcode/linkedlist/Linked List Cycle II.cpp ================================================ // https://leetcode.com/problems/linked-list-cycle-ii/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { if(head == NULL) return NULL; ListNode* slow = head, *fast = head, *entry = head; while(fast->next != NULL && fast->next->next != NULL){ slow = slow->next; fast = fast->next->next; if(slow == fast){ while(entry != slow){ slow = slow->next; entry = entry->next; } return slow; } } return NULL; /* unordered_set set; ListNode* curr = head; while(curr != NULL){ if(set.find(curr) != set.end()){ return curr; }else{ set.insert(curr); curr = curr->next; } } return NULL; */ } }; ================================================ FILE: Leetcode/linkedlist/Merge Two Sorted Lists.cpp ================================================ // https://leetcode.com/problems/merge-two-sorted-lists/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { ListNode* head; if(list1->val <= list2->val){ head = list1; list1 = list1->next; }else{ head = list2; list2 = list2->next; } ListNode* curr = head; while(list1 != NULL && list2 != NULL){ if(list1->val <= list2->val){ curr->next = list1; list1 = list1->next; }else{ curr->next = list2; list2 = list2->next; } curr = curr->next; } if(list1 != NULL) curr->next = list1; if(list2 != NULL) curr->next = list2; return head; } }; ================================================ FILE: Leetcode/linkedlist/Palindrome Linked List.cpp ================================================ // https://leetcode.com/problems/palindrome-linked-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { ListNode* slow = head, *fast = head; while(fast and fast->next){ slow = slow->next; fast = fast->next->next; } if(fast != NULL and fast->next == NULL ){ slow = slow->next; } ListNode* prev = NULL; while(slow and slow->next){ ListNode* temp = slow->next; slow->next = prev; prev = slow; slow = temp; } if(slow != NULL){slow->next = prev;} fast = head; while(slow and fast){ if(slow->val != fast->val) return false; slow = slow->next; fast = fast->next; } return true; } }; ================================================ FILE: Leetcode/linkedlist/Remove Duplicates from Sorted List.cpp ================================================ // https://leetcode.com/problems/remove-duplicates-from-sorted-list/ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* curr = head; while(curr != NULL && curr->next != NULL){ if(curr->val == curr->next->val){ // same ListNode* temp = curr->next; curr->next = temp->next; delete(temp); }else{ curr = curr->next; } } return head; } }; ================================================ FILE: Leetcode/linkedlist/Remove Nth Node From End of List.cpp ================================================ // https://leetcode.com/problems/remove-nth-node-from-end-of-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *slow = head, *fast = head; while(n--){ fast = fast->next; } if(fast == NULL) return slow->next; while(fast->next != NULL){ slow = slow->next; fast = fast->next; } slow->next = slow->next->next; return head; } }; ================================================ FILE: Leetcode/linkedlist/Remove duplicates from an unsorted linked list.cpp ================================================ // https://practice.geeksforgeeks.org/problems/remove-duplicates-from-an-unsorted-linked-list/0 /* The structure of linked list is the following struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } }; */ class Solution { public: //Function to remove duplicates from unsorted linked list. Node * removeDuplicates( Node *head) { // your code goes here unordered_setseen; Node* curr = head; if(curr == NULL) return head; else seen.insert(curr->data); while(curr != NULL && curr->next != NULL){ if(seen.find(curr->next->data) != seen.end()){ // same curr->next = curr->next->next; }else{ // not same seen.insert(curr->next->data); curr = curr->next; } } return head; } }; ================================================ FILE: Leetcode/linkedlist/Reverse Linked List.cpp ================================================ // https://leetcode.com/problems/reverse-linked-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* prev = NULL, *curr = head; while(curr != NULL){ ListNode *temp = curr->next; curr->next = prev; prev = curr; curr = temp; } return prev; } }; ================================================ FILE: Leetcode/linkedlist/Sort List.cpp ================================================ // https://leetcode.com/problems/sort-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* Mid(ListNode* head){ ListNode* slow = head; ListNode* fast = head; while(fast->next != NULL and fast->next->next != NULL){ slow = slow->next; fast = fast->next->next; } return slow; } ListNode* mergeSortedList(ListNode *p1, ListNode *p2){ if(p1 == NULL or p2 == NULL){ return (p1==NULL) ? p2 : p1; } ListNode * ans = new ListNode(0); ListNode* curr = ans; while(p1 != NULL and p2 != NULL){ if(p1->val < p2->val){ curr->next = p1; p1= p1->next; }else{ curr->next = p2; p2 = p2->next; } curr = curr->next; } if(p1 != NULL or p2 != NULL){ curr->next = (p1 != NULL) ? p1 : p2; } return ans->next; } ListNode* sortList(ListNode* head) { if( head == NULL or head->next == NULL) return head; ListNode* mid = Mid(head); ListNode* newhead = mid->next; mid->next = NULL; ListNode* left_half = sortList(head); ListNode* right_half = sortList(newhead); return mergeSortedList(left_half, right_half); } }; ================================================ FILE: Leetcode/linkedlist/Swap Nodes in Pairs.cpp ================================================ // https://leetcode.com/problems/swap-nodes-in-pairs/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode *curr = head->next->next; ListNode * prev = head; head = head->next; head->next = prev; while(curr != NULL && curr->next != NULL){ prev->next = curr->next; prev = curr; ListNode * temp = curr->next->next; curr->next->next = curr; curr = temp; } prev->next = curr; return head; } }; ================================================ FILE: Leetcode/linkedlist/Swapping Nodes in a Linked List.cpp ================================================ // https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* swapNodes(ListNode* head, int k) { ListNode* slow = head, *fast = head; while(--k){ fast = fast->next; } ListNode *first = fast; while(fast->next != NULL){ slow = slow->next; fast = fast->next; } swap(first->val, slow->val); return head; } }; ================================================ FILE: Leetcode/stack/Evaluate Reverse Polish Notation.cpp ================================================ // https://leetcode.com/problems/evaluate-reverse-polish-notation/ class Solution { public: int evalRPN(vector& tokens) { stackst; for(auto x: tokens){ if(x == "+" || x == "-" || x =="/" || x == "*"){ int op2 = st.top(); st.pop(); int op1 = st.top(); st.pop(); if(x == "+"){ st.push(op1 + op2); } if(x == "-"){ st.push(op1 - op2); } if(x == "*"){ st.push(op1 * op2); } if(x == "/"){ st.push(op1 / op2); } } else{ stringstream ss(x); int data; ss >> data; st.push(data); } } return st.top(); } }; ================================================ FILE: Leetcode/stack/Implement Queue using Stacks.cpp ================================================ // https://leetcode.com/problems/implement-queue-using-stacks/ class MyQueue { private: stackinput, output; public: MyQueue() { } void push(int x) { input.push(x); } int pop() { int val = peek(); output.pop(); return val; } int peek() { if( output.empty() ){ while( input.empty() != true ){ output.push(input.top()); input.pop(); } } return output.top(); } bool empty() { return input.empty() && output.empty(); } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */ ================================================ FILE: Leetcode/stack/Implement Stack using Queues.cpp ================================================ // https://leetcode.com/problems/implement-stack-using-queues/ class MyStack { public: queueq1,q2; MyStack() { } void push(int x) { while(!q1.empty()){ q2.push(q1.front()); q1.pop(); } q1.push(x); while(!q2.empty()){ q1.push(q2.front()); q2.pop(); } } int pop() { int val = q1.front(); q1.pop(); return val; } int top() { return q1.front(); } bool empty() { return q1.empty(); } }; /** * Your MyStack object will be instantiated and called as such: * MyStack* obj = new MyStack(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->top(); * bool param_4 = obj->empty(); */ ================================================ FILE: Leetcode/stack/Largest Rectangle in Histogram.cpp ================================================ // https://leetcode.com/problems/largest-rectangle-in-histogram/ class Solution { public: vector previous_smaller(vector& heights){ vector ans; stackst; int n = heights.size(); for(int i=0; i= heights[i] ){ st.pop(); } int ele = (st.empty()) ? -1 : st.top(); ans.push_back(ele); st.push(i); } return ans; } vector next_smaller(vector& heights){ vector ans; stackst; int n = heights.size(); for(int i=n-1; i>=0; i--){ while(st.empty() == false && heights[st.top()] >= heights[i] ){ st.pop(); } int ele = (st.empty()) ? n : st.top(); ans.push_back(ele); st.push(i); } reverse(ans.begin(), ans.end()); return ans; } int largestRectangleArea(vector& heights) { int res = 0; int n = heights.size(); vectorps = previous_smaller(heights); vectorns = next_smaller(heights); for(int i=0; ist, s2; MinStack() { } void push(int val) { if( s2.empty() || val <= s2.top() ){ s2.push(val); } st.push(val); } void pop() { if(st.top() == s2.top()){ s2.pop(); } st.pop(); } int top() { return st.top(); } int getMin() { return s2.top(); } }; /** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(val); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */ ================================================ FILE: Leetcode/stack/Next Greater Element I.cpp ================================================ // https://leetcode.com/problems/next-greater-element-i/ class Solution { public: vector nextGreaterElement(vector& nums1, vector& nums2) { unordered_mapumap; stackst; int n = nums2.size(); for(int i=n-1; i>=0; i--){ int ele = nums2[i]; while(!st.empty() && st.top() <= ele){ st.pop(); } int res = (st.empty()) ? -1 : st.top(); umap.insert({ele, res}); st.push(ele); } vector ans; for(auto x: nums1){ ans.push_back(umap[x]); } return ans; } }; ================================================ FILE: Leetcode/stack/Online Stock Span.cpp ================================================ // https://leetcode.com/problems/online-stock-span/ class StockSpanner { public: stack>st; // price, span StockSpanner() { } int next(int price) { int span = 1; while(!st.empty() && st.top().first <= price){ span += st.top().second; st.pop(); } st.push({price, span}); return span; } }; /** * Your StockSpanner object will be instantiated and called as such: * StockSpanner* obj = new StockSpanner(); * int param_1 = obj->next(price); */ ================================================ FILE: Leetcode/stack/Remove All Adjacent Duplicates In String.cpp ================================================ // https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ class Solution { public: string removeDuplicates(string s) { int n = s.size(), i=0; stackst; while(i>st; for(auto c : s){ if(st.size() == 0 || st.back().first != c ){ st.push_back({c, 1}); } else{ st.back().second++; } if(st.back().second == k){ st.pop_back(); } } string res ; for(auto x: st){ res.append(x.second, x.first); } return res; } }; ================================================ FILE: Leetcode/stack/Reverse First K elements of Queue.cpp ================================================ // https://practice.geeksforgeeks.org/problems/reverse-first-k-elements-of-queue/1/ // { Driver Code Starts // Initial Template for C++ #include using namespace std; queue modifyQueue(queue q, int k); int main() { int t; cin >> t; while (t-- > 0) { int n, k; cin >> n >> k; queue q; while (n-- > 0) { int a; cin >> a; q.push(a); } queue ans = modifyQueue(q, k); while (!ans.empty()) { int a = ans.front(); ans.pop(); cout << a << " "; } cout << endl; } }// } Driver Code Ends // User function Template for C++ // Function to reverse first k elements of a queue. queue modifyQueue(queue q, int k) { // add code here. queue ans; stackst; while(k--){ st.push(q.front()); q.pop(); } while(!st.empty()){ ans.push(st.top()); st.pop(); } while(!q.empty()){ ans.push(q.front()); q.pop(); } return ans; } ================================================ FILE: Leetcode/stack/Valid Parentheses.cpp ================================================ // https://leetcode.com/problems/valid-parentheses/ class Solution { public: bool isValid(string s) { stackst; for(auto c : s){ if(st.empty()){ st.push(c); } else if( (st.top() == '(' && c == ')') || (st.top() == '[' && c == ']') || (st.top() == '{' && c == '}') ){ st.pop(); } else{ st.push(c); } } if(st.size() == 0) return true; return false; } }; ================================================ FILE: Leetcode/string/Find the Index of the First Occurrence in a String.cpp ================================================ // https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/ // Pattern Matching Algorithm by using KMP Algorithm class Solution { public: vector fillLPS(string str){ int n = str.size(); vectorlps(n,0); int len =0, i = 1; lps[0]=0; while(ilps = fillLPS(needle); int i=0, j=0; while(i& gas, vector& cost) { int totalDiff =0, n = gas.size(), fuel =0, index =0; for(int i=0; i& costs, int coins) { int ans = 0; sort(costs.begin(), costs.end()); for(auto x: costs){ if(coins >= x){ ans++; coins-=x; } } return ans; } }; ================================================ FILE: Leetcode/sum of numbers in string.cpp ================================================ // https://practice.geeksforgeeks.org/problems/sum-of-numbers-in-string/0 #include using namespace std; int findSum(string s) { // Your code here int n = (int)s.size(); int num=0; int sum=0; for(int i=0;i='0' && s[i]<='9') num = num*10 + (s[i]-'0'); else{ sum += num; num = 0; } } return sum+num; } int main() { int t; cin>>t; while(t--) { string str; cin>>str; cout << findSum(str); cout<HELLO WORLD > [Hello World](https://www.youtube.com/channel/UCbW63uLlDnsL7l992Z9nF_Q/) This section will provide you the pdf of my lecture and codes. I have Youtube channel named - "Hello World" My channel contains Courses on * Competitive Programming * Data Structure * Algorithms like sorting , searching , graph etc * C++ Language * And lots of stuffs You can contact me on my Email ID : Helloworldbyprince@gmail.com ================================================ FILE: STL/Array_Algorithms_in_stl.cpp ================================================ // DATA STRUCTURES.cpp // // Created by Prince Kumar on 26/06/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** STANDARD TEMPLATE LIBRARY (STL) in C++ **--- // ---** PRACTICE CODING SKILLS **--- // all_of | any_of | none_of | copy_n | iota #include #include #include using namespace std; int main(){ int a[6] = {2, 5 , -6, 7, 9,100}; // int count=0; // for(int i=0;i<6;i++){ // if(a[i]>=0){ // count++; // } // } all_of(a, a+6, [](int x){ return x>0;}) ? cout<<"all elements of array is +ve"< #include using namespace std; void show(int a[], int asize){ for(int i=0;i #include using namespace std; void show(list l){ list :: iterator it; for(it = l.begin(); it!=l.end(); it++){ cout<<*it<<" "; } cout< list1; list :: iterator it; list1.push_back(9); list1.push_back(2); list1.push_back(-7); list1.push_back(3); it = list1.begin(); cout<<*it< #include using namespace std; void show(queue QUEUE){ queue q = QUEUE; while(!q.empty()){ cout< q; q.push(10); q.push(11); q.push(-3); q.push(2); show(q); cout<<"size : "< #include #include #include using namespace std; void show(vectorv){ for(int i=0;i<(int)v.size();i++){ cout< v; v.push_back(3); v.push_back(0); v.push_back(-4); v.push_back(7); v.push_back(13); v.push_back(8); v.push_back(2); show(v); //sort(v.begin(), v.end()); //show(v); reverse(v.begin(), v.end()); show(v); cout<<*max_element(v.begin(), v.end())< #include using namespace std; int main(){ int a[10]= {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; sort(a,a+10); for(int i=0;i<10;i++){ cout< #include using namespace std; void showDeque(deque q){ deque :: iterator it; for(it = q.begin(); it!=q.end() ;it++){ cout<<*it<<" "; } cout< dq; dq.push_back(10); // 7 10 -3 8 dq.push_front(-3); dq.push_back(7); dq.push_front(8); showDeque(dq); cout<<"size of deque : "< #include using namespace std; int main(){ pair PAIR1; PAIR1.first = 100; PAIR1.second = 'G'; cout<PAIR2 ("prince" , 78.8); cout<PAIR3; PAIR3 = make_pair("krishna", 90.3); cout< pair1 = make_pair(1, 19); pair pair2 = make_pair(2, 7); pair pair3(pair2); // we copied pair2 data in the pair3 cout<= pair2)< #include using namespace std; void showPriorityQueue(priority_queue pq){ priority_queue q = pq; while(!q.empty()){ cout< q; q.push(10); q.push(-3); q.push(7); q.push(8); showPriorityQueue(q); cout< #include #include using namespace std; void showArray(int a[]){ for(int i=0;i<10;i++){ cout< v; v.push_back(10); v.push_back(-3); v.push_back(2); v.push_back(91); v.push_back(5); v.push_back(7); sort(v.begin(), v.end()); for(int i=0;i<(int)v.size();i++){ cout< #include using namespace std; void printElementOfStack(stack s){ while(!s.empty()){ cout< s; s.push(3); s.push(10); s.push(-3); s.push(9); cout< using namespace std; template //template T MAX ( T a , T b){ return a>b ? a : b; } template class boy { public: Y name; }; int main(){ //cout<('a', 'c'); cout< person; person.name="prince"; cout<<(person.name)< using namespace std; struct node{ int data; node* left; node* right; }; node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } node * search(node * root, int key){ if(root==NULL || root->data == key) return root; // if key is greater than root if( root->data < key){ return search(root->right, key); } return search(root->left, key); } int main(){ node * root = newNode(4); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(1); root->left->right = newNode(3); /* 4 / \ 2 5 / \ 1 3 */ node* address = search(root, 5); cout<data< using namespace std; struct node{ int data; node* left; node* right; }; node* newNode(int data){ node* element = new node(); element->data = data; element->left = NULL; element->right = NULL; return element; } //node* newNode(int data){ // node* node = new struct node(); // node->data = data; // node->left = NULL; // node->right = NULL; // // return node; //} void printNode(node *n){ while( n!=NULL){ cout<data<<" "; n = n->left; } cout<left = newNode(2); /* 1 / \ 2 NULL / \ NULL NULL */ root->right = newNode(3); root->left->left = newNode(4); printNode(root); } // 1 2 3 4 5 6 7 ================================================ FILE: Tree/Code of Deletion of Node in BST.cpp ================================================ // DATA STRUCTURES.cpp // // Created by Prince Kumar on 04/08/2020. // Copyright © 2020 Prince Kumar. All rights reserved. // // ---** TREE DATA STRUCTURE in C++ **--- // ---** PRACTICE CODING SKILLS **--- #include using namespace std; struct node{ int data; node* left ,* right; }; node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } void inorder(node* root){ if(root!=NULL){ inorder(root->left); cout<<(root->data)<<" "; inorder(root->right); } } node *insert(node * node, int key){ // tree empty if(node == NULL) return newNode(key); // key is smaller than node->data if(key < (node->data)){ node->left = insert(node->left, key); } else if( key > (node->data)){ node->right = insert(node->right, key); } // else return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ node * minValueNode(node * node){ struct node *current = node; /* loop down to find the leftmost leaf */ while(current && current->left != NULL ) current = current->left; return current; } /* Given a binary search tree and a key, this function deletes the key and returns the new root */ node * deleteNode(node * root, int key){ // base case if(root == NULL) return root; // If the key to be deleted is smaller than the root's key, then it lies in left subtree if(key < root->data){ root->left = deleteNode(root->left, key); } // If the key to be deleted is greater than the root's key, then it lies in right subtree else if(key > root->data){ root->right = deleteNode(root->right, key); } // if key is same as root's key, then This is the node to be deleted else{ // node with only one child or no child if(root->left == NULL){ node * temp = root->right; free(root); return temp; } else if(root->right == NULL){ node * temp = root->left; free(root); return temp; } // node with two children: Get the inorder successor (smallest in the right subtree) node * temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->data = temp->data; // Delete the inorder successor root->right = deleteNode(root->right, temp->data); } return root; } int main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ node *root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); root = deleteNode(root, 20); inorder(root); cout< using namespace std; struct node{ int data; node* left; node* right; }; node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } void printInorder(node *node){ if(node == NULL) return; /* first traverse left part of tree */ printInorder(node->left); /* then print data */ cout<data<<" "; /* and last traverse right part of tree */ printInorder(node->right); } int main(){ node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* 1 / \ 2 3 / \ 4 5 */ cout<<"Inorder Traversl of Tree : "< using namespace std; struct node{ int data; node* left ,* right; }; node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } void inorder(node* root){ if(root!=NULL){ inorder(root->left); cout<<(root->data)<<" "; inorder(root->right); } } node *insert(node * node, int key){ // tree empty if(node == NULL) return newNode(key); // key is smaller than node->data if(key < (node->data)){ node->left = insert(node->left, key); } else if( key > (node->data)){ node->right = insert(node->right, key); } // else return node; } int main(){ /* 50 / \ 30 70 / \ / \ 20 40 60 80 */ node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 70); insert(root, 20); insert(root, 40); insert(root, 60); insert(root, 80); inorder(root); cout< #include using namespace std; #define MAX 1000 bool hashTable[MAX+1][2]; bool search(int x){ if(x>=0){ if(hashTable[x][0] == 1 ){ return true; }else{ return false; } }else{ x = abs(x); if(hashTable[x][1] == 1 ){ return true; }else{ return false; } } } void insert(int a[], int n){ for(int i=0;i=0){ hashTable[a[i]][0] = 1; } else{ hashTable[abs(a[i])][1] = 1; } } } int main(){ int arr[] = {-1, 9, 2, -5, 3, 1}; int n = sizeof(arr)/sizeof(arr[0]); insert(arr, n); int find = -1; if(search(find)){ cout<<"Element is present"< using namespace std; struct node{ int data; node* left; node* right; }; node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } void printInorder(node *node){ if(node == NULL) return; /* first traverse left part of tree */ printInorder(node->left); /* then print data */ cout<data<<" "; /* and last traverse right part of tree */ printInorder(node->right); } void printPreorder(node *node){ if(node == NULL) return; /* then print data */ cout<data<<" "; /* first traverse left part of tree */ printPreorder(node->left); /* and last traverse right part of tree */ printPreorder(node->right); } void printPostorder(node *node){ if(node == NULL) return; /* first traverse left part of tree */ printPostorder(node->left); /* and last traverse right part of tree */ printPostorder(node->right); /* then print data */ cout<data<<" "; } int main(){ node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* 1 / \ 2 3 / \ 4 5 */ cout<<"Inorder Traversl of Tree : "< using namespace std; int main(){ int T; cin>>T; while(T--){ int n; cin>>n; int a[3]= {0,0,0}; // 5 10 15 int check=0; for(int i=0;i>x; if(x==5){ a[0]+=1; }else if(x==10){ if(a[0]>=1){ a[1]+=1; a[0]-=1; }else{ check++; } }else{ if(a[1]>=1){ a[2]+=1; a[1]-=1; }else if(a[0]>=2){ a[2]+=1; a[0]-=2; }else{ check++; } } } if(check==0){ cout<<"YES"< using namespace std; int main(){ int T; cin>>T; while(T--){ string s; cin>>s; int n = (int)s.size(); int i=0; int count=0; // 0 1 2 3 4 5 i=5 while(i #include using namespace std; int main(){ // roll_num weight of student map < int , int > person; // Insert the values in map person.insert(pair(1,35)); person.insert({2, 40}); person.insert({3,50}); person.insert({5, 10}); // auto it = person.find(3); // person.erase(it); //person.erase(5); // print for(auto itr = person.begin() ; itr!=person.end() ; ++itr){ cout<first <<" " <second< return iterator //auto var = person.begin(); //cout<<"By var iterator " <first <<" "<second< return iterator //auto var = person.end(); // Not actual map //cout<<"By var iterator " <first <<" "<second<whether map is empty or not // 0 --> map is not empty // 1 --> map is empty person.clear(); // delete all the values in map cout<<"map is empty or not ? "<