├── LL-1 ├── lenght of LL (recursive) ├── print reverse ll ├── delete node(recursive) ├── insert a node recursive ├── print ith node ├── AppendLastNToFirst ├── delete node ├── palindrome LL ├── Length of LL └── Eliminate duplicates from LL ├── README.md ├── stack and queues ├── reverse stack ├── reverse queue ├── balanced parenthesis ├── stack using LL ├── queue using LL ├── check radundant brackets ├── minimum bracket reversal └── stock span ├── trees ├── post order traversal ├── height of tree ├── count nodes ├── replace with depth ├── contains x ├── structually identical ├── find sum of nodes ├── next larger ├── max data node ├── node with maximum child sum ├── second largest element in a tree (important) └── print level wise.cpp ├── binary trees ├── preorder ├── post order ├── height of a binary tree ├── Sum of all nodes ├── remove leaf nodes ├── mirror ├── find a node ├── nodes without siblings ├── is balanced ├── Print Level Wise ├── Level order traversal ├── diameter of tree ├── zig zag tree ├── level wise LL ├── Construct Tree from Preorder and Inorder ├── Construct Tree from Postorder and Inorder └── Min and Max of Binary Tree ├── LL 2 ├── reverse LL (iteratively) ├── find a node in LL( recursive) ├── reverse LL(recursive) ├── mid point of a LL ├── even after odd LL ├── delete every m node ├── merge two sorted LL ├── Bubble sort └── merge sort ├── Recursion 1 ├── Number of Digits ├── power ├── Print Numbers ├── Multiplication recursive ├── Sum Of Digit ├── Sum Of Array ├── Count Zeroes ├── Geometric Sum ├── First Index Of Number ├── Check Number ├── Check Palindrome ├── Last Index of Number └── All indices of a number ├── priority queues ├── check Max-heap ├── kth largest element in the array. ├── Merge K sorted arrays ├── K largest elements ├── K smallest elements ├── in place heap sort ├── Running median ├── max priority queues :: max heap sort ├── buy the ticket └── remove min :: min heap sort ├── z-revision ├── balanced parenthisis ├── stock sPan.cpp ├── Largest Piece.cpp └── Connecting Dots.cpp ├── time and space complexity analysis ├── check array rotation ├── rotate array ├── Find the Unique Element ├── Print Array intersection ├── Pair sum in array └── Triplet sum ├── .gitignore ├── Recursion 1b ├── Tower Of Hanoi ├── Pair Stars ├── String To Integer ├── Remove X └── Replace pi ├── BST ├── Construct BST from a Sorted Array ├── search in BST ├── Create & Insert Duplicate Node ├── Print Elements in Range ├── LCA in BST ├── LCA of Binary Tree ├── Replace with Sum of greater nodes ├── find path in BST ├── Path Sum Root to Leaf ├── Pair sum BInary Tree ├── check if binary tree is BST ├── largest BST in a binary tree ├── BST to Sorted LL ├── Print nodes at distance k from node ├── pair sum in BST └── BST class.cpp ├── hashmap ├── Extract Unique characters ├── Print Intersection ├── Maximum Frequency Number ├── Longest subset zero sum ├── Pair Sum to 0 ├── Pairs with difference K └── Longest consecutive Sequence ├── recursion 2 ├── binary search(recursively) ├── Print Keypad Combinations Code ├── Remove Duplicates Recursively ├── Replace Character Recursively ├── Print Permutations - String ├── Print Subset Sum to K ├── check ab ├── staircase ├── Return Permutations - String ├── Print all Codes - String ├── return keypad code ├── print subset of an array ├── quick sort code ├── return subset of an array ├── Return all codes - String ├── Return subsets sum to K └── Merge Sort Code ├── DP 1 ├── Staircase using Dp ├── No. of balanced BTs ├── Min Steps to 1 └── Minimum Count ├── Test ├── Does s contain t ? .cpp ├── Delete alternate nodes ├── Maximum Profit on App .cpp ├── Longest Leaf to root Path ├── Longest Leaf to root path ├── Next Number └── Check cousins ├── DP-2 ├── longest increasing subsequence ├── Loot Houses ├── all possible ways ├── Matrix Chain Multiplication (MCM) ├── shortest subsequence (pending) ├── coin tower ├── Maximum Square Matrix With All Zeros ├── Min Cost Path └── Ways To Make Coin Change ├── Graph 1 ├── largest piece ├── 3 cycle ├── islands ├── has path ├── is connected ├── all connected components ├── get path DFS ├── CODING ninjas ├── BFS Traversal ├── coding ninjas └── connecting dots ├── Graph 2 ├── dijkstra algorithm └── Kruskal's Algorithm ├── tries and huffman coding ├── pattern matching └── auto complete └── OOPS1 └── complex number class /LL-1/lenght of LL (recursive): -------------------------------------------------------------------------------- 1 | 2 | int length(Node *head) { 3 | 4 | if(head==NULL) 5 | return 0; 6 | 7 | return 1+ length(head->next); 8 | 9 | } 10 | 11 | -------------------------------------------------------------------------------- /LL-1/print reverse ll: -------------------------------------------------------------------------------- 1 | void print_linkedlist_spl(node*head) 2 | { 3 | //write your code here 4 | if(head==NULL) 5 | return; 6 | print_linkedlist_spl(head->next); 7 | cout<data<<" "; 8 | } 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # code_practice 2 | also check out competitive programming for CP, my templates and code snippets I use in sublime for auto-completion :D 3 | -------------------------------------------------------------------------------- /stack and queues/reverse stack: -------------------------------------------------------------------------------- 1 | void reverseStack(stack &s1, stack &s2) { 2 | // Write your code here 3 | int x; 4 | while(!s1.empty()) 5 | { 6 | x=s1.top(); 7 | s2.push(x); 8 | s1.pop(); 9 | } 10 | s1=s2; 11 | } 12 | -------------------------------------------------------------------------------- /trees/post order traversal: -------------------------------------------------------------------------------- 1 | 2 | void postOrder(TreeNode* root) { 3 | 4 | 5 | for(int i=0;ichildren.size();i++) 6 | { 7 | postOrder(root->children[i]); 8 | 9 | } 10 | cout<data<<" "; 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /stack and queues/reverse queue: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void reverseQueue(queue &q) { 4 | // Write your code here 5 | if(q.size()<=0) 6 | return; 7 | 8 | int x=q.front(); 9 | q.pop(); 10 | reverseQueue(q); 11 | 12 | q.push(x); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /binary trees/preorder: -------------------------------------------------------------------------------- 1 | Pre-order traversal is: Root LeftChild RightChild 2 | 3 | 4 | 5 | void preOrder(BinaryTreeNode *root) { 6 | if(!root)return; 7 | 8 | cout<data<<" "; 9 | 10 | preOrder(root->left); 11 | 12 | preOrder(root->right); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /binary trees/post order: -------------------------------------------------------------------------------- 1 | Post-order traversal is: LeftChild RightChild Root 2 | 3 | 4 | void postOrder(BinaryTreeNode *root) { 5 | if(!root)return; 6 | 7 | 8 | postOrder(root->left); 9 | 10 | postOrder(root->right); 11 | 12 | cout<data<<" "; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /LL 2/reverse LL (iteratively): -------------------------------------------------------------------------------- 1 | node* rev_linkedlist_itr(node* head) 2 | { 3 | //write your iterative code here 4 | node *p=head,*q=NULL,*r=NULL; 5 | while(p) 6 | { 7 | r=q; 8 | q=p; 9 | p=p->next; 10 | q->next=r; 11 | } 12 | 13 | return q; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Recursion 1/Number of Digits: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int count(int n){ 6 | if(n == 0){ 7 | return 0; 8 | } 9 | 10 | return count(n / 10) + 1; 11 | } 12 | 13 | int main(){ 14 | int n; 15 | cin >> n; 16 | 17 | cout << count(n) << endl; 18 | } 19 | -------------------------------------------------------------------------------- /Recursion 1/power: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int power(int x, int n) { 6 | 7 | if(n==0) 8 | return 1; 9 | 10 | return x*power(x,n-1); 11 | } 12 | int main(){ 13 | int x, n; 14 | cin >> x >> n; 15 | 16 | cout << power(x, n) << endl; 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /LL 2/find a node in LL( recursive): -------------------------------------------------------------------------------- 1 | int indexOfNRecursive(Node *head, int n) { 2 | 3 | if(head==NULL) 4 | return -1; 5 | if(head->data==n) 6 | return 0; 7 | 8 | int x=indexOfNRecursive(head->next,n); 9 | if(x==-1) 10 | {return x;} 11 | else 12 | return x+1; 13 | } 14 | -------------------------------------------------------------------------------- /Recursion 1/Print Numbers: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void print(int n){ 5 | if(n == 1){ 6 | cout << n << " "; 7 | return; 8 | } 9 | 10 | print(n - 1); 11 | cout << n << " "; 12 | } 13 | int main(){ 14 | int n; 15 | cin >> n; 16 | 17 | print(n); 18 | } 19 | -------------------------------------------------------------------------------- /priority queues/check Max-heap: -------------------------------------------------------------------------------- 1 | Given an array of integers, check whether it represents max-heap or not. 2 | Return true or false. 3 | 4 | bool checkMaxHeap(int arr[], int n){ 5 | 6 | for(int child=1; childnext; 11 | delete p; 12 | return head; 13 | } 14 | Node *x=deleteNodeRec(head->next,i-1); 15 | head->next=x; 16 | x=head; 17 | return head; 18 | } 19 | -------------------------------------------------------------------------------- /Recursion 1/Multiplication recursive: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int multiplyNumbers(int m, int n) { 6 | // Write your code here 7 | if (n==0) 8 | return 0; 9 | 10 | return m+multiplyNumbers(m,n-1); 11 | } 12 | 13 | 14 | 15 | 16 | int main() { 17 | int m, n; 18 | cin >> m >> n; 19 | cout << multiplyNumbers(m, n) << endl; 20 | } 21 | -------------------------------------------------------------------------------- /LL-1/insert a node recursive: -------------------------------------------------------------------------------- 1 | Node* insertNodeRec(Node *head, int i, int data) { 2 | 3 | if(i==0) 4 | { 5 | Node *p=new Node(data); 6 | p->next=head; 7 | head =p; 8 | return p; 9 | } 10 | 11 | if(head==NULL || i<0) 12 | return head; 13 | 14 | 15 | head->next=insertNodeRec(head->next,i-1,data); 16 | 17 | return head; 18 | } 19 | -------------------------------------------------------------------------------- /LL 2/reverse LL(recursive): -------------------------------------------------------------------------------- 1 | node *reverse_linked_list_rec(node *head) 2 | { 3 | //write your recursive code here 4 | if(head==NULL || head ->next ==NULL) 5 | return head; 6 | 7 | node* smallans=reverse_linked_list_rec(head->next); 8 | node*tail= head->next; 9 | tail->next=head; 10 | head ->next =NULL; 11 | 12 | return smallans; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Recursion 1/Sum Of Digit: -------------------------------------------------------------------------------- 1 | Write a recursive function that returns the sum of the digits of a given integer. 2 | 3 | #include 4 | using namespace std; 5 | 6 | int sumOfDigits(int n) { 7 | 8 | if(n==0) 9 | return 0; 10 | 11 | int rem=n%10; 12 | return rem+ sumOfDigits(n/10); 13 | } 14 | int main() { 15 | int n; 16 | cin >> n; 17 | cout << sumOfDigits(n) << endl; 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /binary trees/height of a binary tree: -------------------------------------------------------------------------------- 1 | Given a binary tree, find and return the height of given tree. 2 | 3 | 4 | int height(BinaryTreeNode *root) { 5 | int h=0; 6 | if(root==NULL) 7 | return h; 8 | 9 | int lefth= height(root->left); 10 | int righth= height(root->right); 11 | 12 | if(lefth>righth) 13 | return lefth +1; 14 | else 15 | return righth+1; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /binary trees/Sum of all nodes: -------------------------------------------------------------------------------- 1 | Given a binary tree, find and return the sum of all nodes. 2 | 3 | 4 | int sumOfAllNodes(BinaryTreeNode* root) { 5 | if(!root) 6 | return 0; 7 | 8 | int sum =root->data; 9 | 10 | int lsum=sumOfAllNodes (root->left); 11 | 12 | sum+=lsum; 13 | 14 | int rsum=sumOfAllNodes (root->right); 15 | 16 | sum+=rsum; 17 | 18 | return sum; 19 | } 20 | -------------------------------------------------------------------------------- /binary trees/remove leaf nodes: -------------------------------------------------------------------------------- 1 | 2 | BinaryTreeNode* removeLeafNodes(BinaryTreeNode *root) { 3 | // Write your code here 4 | if(root->left==NULL && root->right==NULL) 5 | { 6 | delete root; 7 | return NULL; 8 | } 9 | 10 | if(root->left) 11 | root->left=removeLeafNodes(root->left); 12 | if(root->right) 13 | root->right=removeLeafNodes(root->right); 14 | 15 | return root; 16 | } 17 | -------------------------------------------------------------------------------- /binary trees/mirror: -------------------------------------------------------------------------------- 1 | Mirror the given binary tree. That is, right child of every nodes should become left and left should become right. 2 | 3 | 4 | void mirrorBinaryTree(BinaryTreeNode* root) { 5 | if(!root) 6 | return; 7 | BinaryTreeNode* temp=root->left; 8 | 9 | root->left=root->right; 10 | root->right=temp; 11 | 12 | mirrorBinaryTree(root->left); 13 | mirrorBinaryTree(root->right); 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Recursion 1/Sum Of Array: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int sum(int input[], int n) { 5 | if(n==0) 6 | return 0; 7 | 8 | int total= input[0] + sum (input+1,n-1); 9 | return total; 10 | 11 | } 12 | 13 | int main(){ 14 | int n; 15 | cin >> n; 16 | 17 | int *input = new int[n]; 18 | 19 | for(int i = 0; i < n; i++) { 20 | cin >> input[i]; 21 | } 22 | 23 | cout << sum(input, n) << endl; 24 | } 25 | -------------------------------------------------------------------------------- /Recursion 1b/Tower Of Hanoi: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void towerOfHanoi(int n, char source, char auxiliary, char destination) { 5 | if(n==0) 6 | return; 7 | towerOfHanoi(n-1,source,destination,auxiliary); 8 | cout<> n; 17 | towerOfHanoi(n, 'a', 'b', 'c'); 18 | } 19 | -------------------------------------------------------------------------------- /trees/height of tree: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int height(TreeNode* root) { 4 | 5 | int h =1; 6 | 7 | if(root->children.size()==0) 8 | return h; 9 | 10 | int arr[root->children.size()]; 11 | for(int i=0;ichildren.size();i++) 12 | { 13 | arr[i]=height(root->children[i]); 14 | 15 | } 16 | sort(arr,arr+root->children.size(),greater()); 17 | h+=arr[0]; 18 | 19 | return h; 20 | } 21 | -------------------------------------------------------------------------------- /BST/Construct BST from a Sorted Array: -------------------------------------------------------------------------------- 1 | 2 | BinaryTreeNode* tree(int input[],int s ,int e) 3 | { 4 | if(s>e) 5 | return NULL; 6 | int mid=(s+e)/2; 7 | 8 | BinaryTreeNode* root=new BinaryTreeNode(input[mid]); 9 | 10 | root->left=tree(input,s,mid-1); 11 | root->right=tree(input,mid+1,e); 12 | return root; 13 | } 14 | BinaryTreeNode* constructTree(int *input, int n) { 15 | 16 | return tree(input,0,n-1); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /trees/count nodes: -------------------------------------------------------------------------------- 1 | Given a tree and an integer x, find and return the number of Nodes which are greater than x. 2 | 3 | 4 | int nodesGreaterThanX(TreeNode *root, int x) { 5 | 6 | int sum =0; 7 | 8 | if(root->data > x) 9 | sum++; 10 | 11 | 12 | for(int i=0;ichildren.size();i++) 13 | { 14 | int smallsum=nodesGreaterThanX(root->children[i], x) ; 15 | sum+=smallsum; 16 | } 17 | 18 | 19 | return sum; 20 | } 21 | -------------------------------------------------------------------------------- /LL-1/print ith node: -------------------------------------------------------------------------------- 1 | Given a linked list and a position i, print the node at ith position. 2 | If position i is greater than length of LL, then don't print anything. 3 | 4 | void printIthNode(Node *head, int i) { 5 | 6 | Node* temp = head; 7 | int count =0; 8 | while(temp) 9 | { 10 | if(i==count) 11 | { 12 | cout<< temp->data<next; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LL 2/mid point of a LL: -------------------------------------------------------------------------------- 1 | Given a linked list, find and return the midpoint. 2 | 3 | 4 | #include 5 | int length(node*head) 6 | { 7 | int count=0; 8 | while(head) 9 | { 10 | count++; 11 | head=head->next; 12 | } 13 | return count; 14 | } 15 | node* midpoint_linkedlist(node *head) 16 | { 17 | // Write your code here 18 | int x=ceil(length(head)/2); 19 | for(int i=1;inext; 22 | } 23 | 24 | return head; 25 | } 26 | -------------------------------------------------------------------------------- /trees/replace with depth: -------------------------------------------------------------------------------- 1 | in a given Generic Tree, replace each node with its depth value. 2 | You need to just update the data of each node, no need to return or print anything. 3 | 4 | 5 | void help(TreeNode *root, int depth) 6 | { 7 | root->data=depth; 8 | for(int i=0;ichildren.size();i++) 9 | { 10 | help(root->children[i] ,depth+1); 11 | } 12 | } 13 | 14 | void replaceWithDepthValue(TreeNode *root){ 15 | 16 | int depth=0; 17 | help(root,depth); 18 | } 19 | -------------------------------------------------------------------------------- /Recursion 1/Count Zeroes: -------------------------------------------------------------------------------- 1 | Given an integer n, count and return the number of zeros that are present in the given integer using recursion. 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | 8 | int countZeros(int n) { 9 | // Write your code here 10 | if(n==0) 11 | return 0; 12 | int rem=n%10; 13 | if(rem==0) 14 | return 1+countZeros(n/10); 15 | else 16 | return countZeros(n/10); 17 | } 18 | int main() { 19 | int n; 20 | cin >> n; 21 | cout << countZeros(n) << endl; 22 | } 23 | -------------------------------------------------------------------------------- /BST/search in BST: -------------------------------------------------------------------------------- 1 | Given a BST and an integer k. Find if the integer k is present in given BST or not. 2 | Return the node with data k if it is present, return null otherwise. 3 | 4 | 5 | BinaryTreeNode* searchInBST(BinaryTreeNode *root , int k){ 6 | if(root==NULL) 7 | return root; 8 | 9 | if(root->data== k) 10 | return root; 11 | 12 | 13 | if(root->data > k) 14 | return searchInBST(root->left , k); 15 | 16 | if( root->data < k ) 17 | return searchInBST(root->right , k); 18 | } 19 | -------------------------------------------------------------------------------- /trees/contains x: -------------------------------------------------------------------------------- 1 | Given a generic tree and an integer x, check if x is present in the given tree or not. 2 | Return true if x is present, return false otherwise. 3 | 4 | 5 | 6 | bool containsX(TreeNode* root, int x) { 7 | if(root->data==x) 8 | return true; 9 | 10 | 11 | bool ans=false; 12 | for(int i=0;ichildren.size();i++) 13 | { 14 | bool smallans=containsX(root->children[i],x); 15 | if(smallans!=ans && smallans==true) 16 | ans=smallans; 17 | } 18 | 19 | return ans; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /BST/Create & Insert Duplicate Node: -------------------------------------------------------------------------------- 1 | Given a Binary Tree with N number of nodes, for each node create a new duplicate node, 2 | and insert that duplicate as left child of the original node. 3 | 4 | 5 | void insertDuplicateNode(BinaryTreeNode *root) { 6 | // Write your code here 7 | if(root==NULL) 8 | return; 9 | 10 | BinaryTreeNode *duplicate = new BinaryTreeNode (root->data); 11 | duplicate->left=root->left; 12 | root->left=duplicate; 13 | 14 | insertDuplicateNode(duplicate->left); 15 | insertDuplicateNode(root->right); 16 | } 17 | -------------------------------------------------------------------------------- /hashmap/Extract Unique characters: -------------------------------------------------------------------------------- 1 | Given a string, you need to remove all the duplicates. 2 | That means, the output string should contain each character only once. The respective order of characters should remain same. 3 | 4 | #include 5 | char* uniqueChar(char *s){ 6 | // Write your code here 7 | unordered_map exists; 8 | int index = 0; 9 | for(int i=0;s[i]!='\0';i++) 10 | { 11 | if(exists[s[i]]==0) 12 | { 13 | s[index++] = s[i]; 14 | exists[s[i]]++; 15 | } 16 | } 17 | s[index]='\0'; 18 | return s; 19 | } 20 | -------------------------------------------------------------------------------- /recursion 2/binary search(recursively): -------------------------------------------------------------------------------- 1 | // input - input array 2 | // size - length of input array 3 | // element - value to be searched 4 | int B(int a[],int s,int e, int i) 5 | { 6 | if(s>e) 7 | return -1; 8 | int mid= (s+e)/2; 9 | if(a[mid]==i) return mid; 10 | if(a[mid]>i) return B(a,s,mid-1,i); 11 | if(a[mid]* root, int k1, int k2) { 6 | 7 | if ( NULL == root ) 8 | return; 9 | 10 | 11 | if ( k1 < root->data ) 12 | elementsInRangeK1K2(root->left, k1, k2); 13 | 14 | if ( k1 <= root->data && k2 >= root->data ) 15 | cout<data<<" "; 16 | 17 | 18 | if ( k2 > root->data ) 19 | elementsInRangeK1K2(root->right, k1, k2); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /recursion 2/Print Keypad Combinations Code: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | string key[]={" ", " ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 5 | 6 | void printKeypad(int num,string str=""){ 7 | /* 8 | Given an integer number print all the possible combinations of the keypad. You do not need to return anything just print them. 9 | */ 10 | if(num==0) 11 | { 12 | cout<* root, int x) { 5 | 6 | 7 | if(root->data==x) 8 | ans =true; 9 | 10 | bool ans=false; 11 | if(root->left) 12 | { bool leftans= isNodePresent(root->left,x); 13 | if(leftans) 14 | ans=leftans; 15 | } 16 | 17 | if(root->right) 18 | { bool rightans= isNodePresent(root->right,x); 19 | if(rightans) 20 | ans=rightans; 21 | } 22 | return ans; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Recursion 1/Geometric Sum: -------------------------------------------------------------------------------- 1 | Given k, find the geometric sum i.e. 2 | 1 + 1/2 + 1/4 + 1/8 + ... + 1/(2^k) 3 | using recursion. Return the answer. 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | double geometricSum(int k) { 11 | 12 | if(k==0) 13 | return 1; 14 | int no=2; 15 | for (int i=1;i> k; 29 | cout << fixed << setprecision(5); 30 | cout << geometricSum(k) << endl; 31 | } 32 | -------------------------------------------------------------------------------- /binary trees/nodes without siblings: -------------------------------------------------------------------------------- 1 | Given a binary tree, print all nodes that don’t have a sibling. 2 | 3 | 4 | void nodesWithoutSibling(BinaryTreeNode *root) { 5 | // Write your code here 6 | if(root==NULL) 7 | return; 8 | 9 | if(root->left && !root->right) 10 | { cout<left->data<left); 13 | } 14 | else if(!root->left && root->right) 15 | { cout<right->data<right); 18 | } 19 | else 20 | { 21 | nodesWithoutSibling(root->left); 22 | nodesWithoutSibling(root->right); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /priority queues/kth largest element in the array.: -------------------------------------------------------------------------------- 1 | Given an array A of random integers and an integer k, find and return the kth largest element in the array. 2 | Try to do this question in less than O(nlogn) time 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | int kthLargest(vector arr, int n, int k) 8 | { 9 | 10 | priority_queue pq; 11 | 12 | // push first k eements in the priority queue 13 | for(int i=0 ;isize 14 | int temp[z]; 15 | for(int i=0;i *root1, TreeNode * root2) { 6 | if(root1->data != root2->data) 7 | return false; 8 | 9 | if(root1->children.size() != root2->children.size()) 10 | return false; 11 | 12 | bool ans =true; 13 | for(int i=0;ichildren.size();i++) 14 | { 15 | bool smallans = isIdentical(root1->children[i],root2->children[i]); 16 | if(smallans == false) 17 | { ans=smallans; 18 | return ans; 19 | } 20 | } 21 | return ans; 22 | 23 | } 24 | -------------------------------------------------------------------------------- /binary trees/is balanced: -------------------------------------------------------------------------------- 1 | Given a binary tree, check if its balanced i.e. depth of left and right subtrees of every node differ by at max 1. 2 | Return true if given binary tree is balanced, false otherwise. 3 | 4 | 5 | #include 6 | 7 | int height(BinaryTreeNode *root) 8 | { if(root==NULL) 9 | return 0; 10 | 11 | return 1+max(height(root->left),height(root->right)); 12 | } 13 | bool isBalanced(BinaryTreeNode *root) { 14 | 15 | if (root == NULL) 16 | return 1; 17 | int l=height(root->left); 18 | int r=height(root->right); 19 | 20 | if ( ( abs(l- r) ==0 || abs(l-r) == 1 ) && isBalanced(root->left) && isBalanced(root->right)) 21 | return 1; 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /LL-1/AppendLastNToFirst: -------------------------------------------------------------------------------- 1 | Given a linked list and an integer n, append the last n elements of the LL to front. 2 | 3 | int length(node *head) { 4 | 5 | int count=0; 6 | while(head) 7 | { 8 | count++; 9 | head=head->next; 10 | } 11 | return count; 12 | } 13 | node* append_LinkedList(node* head,int n) 14 | { 15 | //write your code here 16 | node *p=head; 17 | node *q=head; 18 | for(int i=1;inext; 21 | } 22 | for(int i=1;inext; 25 | } 26 | q->next=head; //circular LL 27 | head=p->next; 28 | p->next=NULL; //breaking that circular LL 29 | 30 | return head; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Recursion 1/First Index Of Number: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int help(int input[],int size,int x,int i){ 5 | 6 | if(size==0) 7 | return -1; 8 | if(input[0]==x) 9 | return i; 10 | 11 | help(input+1,size-1,x,i+1); 12 | } 13 | 14 | int firstIndex(int input[], int size, int x) { 15 | int i=0; 16 | int ans=help(input, size, x, i); 17 | return ans; 18 | } 19 | 20 | 21 | int main(){ 22 | int n; 23 | cin >> n; 24 | 25 | int *input = new int[n]; 26 | 27 | for(int i = 0; i < n; i++) { 28 | cin >> input[i]; 29 | } 30 | 31 | int x; 32 | 33 | cin >> x; 34 | 35 | cout << firstIndex(input, n, x) << endl; 36 | 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /trees/find sum of nodes: -------------------------------------------------------------------------------- 1 | //recursive 2 | int sumOfNodes(TreeNode* root) { 3 | int sum =root->data; 4 | 5 | for(int i=0;ichildren.size();i++) 6 | { 7 | sum+=sumOfNodes(root->children[i]); 8 | } 9 | return sum; 10 | } 11 | 12 | //level wise 13 | 14 | int sumOfNodes(TreeNode* root) { 15 | 16 | int sum=0; 17 | queue*> pn; 18 | pn.push(root); 19 | 20 | while(pn.size()!=0) 21 | { 22 | TreeNode* front=pn.front(); 23 | pn.pop(); 24 | sum=sum+front->data; 25 | 26 | for(int i=0;ichildren.size();i++) 27 | { 28 | pn.push(front->children[i]); 29 | } 30 | } 31 | return sum; 32 | } 33 | -------------------------------------------------------------------------------- /hashmap/Print Intersection: -------------------------------------------------------------------------------- 1 | Given two random integer arrays, print their intersection. 2 | That is, print all the elements that are present in both the given arrays. 3 | Input arrays can contain duplicate elements. 4 | 5 | #include 6 | 7 | void intersection(int input1[], int input2[], int size1, int size2) { 8 | unordered_map m1 ; 9 | 10 | 11 | for(int i=0 ;i0) 17 | { 18 | cout< 2 | 3 | using namespace std; 4 | 5 | bool checkNumber(int input[], int size, int x) { 6 | if(size==0) 7 | return false; 8 | 9 | if(input[0]==x) 10 | return true; 11 | 12 | bool checksmaller= checkNumber(input +1,size-1,x); 13 | return checksmaller; 14 | 15 | } 16 | 17 | 18 | int main(){ 19 | int n; 20 | cin >> n; 21 | 22 | int *input = new int[n]; 23 | 24 | for(int i = 0; i < n; i++) { 25 | cin >> input[i]; 26 | } 27 | 28 | int x; 29 | 30 | cin >> x; 31 | 32 | if(checkNumber(input, n, x)) { 33 | cout << "true" << endl; 34 | } 35 | else { 36 | cout << "false" << endl; 37 | } 38 | } 39 | 40 | 41 | -------------------------------------------------------------------------------- /recursion 2/Replace Character Recursively: -------------------------------------------------------------------------------- 1 | Given an input string S and two characters c1 and c2, you need to replace every occurrence of character c1 with character c2 in the given string. 2 | Do this recursively. 3 | Input Format : 4 | Line 1 : Input String S 5 | Line 2 : Character c1 and c2 (separated by space) 6 | Output Format : 7 | Updated string 8 | Constraints : 9 | 1 <= Length of String S <= 10^6 10 | Sample Input : 11 | abacd 12 | a x 13 | Sample Output : 14 | xbxcd 15 | 16 | void replaceCharacter(char input[], char c1, char c2) { 17 | 18 | if(input[0]=='\0') 19 | return; 20 | if(input[0]!=c1) 21 | replaceCharacter(input+1,c1,c2); 22 | else 23 | { 24 | input[0]=c2; 25 | replaceCharacter(input+1,c1,c2); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /priority queues/Merge K sorted arrays: -------------------------------------------------------------------------------- 1 | Given k different arrays, which are sorted individually (in ascending order). 2 | You need to merge all the given arrays such that output array should be sorted (in ascending order). 3 | 4 | #include 5 | #include 6 | vector mergeKSortedArrays(vector*> input){ 7 | 8 | priority_queue < int ,vector , greater > pq; 9 | for(int i=0 ; isize() ;j++) 12 | { 13 | pq.push(input[i]->at(j)); 14 | } 15 | } 16 | 17 | vector ans; 18 | 19 | while(!pq.empty()) 20 | { 21 | ans.push_back(pq.top()); 22 | pq.pop(); 23 | } 24 | 25 | return ans; 26 | } 27 | -------------------------------------------------------------------------------- /BST/LCA in BST: -------------------------------------------------------------------------------- 1 | Given a binary search tree and two nodes, find LCA(Lowest Common Ancestor) of the given two nodes in the BST. 2 | Read about LCA if you are having doubts about the definition. 3 | 4 | 5 | 6 | int lcaInBST(BinaryTreeNode* root , int val1 , int val2){ 7 | 8 | if(root==NULL) 9 | return -1; 10 | if(root->data == val1 || root->data== val2) 11 | return root->data; 12 | 13 | int left=lcaInBST(root->left,val1,val2); 14 | int right =lcaInBST(root->right,val1,val2); 15 | 16 | if(left== -1 && right == -1) 17 | return -1; 18 | else if( left!=-1 &&right ==-1) 19 | return left; 20 | else if( left==-1 &&right !=-1) 21 | return right; 22 | else 23 | return root->data; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /BST/LCA of Binary Tree: -------------------------------------------------------------------------------- 1 | Given a binary tree and two nodes, find LCA (Lowest Common Ancestor) of the given two nodes in Binary Tree. 2 | Read about LCA if you are having doubts about the definition. 3 | 4 | 5 | int lcaBinaryTree(BinaryTreeNode * root , int val1, int val2){ 6 | if(root==NULL) 7 | return -1; 8 | if(root->data == val1 || root->data== val2) 9 | return root->data; 10 | 11 | int left=lcaBinaryTree(root->left,val1,val2); 12 | int right =lcaBinaryTree(root->right,val1,val2); 13 | 14 | if(left== -1 && right == -1) 15 | return -1; 16 | else if( left!=-1 &&right ==-1) 17 | return left; 18 | else if( left==-1 &&right !=-1) 19 | return right; 20 | else 21 | return root->data; 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Recursion 1b/Pair Stars: -------------------------------------------------------------------------------- 1 | Given a string, 2 | compute recursively a new string where identical chars that are adjacent in the original string are separated from each other by a "*". 3 | 4 | #include 5 | using namespace std; 6 | 7 | #include 8 | void help(char a[],int s) 9 | { 10 | if(s==0) 11 | return; 12 | if(a[0]==a[1]) 13 | { 14 | for(int i=s;i>0;i--) 15 | { 16 | a[i+1]=a[i]; 17 | } 18 | a[1]='*'; 19 | s=s+1; 20 | } 21 | help(a+1,s-1); 22 | } 23 | 24 | 25 | void pairStar(char input[]) { 26 | 27 | int size=strlen(input); 28 | help(input,size); 29 | } 30 | 31 | int main() { 32 | char input[100]; 33 | cin.getline(input, 100); 34 | pairStar(input); 35 | cout << input << endl; 36 | } 37 | -------------------------------------------------------------------------------- /hashmap/Maximum Frequency Number: -------------------------------------------------------------------------------- 1 | You are given an array of integers that contain numbers in random order. 2 | Write a program to find and return the number which occurs the maximum times in the given input. 3 | If two or more elements contend for the maximum frequency, return the element which occurs in the array first. 4 | 5 | #include 6 | int highestFrequency(int *input, int n){ 7 | 8 | map max; 9 | for(int i=0 ;i value) 22 | { 23 | key=input[i]; 24 | value = max[input[i]]; 25 | } 26 | } 27 | return key; 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /binary trees/Print Level Wise: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void printLevelWise(BinaryTreeNode *root) { 4 | 5 | if(!root) 6 | return; 7 | 8 | queue *> pn ; 9 | pn.push(root); 10 | 11 | while(!pn.empty()) 12 | { 13 | BinaryTreeNode * front= pn.front(); 14 | pn.pop(); 15 | cout<data<<":"; 16 | 17 | if(front->left) 18 | { pn.push(front->left); 19 | cout<<"L:"<left->data; 20 | } 21 | else 22 | cout<<"L:-1"; 23 | 24 | cout<<","; 25 | 26 | if(front->right) 27 | {pn.push(front->right); 28 | cout<<"R:"<right->data< *root,int sum) 7 | { 8 | if(root==NULL) 9 | return sum; 10 | 11 | sum=replace(root->right,sum); 12 | sum=sum +root->data; 13 | root->data=sum; 14 | sum =replace(root->left,sum); 15 | 16 | return sum; 17 | 18 | } 19 | void replaceWithLargerNodesSum(BinaryTreeNode *root) { 20 | if(root==NULL)return; 21 | int ans =replace(root,0); 22 | 23 | return ; 24 | } 25 | -------------------------------------------------------------------------------- /Recursion 1b/String To Integer: -------------------------------------------------------------------------------- 1 | Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer. 2 | 3 | #include 4 | using namespace std; 5 | 6 | #include 7 | 8 | #include 9 | 10 | int help(char *a,int s) 11 | { 12 | int p=a[0]; 13 | p=p-48; 14 | 15 | if(s==1) 16 | { 17 | return p; 18 | } 19 | 20 | return (p* pow(10,s-1)+ help(a+1,s-1)); 21 | } 22 | 23 | int stringToNumber(char input[]) { 24 | 25 | int size=strlen(input); 26 | int ans=help(input,size); 27 | return ans; 28 | } 29 | 30 | int main() { 31 | char input[50]; 32 | cin >> input; 33 | cout << stringToNumber(input) << endl; 34 | } 35 | -------------------------------------------------------------------------------- /DP-2/longest increasing subsequence: -------------------------------------------------------------------------------- 1 | Given an array with N elements, 2 | you need to find the length of the longest subsequence of a given sequence such that 3 | all elements of the subsequence are sorted in strictly increasing order. 4 | 5 | using namespace std; 6 | 7 | 8 | int longestIncreasingSubsequence(int arr[], int n) 9 | { 10 | int dp[n]; 11 | //dp[i] stores length of lis ending till here 12 | // if arr[i+1] is greater the some arr[0.....i] add to that length and store for the max 13 | dp[0] = 1; 14 | for (int i = 1; i < n ; i++) 15 | { 16 | int ans = 0; 17 | 18 | for (int j = i - 1 ; j >= 0 ; j--) 19 | { 20 | if (arr[j] < arr[i]) 21 | { 22 | ans = max(dp[j], ans); 23 | } 24 | } 25 | dp[i] = ans + 1; 26 | } 27 | int res = 0; 28 | for (int i = 0 ; i < n ; i++) 29 | res = max(dp[i], res); 30 | return res; 31 | } 32 | -------------------------------------------------------------------------------- /time and space complexity analysis/Find the Unique Element: -------------------------------------------------------------------------------- 1 | Given an integer array of size 2N + 1. In this given array, N numbers are present twice and one number is present only once in the array. 2 | You need to find and return that number which is unique in the array. 3 | 4 | int FindUnique(int arr[], int size){ 5 | /* Don't write main(). 6 | * Don't read input, it is passed as function argument. 7 | * Return output and don't print it. 8 | * Taking input and printing output is handled automatically. 9 | */ 10 | for(int i=0;i 4 | #include 5 | using namespace std; 6 | int lengthOfLongestSubsetWithZeroSum(int* arr, int n){ 7 | // Write your code here 8 | 9 | unordered_map m; 10 | 11 | 12 | int length=0; 13 | int sum=0; 14 | 15 | for(int i=0 ;i0) 26 | { 27 | length=max(length,i-m[sum]); 28 | } 29 | else 30 | { 31 | m[sum]=i; 32 | } 33 | } 34 | 35 | return length; 36 | } 37 | 38 | 39 | -------------------------------------------------------------------------------- /binary trees/Level order traversal: -------------------------------------------------------------------------------- 1 | Given a binary tree, print the level order traversal. Make sure each level start in new line. 2 | 3 | 4 | void printLevelATNewLine(BinaryTreeNode *root) { 5 | // Write your code here 6 | if(root==NULL) 7 | return; 8 | 9 | queue *> pn; 10 | 11 | pn.push(root); 12 | pn.push(NULL); 13 | 14 | while(pn.size()!=0) 15 | { 16 | BinaryTreeNode *front=pn.front(); 17 | pn.pop(); 18 | 19 | if(front==NULL) 20 | { if(pn.size()==0) 21 | break; 22 | cout<data<<" "; 28 | 29 | if(front->left) 30 | pn.push(front->left); 31 | if(front->right) 32 | pn.push(front->right); 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /DP-2/Loot Houses: -------------------------------------------------------------------------------- 1 | A thief wants to loot houses. He knows the amount of money in each house. He cannot loot two consecutive houses. Find the maximum amount of money he can loot. 2 | 3 | 4 | #include 5 | int max( int a, int b ) 6 | { 7 | return a>b?a:b; 8 | } 9 | //dp 10 | int getmaxmoney(int arr[], int n, int* dp) 11 | { 12 | dp[0]=arr[0]; 13 | dp[1]=max(arr[0],arr[1]); 14 | 15 | for(int i=2 ;i< n ;i++) 16 | { 17 | dp[i]=max(dp[i-1],dp[i-2]+arr[i]); 18 | } 19 | return dp[n-1]; 20 | } 21 | int getMaxMoney(int arr[], int n) 22 | { 23 | int dp[n]; 24 | 25 | return getmaxmoney(arr,n, dp); 26 | } 27 | 28 | 29 | // recursive 30 | 31 | int getMaxMoney(int arr[], int n){ 32 | 33 | if(n<=0) return 0; 34 | 35 | int a= getMaxMoney(arr+2,n-2); 36 | int b=getMaxMoney(arr+1,n-1); 37 | 38 | return max(a+arr[0] , b); 39 | } 40 | -------------------------------------------------------------------------------- /Recursion 1b/Remove X: -------------------------------------------------------------------------------- 1 | Given a string, compute recursively a new string where all 'x' chars have been removed. 2 | Sample Input 1 : 3 | xaxb 4 | Sample Output 1: 5 | ab 6 | 7 | #include 8 | using namespace std; 9 | #include 10 | 11 | void help(char input[],int size ,int a) 12 | { 13 | if(input[a]=='\0') 14 | return; 15 | if(input[a]=='x') 16 | { 17 | for(int i=a;i* nextLargerElement(TreeNode *root, int n) { 6 | 7 | if(root==NULL) 8 | return NULL; ///edge case 9 | 10 | TreeNode*max =NULL; 11 | 12 | if(root->data > n) 13 | max=root; 14 | 15 | for(int i=0;ichildren.size();i++) 16 | { 17 | TreeNode*childmax= nextLargerElement(root->children[i], n); 18 | 19 | if(childmax==NULL) 20 | {continue;} 21 | 22 | else 23 | { 24 | if(max==NULL) 25 | max=childmax; 26 | else if(childmax->data > n && childmax->data < max->data) 27 | max= childmax; 28 | } 29 | } 30 | 31 | return max; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Recursion 1/Check Palindrome: -------------------------------------------------------------------------------- 1 | Check if a given String S is palindrome or not (using recursion). Return true or false. 2 | 3 | #include 4 | using namespace std; 5 | #include 6 | 7 | bool help(char a[],int start, int end){ 8 | 9 | if(start >=end ) 10 | return true; 11 | 12 | if(a[start]!=a[end]) 13 | return false; 14 | 15 | bool smallcheck= help(a,start+1,end-1); 16 | return smallcheck; 17 | } 18 | 19 | 20 | bool checkPalindrome(char input[]) { 21 | 22 | int start =0; 23 | // int end = sizeof(input)/sizeof(*input)-1; 24 | int end = strlen(input)-1; 25 | 26 | return help(input, start, end) ; 27 | 28 | } 29 | int main() { 30 | char input[50]; 31 | cin >> input; 32 | 33 | if(checkPalindrome(input)) { 34 | cout << "true" << endl; 35 | } 36 | else { 37 | cout << "false" << endl; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Recursion 1/Last Index of Number: -------------------------------------------------------------------------------- 1 | ///starting from first 2 | int lastIndex(int input[], int size, int x) { 3 | 4 | if(size==0) return -1; 5 | 6 | int index = lastIndex(input+1, size-1,x); 7 | 8 | if(index != -1) return index+1; 9 | 10 | if(input[0]==x) 11 | return 0; 12 | 13 | return -1; 14 | 15 | } 16 | ///starting from last 17 | 18 | int lastIndex(int input[], int size, int x) { 19 | 20 | if(size==0) 21 | return -1; 22 | 23 | if(input[size-1]==x) 24 | return size-1; 25 | 26 | return lastIndex(input,size-1,x); 27 | 28 | } 29 | int main(){ 30 | int n; 31 | cin >> n; 32 | 33 | int *input = new int[n]; 34 | 35 | for(int i = 0; i < n; i++) { 36 | cin >> input[i]; 37 | } 38 | 39 | int x; 40 | 41 | cin >> x; 42 | 43 | cout << lastIndex(input, n, x) << endl; 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Recursion 1b/Replace pi: -------------------------------------------------------------------------------- 1 | Given a string, compute recursively a new string where all appearances of "pi" have been replaced by "3.14". 2 | 3 | #include 4 | using namespace std; 5 | #include 6 | 7 | using namespace std; 8 | 9 | #include 10 | 11 | void help(char input[], int size) 12 | { 13 | if(size==0) 14 | return; 15 | if(input[0]=='p') 16 | { 17 | if(input[1]=='i') 18 | { 19 | for(int i=size;i>1;i--) 20 | { 21 | input[i+2]=input[i]; 22 | } 23 | input[0]='3'; 24 | input[1]='.'; 25 | input[2]='1'; 26 | input[3]='4'; 27 | size =size +2; 28 | 29 | } 30 | } 31 | 32 | help(input+1,size-1); 33 | } 34 | int main() { 35 | char input[10000]; 36 | cin.getline(input, 10000); 37 | replacePi(input); 38 | cout << input << endl; 39 | } 40 | -------------------------------------------------------------------------------- /priority queues/K largest elements: -------------------------------------------------------------------------------- 1 | You are given with an integer k and an array of integers that contain numbers in random order. 2 | Write a program to find k largest numbers from given array. You need to save them in an array and return it. 3 | Time complexity should be O(nlogk) and space complexity should be not more than O(k). 4 | 5 | #include 6 | #include 7 | vector kLargest(int input[], int n, int k){ 8 | 9 | priority_queue , greater> pq; 10 | 11 | for(int i=0 ; i ans; 24 | 25 | while(!pq.empty()) 26 | { 27 | ans.push_back(pq.top()); 28 | pq.pop(); 29 | } 30 | 31 | return ans; 32 | } 33 | -------------------------------------------------------------------------------- /Test/Delete alternate nodes: -------------------------------------------------------------------------------- 1 | Given a Singly Linked List of integers, delete all the alternate nodes in the list. 2 | Example: 3 | List: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> null 4 | Alternate nodes will be: 20, 40, and 60. 5 | 6 | Hence after deleting, the list will be: 7 | Output: 10 -> 30 -> 50 -> null 8 | 9 | 10 | void delete_alternate_node_LinkedList(Node *head) { 11 | 12 | if(head==NULL) 13 | return; 14 | if(head->next==NULL) 15 | return; 16 | 17 | int x=length(head); 18 | 19 | Node *p=head; 20 | Node *q=head; 21 | 22 | for(int i=2 ; i next; 24 | Node *t=p; 25 | p=p->next; 26 | q->next=p; 27 | delete t; 28 | q=p; 29 | } 30 | 31 | if(x%2==0) 32 | { 33 | p=p->next; 34 | q->next=NULL; 35 | delete p; 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Test/Maximum Profit on App .cpp: -------------------------------------------------------------------------------- 1 | You have made a smartphone app and want to set its price such that the profit earned is maximised. 2 | There are certain buyers who will buy your app only if their budget is greater than or equal to your price. 3 | You will be provided with a list of size N having budgets of buyers and you need to return the maximum profit that you can earn. 4 | Lets say you decide that price of your app is Rs. x and there are N number of buyers. So maximum profit you can earn is : 5 | m * x 6 | where m is total number of buyers whose budget is greater than or equal to x. 7 | 8 | 9 | 10 | #include 11 | int maximumProfit(int budget[], int n) { 12 | // Write your code here 13 | sort(budget , budget+n); 14 | 15 | int temp[n]; 16 | 17 | for(int i=0;i* findPath(BinaryTreeNode *root , int k){ 6 | if(root==NULL) 7 | { 8 | return NULL; 9 | } 10 | 11 | if(root->data == k ) 12 | { 13 | vector *v = new vector (); 14 | v->push_back(k); 15 | return v; 16 | } 17 | 18 | vector *left=findPath(root->left,k); 19 | if(left) 20 | { 21 | left->push_back(root->data); 22 | return left; 23 | } 24 | else 25 | { 26 | vector *right=findPath(root->right,k); 27 | 28 | if(right) 29 | { 30 | right->push_back(root->data); 31 | return right; 32 | } 33 | } 34 | 35 | return NULL; 36 | } 37 | -------------------------------------------------------------------------------- /LL 2/even after odd LL: -------------------------------------------------------------------------------- 1 | Arrange elements in a given Linked List such that, all even numbers are placed after odd numbers. Respective order of elements should remain same. 2 | Note: Input and Output has already managed for you. You don't need to print the elements, instead return the head of updated LL. 3 | 4 | 5 | node* arrange_LinkedList(node* head) 6 | { 7 | node *even= new node(0); 8 | node *etail=even; 9 | 10 | node *odd=new node(0); 11 | node *otail=odd; 12 | 13 | while(head) 14 | { 15 | if(head->data%2==0) 16 | { 17 | 18 | etail->next=head; 19 | etail=head; 20 | head=head->next; 21 | etail->next=NULL; 22 | } 23 | else 24 | { 25 | otail->next=head; 26 | otail=head; 27 | head=head->next; 28 | otail->next=NULL; 29 | } 30 | } 31 | otail->next=even->next; 32 | return odd->next; 33 | } 34 | -------------------------------------------------------------------------------- /recursion 2/Print Permutations - String: -------------------------------------------------------------------------------- 1 | Given a string, find and print all the possible permutations of the input string. 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | void permute(string a, int l, int r) 8 | { 9 | // Base case 10 | if (l == r) 11 | cout< 34 | 35 | using namespace std; 36 | 37 | int main(){ 38 | string input; 39 | cin >> input; 40 | printPermutations(input); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /LL-1/delete node: -------------------------------------------------------------------------------- 1 | Given a linked list and a position i, delete the node of ith position from Linked List iteratively. 2 | If position i is greater than length of LL, then you should return the same LL without any change. 3 | Indexing starts from 0. You don't need to print the elements, just delete the node and return the head of updated LL. 4 | 5 | 6 | int length(Node *head) { 7 | 8 | int count=0; 9 | while(head) 10 | { 11 | count++; 12 | head=head->next; 13 | } 14 | return count; 15 | } 16 | Node* deleteNode(Node *head, int i) { 17 | 18 | Node *p=head; 19 | Node *q=NULL; 20 | 21 | if(i<0||i>=length(head)) 22 | { } 23 | else if(i==0) 24 | { 25 | head=p->next; 26 | delete p; 27 | } 28 | else 29 | { 30 | for(int j=0;jnext; 34 | } 35 | q->next=p->next; 36 | delete p; 37 | } 38 | return head; 39 | } 40 | -------------------------------------------------------------------------------- /trees/max data node: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // level wise 4 | 5 | TreeNode* maxDataNode(TreeNode* root) { 6 | TreeNode *max=new TreeNode(INT_MIN); 7 | queue*> pn; 8 | pn.push(root); 9 | 10 | while(pn.size()!=0) 11 | { 12 | TreeNode* front=pn.front(); 13 | pn.pop(); 14 | if(front->data > max->data) 15 | max=front; 16 | 17 | for(int i=0;ichildren.size();i++) 18 | { 19 | pn.push(front->children[i]); 20 | } 21 | } 22 | return max; 23 | 24 | } 25 | 26 | 27 | //recursive 28 | 29 | TreeNode* maxDataNode(TreeNode* root) { 30 | 31 | TreeNode *max=new TreeNode(root->data); 32 | 33 | for(int i=0;ichildren.size();i++) 34 | { 35 | TreeNode *child=maxDataNode(root->children[i]); 36 | if(child->data > max->data) 37 | max=child; 38 | } 39 | 40 | return max; 41 | } 42 | -------------------------------------------------------------------------------- /BST/Path Sum Root to Leaf: -------------------------------------------------------------------------------- 1 | Given a binary tree and a number k, 2 | print out all root to leaf paths where the sum of all nodes value is same as the given number k. 3 | 4 | 5 | #include 6 | 7 | void rootToLeafPathsSumToK(BinaryTreeNode *root, int k,vector path) 8 | { 9 | if(root==NULL) 10 | return; 11 | 12 | path.push_back(root->data); 13 | k=k- root->data; 14 | 15 | if(!root->left && !root->right) // leaf node 16 | { 17 | if(k==0) 18 | { 19 | for(int i : path) 20 | { 21 | cout<< i<<" "; 22 | } 23 | cout<left,k,path); 29 | rootToLeafPathsSumToK(root->right,k,path); 30 | 31 | } 32 | void rootToLeafPathsSumToK(BinaryTreeNode *root, int k) { 33 | // Write your code here 34 | vector v; 35 | rootToLeafPathsSumToK(root,k,v); 36 | return; 37 | } 38 | -------------------------------------------------------------------------------- /LL-1/palindrome LL: -------------------------------------------------------------------------------- 1 | Check if a given linked list is palindrome or not. Return true or false. 2 | 3 | int length(node *head) { 4 | 5 | int count=0; 6 | while(head) 7 | { 8 | count++; 9 | head=head->next; 10 | } 11 | return count; 12 | } 13 | 14 | node *reverse(node*head2) 15 | { 16 | node *p=head2,*q=NULL,*r=NULL; 17 | while(p) 18 | { 19 | r=q; 20 | q=p; 21 | p=p->next; 22 | q->next=r; 23 | } 24 | head2=q; 25 | return q; 26 | } 27 | 28 | bool check_palindrome(node* head) 29 | { 30 | //write your code here 31 | node *p=head; 32 | int x=length(head)/2; 33 | 34 | for(int i=1;inext; 37 | } 38 | node *head2=p->next; 39 | p->next=NULL; 40 | head2= reverse(head2); 41 | 42 | while(head&&head2) 43 | { 44 | if(head->data!=head2->data) 45 | return false; 46 | head=head->next; 47 | head2=head2->next; 48 | } 49 | return true; 50 | } 51 | -------------------------------------------------------------------------------- /z-revision/stock sPan.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int* stockSpan(int *arr, int size) { 3 | // Write your code here 4 | int * ans = new int [size]; 5 | 6 | stack < pair > s ; 7 | 8 | int index = 0 ; 9 | 10 | for(int i = 0 ; i< size ; i++) 11 | { 12 | if(s.size()==0) 13 | { 14 | ans [ index++] = -1; 15 | } 16 | else if( s.top().first >= arr[i]) 17 | { 18 | ans[index++] = s.top().second; 19 | } 20 | else 21 | { 22 | while( s.size() and s.top().first< arr[i]) 23 | s.pop(); 24 | if(s.size()==0) 25 | { 26 | ans [index++] = -1; 27 | } 28 | else if( s.top().first >= arr[i]) 29 | { 30 | ans[index++] = s.top().second; 31 | } 32 | } 33 | s.push({ arr[i] , i }); 34 | } 35 | for(int i =0 ; i< size ; i++) 36 | ans[i] = i- ans[i]; 37 | 38 | return ans ; 39 | 40 | } 41 | -------------------------------------------------------------------------------- /hashmap/Pair Sum to 0: -------------------------------------------------------------------------------- 1 | Given a random integer array A of size N. Find and print the pair of elements in the array which sum to 0. 2 | Array A can contain duplicate elements. 3 | While printing a pair, print the smaller element first. 4 | That is, if a valid pair is (6, -6) print "-6 6". There is no constraint that out of 5 pairs which have to be printed in 1st line. 5 | You can print pairs in any order, just be careful about the order of elements in a pair. 6 | 7 | #include 8 | void PairSum(int *input, int n) { 9 | 10 | map m; 11 | 12 | for(int i=0 ;i0) 18 | { 19 | int x= m[-input[i]]; 20 | while(x>0) 21 | {if(input[i] > -input[i]) 22 | cout << -input[i] << " "<< input[i] < 2 | 3 | bool checkBalanced(char *exp) { 4 | // Write your code here 5 | 6 | stack s; 7 | for(int i=0;exp[i]!='\0';i++) 8 | { 9 | if(exp[i]=='[' || exp[i]=='(' || exp[i]=='{' ) 10 | s.push(exp[i]); 11 | if(s.empty() && (exp[i]==']' || exp[i]==')' || exp[i]=='}') ) 12 | return false; 13 | 14 | 15 | if(exp[i]==']') 16 | { if(s.top()=='[') 17 | s.pop(); 18 | else 19 | return false; 20 | } 21 | 22 | if(exp[i]==')') 23 | { if(s.top()=='(') 24 | s.pop(); 25 | else 26 | return false; 27 | } 28 | 29 | if(exp[i]=='}') 30 | { if(s.top()=='{') 31 | s.pop(); 32 | else 33 | return false; 34 | } 35 | 36 | 37 | } 38 | if(s.empty()) 39 | return true ; 40 | else 41 | return false; 42 | } 43 | -------------------------------------------------------------------------------- /DP 1/No. of balanced BTs: -------------------------------------------------------------------------------- 1 | Given an integer h, find the possible number of balanced binary trees of height h. 2 | You just need to return the count of possible binary trees which are balanced. 3 | This number can be huge, so return output modulus 10^9 + 7. 4 | 5 | 6 | //brute force 7 | #include 8 | int balancedBTs(int h) { 9 | if(h<=1) return 1; 10 | 11 | int x= balancedBTs(h-1); 12 | int y =balancedBTs(h-2); 13 | int mod = (int)(pow(10,9) + 7); 14 | 15 | int temp1=(int) (((long)(x)*x)%mod); 16 | int temp2=(int) ((2*(long)(x)*y)%mod); 17 | 18 | int ans = (temp1 +temp2 ) %mod; 19 | 20 | return ans; 21 | } 22 | 23 | // dp 24 | #include 25 | int binaryTreesOfHeightH(int h) { 26 | 27 | int dp[h+1]; 28 | 29 | dp[0]=1; 30 | dp[1]=1; 31 | 32 | int mod = (int) (pow(10,9)+ 7); 33 | for(int i=2 ;i<=h; i++) 34 | { 35 | dp[i]=(int)( ( (long)(dp[i-1])*dp[i-1] )%mod + (2*(long)(dp[i-1])*dp[i-2])%mod ) % mod; 36 | 37 | } 38 | 39 | return dp[h]; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /recursion 2/Print Subset Sum to K: -------------------------------------------------------------------------------- 1 | Given an array A and an integer K, print all subsets of A which sum to K. 2 | 3 | #include 4 | using namespace std; 5 | #include 6 | 7 | void help(int input[], int size, int k ,vector ans) 8 | { 9 | if(size==0) 10 | { 11 | if(k==0) 12 | { 13 | for(int i: ans) 14 | cout< ans; 32 | 33 | help(input,size,k,ans); 34 | 35 | } 36 | 37 | 38 | int main() { 39 | int input[1000],length,k; 40 | cin >> length; 41 | for(int i=0; i < length; i++) 42 | cin >> input[i]; 43 | cin>>k; 44 | printSubsetSumToK(input, length,k); 45 | } 46 | -------------------------------------------------------------------------------- /BST/Pair sum BInary Tree: -------------------------------------------------------------------------------- 1 | Given a binary tree and an integer S, print all the pair of nodes whose sum equals S. 2 | 3 | Sample Input 1: 4 | 5 10 6 2 3 -1 -1 -1 -1 -1 9 -1 -1 5 | 15 6 | Sample Output 1: 7 | 5 10 8 | 6 9 9 | 10 | 11 | #include 12 | int k=0; 13 | 14 | void convert (BinaryTreeNode *root,int *arr) 15 | { 16 | if(root==NULL) 17 | return; 18 | arr[k++]=root->data; 19 | 20 | convert(root->left,arr); 21 | convert(root->right,arr); 22 | 23 | } 24 | 25 | void nodesSumToS(BinaryTreeNode *root, int sum) { 26 | int arr[1001]; 27 | 28 | convert(root,arr); 29 | 30 | sort(arr,arr+k); 31 | 32 | int i=0; 33 | int j=k-1; 34 | 35 | while(i sum) 44 | { 45 | j--; 46 | } 47 | else if(arr[i]+arr[j] < sum) 48 | i++; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /binary trees/diameter of tree: -------------------------------------------------------------------------------- 1 | 2 | int height(BinaryTreeNode* root) { 3 | if (root == NULL) { 4 | return 0; 5 | } 6 | return 1 + max(height(root->left), height(root->right)); 7 | } 8 | 9 | int diameter(BinaryTreeNode* root) { 10 | if (root == NULL) { 11 | return 0; 12 | } 13 | 14 | int option1 = height(root->left) + height(root->right); 15 | int option2 = diameter(root->left); 16 | int option3 = diameter(root->right); 17 | return max(option1, max(option2, option3)); 18 | } 19 | 20 | pair heightDiameter(BinaryTreeNode* root) { 21 | if (root == NULL) { 22 | pair p; 23 | p.first = 0; 24 | p.second = 0; 25 | return p; 26 | } 27 | pair leftAns = heightDiameter(root->left); 28 | pair rightAns = heightDiameter(root->right); 29 | int ld = leftAns.second; 30 | int lh = leftAns.first; 31 | int rd = rightAns.second; 32 | int rh = rightAns.first; 33 | 34 | int height = 1 + max(lh, rh); 35 | int diameter = max(lh + rh, max(ld, rd)); 36 | pair p; 37 | p.first = height; 38 | p.second = diameter; 39 | return p; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /stack and queues/stack using LL: -------------------------------------------------------------------------------- 1 | template 2 | class Stack { 3 | Node *head; 4 | int size; // number of elements prsent in stack 5 | 6 | public : 7 | 8 | Stack() { 9 | size=0; 10 | head=NULL; 11 | } 12 | 13 | int getSize() { 14 | return size; 15 | } 16 | 17 | bool isEmpty() { 18 | return size==0; 19 | } 20 | 21 | void push(T element) { 22 | Node *p=new Node(element); 23 | p->next=head; 24 | head=p; 25 | size+=1; 26 | } 27 | 28 | T pop() { 29 | // Return 0 if stack is empty. Don't display any other message 30 | if(!head) 31 | {return 0;} 32 | 33 | T x=head->data; 34 | Node * p =head; 35 | head=head->next; 36 | delete p; 37 | size--; 38 | return x; 39 | } 40 | 41 | T top() { 42 | // Return 0 if stack is empty. Don't display any other message 43 | if(!head) return 0; 44 | 45 | return head->data; 46 | } 47 | 48 | 49 | 50 | }; 51 | -------------------------------------------------------------------------------- /Test/Longest Leaf to root Path: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the longest path from leaf to root. Longest means, a path which contain maximum number of nodes from leaf to root. 2 | 3 | 4 | #include 5 | int height(BinaryTreeNode* root) 6 | { 7 | if(root==NULL) 8 | return 0; 9 | 10 | return 1+ max(height(root->left),height(root->right)); 11 | } 12 | 13 | vector* longestPath(BinaryTreeNode* root) { 14 | // Write your code here 15 | if(root->left==NULL && root->right==NULL) 16 | { 17 | vector *ans = new vector(); 18 | ans->push_back(root->data); 19 | return ans; 20 | 21 | } 22 | int left=0; 23 | int right=0; 24 | if(root->left) 25 | left=height(root->left); 26 | if(root->right) 27 | right=height(root->right); 28 | 29 | if(left>right) 30 | { 31 | vector* l =longestPath(root->left); 32 | l->push_back(root->data); 33 | return l; 34 | } 35 | else { 36 | vector* r =longestPath(root->right); 37 | r->push_back(root->data); 38 | return r; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Test/Longest Leaf to root path: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the longest path from leaf to root. Longest means, a path which contain maximum number of nodes from leaf to root. 2 | 3 | 4 | #include 5 | int height(BinaryTreeNode* root) 6 | { 7 | if(root==NULL) 8 | return 0; 9 | 10 | return 1+ max(height(root->left),height(root->right)); 11 | } 12 | 13 | vector* longestPath(BinaryTreeNode* root) { 14 | // Write your code here 15 | if(root->left==NULL && root->right==NULL) 16 | { 17 | vector *ans = new vector(); 18 | ans->push_back(root->data); 19 | return ans; 20 | 21 | } 22 | int left=0; 23 | int right=0; 24 | if(root->left) 25 | left=height(root->left); 26 | if(root->right) 27 | right=height(root->right); 28 | 29 | if(left>right) 30 | { 31 | vector* l =longestPath(root->left); 32 | l->push_back(root->data); 33 | return l; 34 | } 35 | else { 36 | vector* r =longestPath(root->right); 37 | r->push_back(root->data); 38 | return r; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /recursion 2/check ab: -------------------------------------------------------------------------------- 1 | Suppose you have a string made up of only 'a' and 'b'. Write a recursive function that checks if the string was generated using the following rules: 2 | a. The string begins with an 'a' 3 | b. Each 'a' is followed by nothing or an 'a' or "bb" 4 | c. Each "bb" is followed by nothing or an 'a' 5 | If all the rules are followed by the given string, return true otherwise return false. 6 | Sample Input: 7 | abb 8 | Sample Output: 9 | true 10 | 11 | bool solve(char input[]) { 12 | if(input[0]=='\0') 13 | return true; // Write your code here 14 | bool so; 15 | if(input[0]=='a'&&(input[1]=='\0'||input[1]=='a')) 16 | so=solve(input+1); 17 | else if(input[0]=='a'&&(input[1]=='b'&&input[2]=='b')) 18 | so=solve(input+1); 19 | else if(input[0]=='b'&&input[1]=='b'&&(input[2]=='\0'||input[2]=='a')) 20 | so= solve(input+2); 21 | else 22 | return false; 23 | return so; 24 | } 25 | 26 | 27 | bool checkAB(char input[]) { 28 | if(input[0]=='\0') 29 | return true; 30 | else if (input[0] != 'a') 31 | return false; 32 | return solve(input); 33 | } 34 | -------------------------------------------------------------------------------- /time and space complexity analysis/Print Array intersection: -------------------------------------------------------------------------------- 1 | Given two random integer arrays, print their intersection. That is, print all the elements that are present in both the given arrays. 2 | Input arrays can contain duplicate elements. 3 | 4 | Input format : 5 | Line 1 : Integer N, Array 1 Size 6 | Line 2 : Array 1 elements (separated by space) 7 | Line 3 : Integer M, Array 2 Size 8 | Line 4 : Array 2 elements (separated by space) 9 | 10 | Sample Input 1 : 11 | 6 12 | 2 6 8 5 4 3 13 | 4 14 | 2 3 4 7 15 | Sample Output 1 : 16 | 2 17 | 4 18 | 3 19 | 20 | 21 | void intersection(int input1[], int input2[], int size1, int size2) { 22 | 23 | sort(input1 ,input1+size1); 24 | sort(input2 ,input2+size2); 25 | int i=0,j=0; 26 | while(iinput2[j]) 31 | j++; 32 | else if(input1[i]==input2[j]) 33 | { 34 | cout< 6 | #include 7 | 8 | vector kSmallest(int *input, int n, int k) { 9 | // Write your code here 10 | priority_queue pq; 11 | 12 | // push first k eements in the priority queue 13 | for(int i=0 ;i ans; 29 | 30 | while (!pq.empty()) 31 | { 32 | ans.push_back(pq.top()); 33 | pq.pop(); 34 | } 35 | 36 | return ans; 37 | 38 | } 39 | -------------------------------------------------------------------------------- /recursion 2/Return Permutations - String: -------------------------------------------------------------------------------- 1 | Given a string S, find and return all the possible permutations of the input string.\ 2 | Sample Input : 3 | abc 4 | Sample Output : 5 | abc 6 | acb 7 | bac 8 | bca 9 | cab 10 | cba 11 | 12 | #include 13 | using namespace std; 14 | 15 | 16 | int returnPermutations(string input, string output[]){ 17 | if(input.size()==1) 18 | { 19 | output[0]=input[0]; 20 | return 1; 21 | 22 | } 23 | int index=0; 24 | for(int i=0 ;i< input.size();i++) 25 | { 26 | string smalloutput[1000]; 27 | int ans= returnPermutations(input.substr(0,i)+input.substr(i+1,input.size()-i-1),smalloutput); 28 | for(int j=0;j 37 | 38 | using namespace std; 39 | 40 | int main(){ 41 | string input; 42 | cin >> input; 43 | string output[10000]; 44 | int count = returnPermutations(input, output); 45 | for(int i = 0; i < count && i < 10000; i++){ 46 | cout << output[i] << endl; 47 | } 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /stack and queues/queue using LL: -------------------------------------------------------------------------------- 1 | 2 | template 3 | class Queue { 4 | 5 | Node *head,*last; 6 | int size; 7 | 8 | 9 | public : 10 | 11 | 12 | Queue() { 13 | last=head=NULL; 14 | size=0; 15 | 16 | } 17 | 18 | void enqueue(T data) { 19 | Node *newnode= new Node(data); 20 | if(head==NULL) 21 | { 22 | head=last=newnode; 23 | size++; 24 | } 25 | else 26 | { 27 | last->next=newnode; 28 | last=newnode; 29 | size++; 30 | } 31 | } 32 | 33 | int getSize() { 34 | return size; 35 | } 36 | 37 | bool isEmpty() { 38 | return size==0; 39 | } 40 | 41 | T dequeue() { 42 | // Return 0 if queue is empty 43 | if(size==0) 44 | return 0; 45 | T ans=head->data; 46 | Node *p=head; 47 | head=head->next; 48 | delete p; 49 | size--; 50 | return ans; 51 | } 52 | 53 | T front() { 54 | // Return 0 if queue is empty 55 | return head->data; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /trees/node with maximum child sum: -------------------------------------------------------------------------------- 1 | Given a tree, find and return the node for which sum of data of all children and the node itself is maximum. 2 | In the sum, data of node itself and data of immediate children is to be taken. 3 | 4 | 5 | TreeNode* maxSumNode(TreeNode *root){ 6 | 7 | TreeNode* ans =root; 8 | 9 | int sum=root->data; 10 | for(int i=0;ichildren.size();i++) /// sum for root node 11 | { 12 | sum+=root->children[i]->data; 13 | } 14 | 15 | 16 | for(int i=0;ichildren.size();i++) 17 | { 18 | TreeNode*childmax=maxSumNode(root->children[i]); //get the max node using recursion 19 | 20 | int smallsum=childmax->data; 21 | 22 | for(int i=0;ichildren.size();i++) // calculating sum for max node 23 | { 24 | smallsum+=childmax->children[i]->data; 25 | } 26 | 27 | if(sum<=smallsum) //comparision update if necessary 28 | { 29 | ans=childmax; 30 | sum=smallsum; 31 | } 32 | } 33 | return ans; 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /stack and queues/check radundant brackets: -------------------------------------------------------------------------------- 1 | Given a string mathematical expression, return true if redundant brackets are present in the expression. 2 | Brackets are redundant if there is nothing inside the bracket or more than one pair of brackets are present. 3 | 4 | Sample Input 1: 5 | ((a + b)) 6 | Sample Output 1: 7 | true 8 | Sample Input 2: 9 | (a+b) 10 | Sample Output 2: 11 | false 12 | 13 | // in current code test cases like }{}{}{}{}{ fails 14 | // see soln for other aproach 15 | 16 | bool checkRedundantBrackets(char *input) { 17 | // Write your code here 18 | stack s; 19 | int count; 20 | int i=0; 21 | int len =0; 22 | while(input[len]!='\0'){ 23 | len++; 24 | } 25 | while(inext==NULL) 15 | { 16 | return head; 17 | } 18 | 19 | node*temp=head; 20 | int count1=0; 21 | int count2=0; 22 | while(temp->next !=NULL && count1next; 25 | 26 | } 27 | node*t1=temp; 28 | // t1=temp; 29 | temp=temp->next; 30 | if(temp==NULL) 31 | return head; 32 | 33 | while(temp->next!=NULL && count2next; 36 | 37 | } 38 | 39 | node*t2; 40 | t2=temp->next; 41 | 42 | 43 | node*m=skipMdeleteN(t2,M,N); 44 | t1->next=m; 45 | return head; 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /z-revision/Largest Piece.cpp: -------------------------------------------------------------------------------- 1 | int dirn [4][2] = {{ -1, 0}, {1, 0}, {0, -1}, {0, 1} }; 2 | 3 | bool valid(int x, int y, int n) 4 | { 5 | return ( x>=0 && y>=0 && x> &cake, vector> &visited , int i,int j , int n) 8 | { 9 | visited [i][j]=true; 10 | int cut=0; 11 | for(int k=0;k<4;k++) 12 | { 13 | int x = i + dirn[k][0]; 14 | int y = j + dirn[k][1]; 15 | if(valid(x,y,n) && !visited[x][y] && cake[x][y]==1) 16 | { 17 | cut +=dfs(cake , visited , x,y,n); 18 | } 19 | } 20 | return cut+1; 21 | 22 | } 23 | int getBiggestPieceSize(vector> &cake, int n) { 24 | // Write your code here 25 | vector>visited(n, vector (n, false)); 26 | int ans=0; 27 | for(int i=0;ians) 36 | ans=small; 37 | } 38 | } 39 | } 40 | return ans; 41 | } 42 | -------------------------------------------------------------------------------- /time and space complexity analysis/Pair sum in array: -------------------------------------------------------------------------------- 1 | Given a random integer array A and a number x. Find and print the pair of elements in the array which sum to x. 2 | Array A can contain duplicate elements. 3 | While printing a pair, print the smaller element first. 4 | That is, if a valid pair is (6, 5) print "5 6". There is no constraint that out of 5 pairs which have to be printed in 1st line. 5 | You can print pairs in any order, just be careful about the order of elements in a pair. 6 | 7 | 8 | #include 9 | #include 10 | void pairSum(int input[], int size, int x) { 11 | 12 | 13 | sort(input,input+size); 14 | float y=x/2; 15 | for(int i=size-1; input[i]>=ceil(y);i--) 16 | { 17 | for(int j=i-1;j>=0;j--) 18 | { 19 | if(input[i]+input[j]==x) 20 | cout< 26 | using namespace std; 27 | 28 | 29 | int main() { 30 | 31 | int size; 32 | int x; 33 | 34 | cin>>size; 35 | int *input=new int[1+size]; 36 | 37 | for(int i=0;i>input[i]; 39 | cin>>x; 40 | pairSum(input,size,x); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /DP-2/all possible ways: -------------------------------------------------------------------------------- 1 | Given two integers a and b. You need to find and return the count of possible ways in which we can represent the number a as the sum of unique integers raise to the power b. 2 | For eg. if a = 10 and b = 2, only way to represent 10 as - 3 | 10 = 1^2 + 3^2 4 | Hence, answer is 1. 5 | 6 | int helper(int x,int n,int curNo,int *dp){ 7 | if(x<0){ 8 | return 0; 9 | } 10 | if(x==0){ 11 | return 1; 12 | } 13 | 14 | int ans=0; 15 | 16 | for(int i=curNo;pow(i,n)<=x;i++){ 17 | ans+=helper(x-pow(i,n),n,i+1,dp); 18 | } 19 | dp[x]=ans; 20 | return ans; 21 | } 22 | int allWays(int x,int n){ 23 | int dp[100000]; 24 | for(int i=0;i<100000;i++){ 25 | dp[i]=-1; 26 | } 27 | return helper(x,n,1,dp); 28 | } 29 | 30 | 31 | 32 | int check(int x,int n,int curr_num,int curr_sum){ 33 | int res=0; 34 | int p = pow(curr_num,n); 35 | while(p+curr_sum data = data; 10 | this -> next = NULL; 11 | } 12 | }; 13 | 14 | 15 | 16 | Node* NextLargeNumber(Node *head) { 17 | 18 | if(head->next==NULL) 19 | { 20 | if(head->data==9) 21 | { head->data=0; 22 | Node *x=new Node (1); 23 | 24 | x->next=head; 25 | head=x; 26 | } 27 | else 28 | head->data++; 29 | 30 | return head; 31 | } 32 | Node *pn=NextLargeNumber(head->next); 33 | 34 | if(head->next->data==0 && pn->data==1) 35 | { 36 | if(head->data==9) 37 | { head->data=0; 38 | Node *x=new Node (1); 39 | 40 | x->next=head; 41 | head=x; 42 | } 43 | else 44 | head->data++; 45 | 46 | delete pn; 47 | return head; 48 | } 49 | 50 | else 51 | { 52 | return head; 53 | } 54 | } 55 | 56 | -------------------------------------------------------------------------------- /DP-2/Matrix Chain Multiplication (MCM): -------------------------------------------------------------------------------- 1 | Given a chain of matrices A1, A2, A3,.....An, you have to figure out the most efficient way to multiply these matrices 2 | i.e. determine where to place parentheses to minimise the number of multiplications. 3 | You will be given an array p[] of size n + 1. Dimension of matrix Ai is p[i - 1]*p[i]. You need to find minimum number of multiplications needed to multiply the chain. 4 | 5 | 6 | #include 7 | using namespace std; 8 | 9 | int f(vector > &dp,int *p,int s,int e){ 10 | if(e-s==1) 11 | return 0; 12 | 13 | if(dp[s][e]) 14 | return dp[s][e]; 15 | 16 | int ans=INT_MAX; 17 | for(int k=s+1;k > dp(n+1,vector(n+1,0)); 34 | int ans=f(dp,p,0,n); 35 | return ans; 36 | } 37 | -------------------------------------------------------------------------------- /stack and queues/minimum bracket reversal: -------------------------------------------------------------------------------- 1 | Given a string expression which consists only ‘}’ and ‘{‘. The expression may not be balanced. 2 | You need to find the minimum number of bracket reversals which are required to make the expression balanced. 3 | Return -1 if the given expression can't be balanced. 4 | Input Format : 5 | String S 6 | Output Format : 7 | Required count 8 | Sample Input 1 : 9 | {{{ 10 | Sample Output 1 : 11 | -1 12 | Sample Input 2 : 13 | {{{{}} 14 | Sample Output 2 : 15 | 1 16 | 17 | #include 18 | int countBracketReversals(char input[]){ 19 | // Write your code here 20 | stack s; 21 | 22 | int totalreversal=0; 23 | for(int i=0;input[i]!='\0';i++) 24 | { if(s.empty()) 25 | s.push(input[i]); 26 | 27 | else 28 | { 29 | if(input[i]=='}' && s.top()=='{' ) //{} 30 | {s.pop();} 31 | else if(input[i]=='{' && s.top()=='}') //}{ 32 | { 33 | s.pop(); 34 | totalreversal+=2; 35 | } 36 | else //{{ //}} 37 | s.push(input[i]); 38 | } 39 | 40 | } 41 | 42 | if(s.size()%2==0) 43 | return s.size()/2+totalreversal; 44 | else return -1; 45 | 46 | } 47 | -------------------------------------------------------------------------------- /BST/check if binary tree is BST: -------------------------------------------------------------------------------- 1 | Given a binary tree with N number of nodes, check if that input tree is BST (Binary Search Tree) or not. 2 | If yes, return true, return false otherwise. 3 | Duplicate elements should be in right subtree. 4 | 5 | 6 | #include 7 | class Pair{ 8 | 9 | public: 10 | int minimum; 11 | int maximum; 12 | bool bst; 13 | 14 | }; 15 | 16 | Pair BST(BinaryTreeNode *root) 17 | { 18 | if(root==NULL) 19 | { 20 | Pair obj; 21 | obj.minimum =INT_MAX; 22 | obj.maximum = INT_MIN; 23 | obj.bst = true; 24 | return obj; 25 | } 26 | 27 | Pair left= BST(root->left); 28 | Pair right =BST(root->right); 29 | 30 | int minimum=min(root->data,min(left.minimum,right.minimum)); 31 | int maximum=max(root->data,max(left.maximum,right.maximum)); 32 | bool isBSTfinal=(root->data >left.maximum) && (root->data < right.minimum) && left.bst && right.bst; 33 | 34 | Pair obj; 35 | obj.minimum=minimum; 36 | obj.maximum=maximum; 37 | obj.bst=isBSTfinal; 38 | return obj; 39 | 40 | 41 | 42 | } 43 | 44 | bool isBST(BinaryTreeNode *root){ 45 | 46 | return BST(root).bst; 47 | 48 | 49 | } 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /LL 2/merge two sorted LL: -------------------------------------------------------------------------------- 1 | Given two linked lists sorted in increasing order. Merge them in such a way that the result list is also sorted (in increasing order). 2 | Try solving with O(1) auxiliary space (in-place). You just need to return the head of new linked list, don't print the elements. 3 | 4 | Node* mergeTwoLLs(Node *head1, Node *head2) { 5 | 6 | Node *p=NULL,*q=NULL; 7 | if(head1->datadata) 8 | { 9 | p=head1; 10 | q=head1; 11 | head1=head1->next; 12 | 13 | 14 | } 15 | else if(head1->data>=head2->data) 16 | { 17 | p=head2; 18 | q=head2; 19 | head2=head2->next; 20 | 21 | 22 | } 23 | while(head1&&head2) 24 | { 25 | if(head1->datadata) 26 | { 27 | q->next=head1; 28 | q=head1; 29 | head1=head1->next; 30 | q->next=NULL; 31 | } 32 | else if(head1->data>=head2->data) 33 | { 34 | q->next=head2; 35 | q=head2; 36 | head2=head2->next; 37 | q->next=NULL; 38 | } 39 | } 40 | if(head1) 41 | q->next=head1; 42 | if(head2) 43 | q->next=head2; 44 | 45 | 46 | return p; 47 | } 48 | -------------------------------------------------------------------------------- /recursion 2/Print all Codes - String: -------------------------------------------------------------------------------- 1 | 2 | Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. You are given a numeric string S. 3 | Write a program to print the list of all possible codes that can be generated from the given string 4 | 1123 5 | Sample Output: 6 | aabc 7 | kbc 8 | alc 9 | aaw 10 | kw 11 | 12 | #include 13 | using namespace std; 14 | 15 | void help(string input,string output) 16 | { 17 | if(input.size()==0) 18 | { 19 | cout<=10 && d<=26) 28 | { char c2= d+96; 29 | help(input.substr(2),output +c2); 30 | } 31 | } 32 | 33 | 34 | void printAllPossibleCodes(string input) { 35 | /* 36 | Given the input as a string, print all its possible combinations. You do not need to return anything. 37 | */ 38 | string output=""; 39 | 40 | help(input,output); 41 | } 42 | #include 43 | #include "solution.h" 44 | using namespace std; 45 | 46 | int main(){ 47 | string input; 48 | cin >> input; 49 | 50 | printAllPossibleCodes(input); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /binary trees/zig zag tree: -------------------------------------------------------------------------------- 1 | Given a binary tree, print the zig zag order i.e print level 1 from left to right, level 2 from right to left and so on. 2 | This means odd levels should get printed from left to right and even level right to left. 3 | 4 | 5 | void zigZagOrder(BinaryTreeNode *root) { 6 | // Write your code here 7 | if(!root) 8 | return; 9 | 10 | stack *> s1; 11 | stack *> s2; 12 | 13 | s1.push(root); 14 | 15 | while(!s1.empty() && !s1.empty()) 16 | { 17 | while(!s1.empty()) 18 | { BinaryTreeNode * top=s1.top(); 19 | s1.pop(); 20 | cout<data<<" "; 21 | 22 | if(top->left) 23 | s2.push(top->left); 24 | if(top->right) 25 | s2.push(top->right); 26 | } 27 | 28 | cout< * top=s2.top(); 33 | s2.pop(); 34 | cout<data<<" "; 35 | 36 | if(top->right) 37 | s1.push(top->right); 38 | if(top->left) 39 | s1.push(top->left); 40 | 41 | } 42 | cout< 18 | using namespace std; 19 | string key[]={" ", " ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 20 | 21 | int keypad(int num, string output[]){ 22 | /* Insert all the possible combinations of the integer number into the output string array. You do not need to 23 | print anything, just return the number of strings inserted into the array. 24 | */ 25 | int x=num%10; 26 | //base case 27 | if(x==0 ||x==1) 28 | { output[0]=""; 29 | return 1; 30 | } 31 | 32 | int SizeOfSmall=keypad(num/10,output); 33 | for(int i=1;i m; 8 | for(int i=0 ; i< n ;i++) 9 | { 10 | m[input[i]]++; 11 | } 12 | 13 | if(k!=0){ 14 | for(int i=0 ; i0) 18 | { 19 | // m[input[i]]--; 20 | int j=0; 21 | while(j0) 39 | { 40 | for(int j=0;jnext; 10 | } 11 | return count; 12 | } 13 | #include 14 | class Node{ 15 | public: 16 | int data; 17 | Node *next; 18 | Node(int data){ 19 | this -> data = data; 20 | this -> next = NULL; 21 | } 22 | }; 23 | 24 | using namespace std; 25 | 26 | 27 | Node* takeinput() { 28 | int data; 29 | cin >> data; 30 | Node* head = NULL, *tail = NULL; 31 | while(data != -1){ 32 | Node *newNode = new Node(data); 33 | if(head == NULL) { 34 | head = newNode; 35 | tail = newNode; 36 | } 37 | else{ 38 | tail -> next = newNode; 39 | tail = newNode; 40 | } 41 | cin >> data; 42 | } 43 | return head; 44 | } 45 | 46 | void print(Node *head) { 47 | Node *temp = head; 48 | while(temp != NULL) { 49 | cout << temp -> data << " "; 50 | temp = temp -> next; 51 | } 52 | cout<> pos; 59 | cout << length(head); 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /LL-1/Eliminate duplicates from LL: -------------------------------------------------------------------------------- 1 | node* eliminate_duplicate(node* head) 2 | { 3 | //write your code here 4 | node *p=head->next,*q=head; 5 | while(p) 6 | { 7 | if(p->data==q->data) 8 | { 9 | q->next=p->next; 10 | node *t=p; 11 | p=p->next; 12 | delete t; 13 | } 14 | else{ 15 | q=q->next; 16 | p=p->next; 17 | } 18 | } 19 | return head; 20 | } 21 | --------------------------------------------------------------------------- 22 | 23 | // recursively 24 | 25 | SinglyLinkedListNode* removeDuplicates(SinglyLinkedListNode* head) { 26 | if(head==NULL || head->next == NULL) 27 | return head; 28 | if(head->data == head->next->data) 29 | { 30 | SinglyLinkedListNode* temp=head; 31 | head=head->next; 32 | temp->next=NULL; 33 | delete temp; 34 | return removeDuplicates(head); 35 | } 36 | else{ 37 | head->next =removeDuplicates(head->next); 38 | return head; 39 | } 40 | } 41 | -------------------------------------------------------------- 42 | 43 | if ((head == null) || (head.next == null)) 44 | return head; 45 | 46 | Node tmp = RemoveDuplicates(head.next); 47 | 48 | if (head.next != null) 49 | if (head.data == head.next.data) 50 | head.next = head.next.next; 51 | 52 | return head; 53 | -------------------------------------------------------------------------------- /Graph 1/largest piece: -------------------------------------------------------------------------------- 1 | Its Gary's birthday today and he has ordered his favourite square cake consisting of '0's and '1's . 2 | But Gary wants the biggest piece of '1's and no '0's . A piece of cake is defined as a part which consist of only '1's, and all '1's share an edge with eachother on the cake. 3 | Given the size of cake N and the cake , can you find the size of the biggest piece of '1's for Gary ? 4 | 5 | void dfs(char cake[NMAX][NMAX],int n,int &k,int i,int j){ 6 | 7 | k++; 8 | 9 | cake[i][j]='0'; 10 | 11 | 12 | 13 | if(i+1=0 && cake[i-1][j]=='1') 18 | 19 | dfs(cake,n,k,i-1,j); 20 | 21 | if(j+1=0 && cake[i][j-1]=='1') 26 | 27 | dfs(cake,n,k,i,j-1); 28 | 29 | 30 | 31 | } 32 | 33 | int solve(int n,char cake[NMAX][NMAX]) 34 | 35 | { 36 | 37 | // Write your code here . 38 | int ans=0; 39 | 40 | for(int i=0;i 6 | #include 7 | class Pair{ 8 | 9 | public: 10 | int minimum; 11 | int maximum; 12 | bool bst; 13 | int height; 14 | }; 15 | 16 | Pair BST(BinaryTreeNode *root) 17 | { 18 | if(root==NULL) 19 | { 20 | Pair obj; 21 | obj.minimum =INT_MAX; 22 | obj.maximum = INT_MIN; 23 | obj.bst = true; 24 | obj.height=0; 25 | return obj; 26 | } 27 | 28 | Pair left= BST(root->left); 29 | Pair right =BST(root->right); 30 | 31 | int minimum=min(root->data,min(left.minimum,right.minimum)); 32 | int maximum=max(root->data,max(left.maximum,right.maximum)); 33 | bool isBSTfinal=(root->data >left.maximum) && (root->data < right.minimum) && left.bst && right.bst; 34 | 35 | Pair obj; 36 | obj.minimum=minimum; 37 | obj.maximum=maximum; 38 | obj.bst=isBSTfinal; 39 | if(isBSTfinal) 40 | { 41 | obj.height= 1+max(left.height,right.height); 42 | } 43 | else obj.height= max(left.height,right.height); 44 | return obj; 45 | 46 | } 47 | 48 | int largestBSTSubtree(BinaryTreeNode *root) { 49 | // Write your code here 50 | return BST(root).height; 51 | } 52 | -------------------------------------------------------------------------------- /time and space complexity analysis/Triplet sum: -------------------------------------------------------------------------------- 1 | Given a random integer array and a number x. Find and print the triplets of elements in the array which sum to x. 2 | While printing a triplet, print the smallest element first. 3 | That is, if a valid triplet is (6, 5, 10) print "5 6 10". There is no constraint that out of 5 triplets which have to be printed on 1st line. 4 | You can print triplets in any order, just be careful about the order of elements in a triple 5 | 6 | #include 7 | #include 8 | 9 | void FindTriplet(int arr[], int size, int x) { 10 | 11 | sort(arr,arr+size); 12 | int i=0,j=1,k=2; 13 | while(i 33 | using namespace std; 34 | #include "solution.h" 35 | 36 | int main() { 37 | 38 | int size; 39 | 40 | int x; 41 | cin>>size; 42 | 43 | int *input=new int[1+size]; 44 | 45 | for(int i=0;i>input[i]; 47 | cin>>x; 48 | 49 | FindTriplet(input,size,x); 50 | 51 | return 0; 52 | } 53 | 54 | -------------------------------------------------------------------------------- /DP-2/shortest subsequence (pending): -------------------------------------------------------------------------------- 1 | Gary has two string S and V. Now Gary wants to know the length shortest subsequence in S such that it is not a subsequence in V. 2 | 3 | 4 | Note: input data will be such so there will always be a solution. 5 | Input Format : 6 | Line 1 : String S of length N (1 <= N <= 1000) 7 | Line 2 : String V of length M (1 <= M <= 1000) 8 | Output Format : 9 | Length of shortest subsequence in S such that it is not a subsequence in V 10 | 11 | 12 | #include 13 | using namespace std; 14 | 15 | int ss(vector < vector > &dp,string s,string v){ 16 | 17 | if(s.size()==0) 18 | return 1550; 19 | 20 | if(v.size()<=0) 21 | return 1; 22 | 23 | if(dp[s.size()][v.size()]) 24 | return dp[s.size()][v.size()]; 25 | int i; 26 | for(i=0;i > dp(S.size()+1,vector(V.size()+1,0)); 48 | int ans=ss(dp,S,V); 49 | 50 | return ans; 51 | 52 | } 53 | -------------------------------------------------------------------------------- /DP-2/coin tower: -------------------------------------------------------------------------------- 1 | Whis and Beerus are playing a new game today . They form a tower of N coins and make a move in alternate turns . Beerus being the God plays first . In one move player can remove 1 or X or Y coins from the tower . The person to make the last move wins the Game . Can you find out who wins the game ? 2 | Input Format : 3 | Contains three value N,X,Y as mentioned in the problem statement 4 | Output Format : 5 | A string containing the name of the winner like “Whis” or “Beerus” (without quotes) 6 | 7 | string solve(int n, int x, int y) 8 | { 9 | // To store results 10 | int dp[n + 1]; 11 | 12 | // Initial values 13 | dp[0] = false; 14 | dp[1] = true; 15 | 16 | // Computing other values. 17 | for (int i = 2; i <= n; i++) { 18 | 19 | // If A losses any of i-1 or i-x 20 | // or i-y game then he will 21 | // definitely win game i 22 | if (i - 1 >= 0 and !dp[i - 1]) 23 | dp[i] = true; 24 | else if (i - x >= 0 and !dp[i - x]) 25 | dp[i] = true; 26 | else if (i - y >= 0 and !dp[i - y]) 27 | dp[i] = true; 28 | 29 | // Else A loses game. 30 | else 31 | dp[i] = false; 32 | } 33 | 34 | // If dp[n] is true then A will 35 | // game otherwise he losses 36 | string s="Whis"; 37 | if (dp[n]) 38 | { 39 | s="Beerus"; 40 | return s; 41 | } 42 | else return s; 43 | } 44 | -------------------------------------------------------------------------------- /Graph 1/3 cycle: -------------------------------------------------------------------------------- 1 | Given a graph with N vertices (numbered from 1 to N) and Two Lists (U,V) of size M where (U[i],V[i]) and (V[i],U[i]) are connected by an edge , 2 | then count the distinct 3-cycles in the graph. A 3-cycle PQR is a cycle in which (P,Q), (Q,R) and (R,P) are connected an edge. 3 | 4 | 5 | 6 | 7 | #include 8 | 9 | using namespace std; 10 | 11 | int solve(int n,int m,vectoru,vectorv) 12 | 13 | { 14 | 15 | // Write your code here . 16 | 17 | unordered_map >adj; 18 | 19 | 20 | 21 | for(int i=0;i*head; 6 | Node *tail; 7 | }; 8 | 9 | Pair BST(BinaryTreeNode* root) 10 | { 11 | if(root==NULL) 12 | { 13 | Pair ans ; 14 | ans.head=NULL; 15 | ans.tail=NULL; 16 | return ans; 17 | 18 | } 19 | 20 | Node *node= new Node (root->data); 21 | 22 | Pair leftans=BST(root->left); 23 | Pair rightans=BST(root->right); 24 | 25 | 26 | Pair ans; 27 | 28 | if(leftans.head==NULL && rightans.head==NULL) 29 | { 30 | 31 | ans.head=node; 32 | ans.tail=node; 33 | 34 | } 35 | 36 | else if(!leftans.head && rightans.head ) 37 | { ans.head=node; 38 | node->next=rightans.head; 39 | 40 | ans.tail=rightans.tail; 41 | } 42 | else if(leftans.head && rightans.head==NULL) 43 | { ans.head=leftans.head; 44 | leftans.tail->next=node; 45 | ans.tail=node; 46 | 47 | } 48 | else 49 | { 50 | ans.head=leftans.head; 51 | leftans.tail->next=node; 52 | node->next=rightans.head; 53 | ans.tail=rightans.tail; 54 | } 55 | 56 | 57 | 58 | return ans; 59 | 60 | } 61 | Node* constructBST(BinaryTreeNode* root) { 62 | return BST(root).head; 63 | 64 | } 65 | -------------------------------------------------------------------------------- /DP-2/Maximum Square Matrix With All Zeros: -------------------------------------------------------------------------------- 1 | Given a n*m matrix which contains only 0s and 1s, find out the size of maximum square sub-matrix with all 0s. You need to return the size of square with all 0s. 2 | Input format : 3 | Line 1 : n and m (space separated positive integers) 4 | Next n lines : m elements of each row (separated by space). 5 | Output Format: 6 | Line 1 : Size of maximum square sub-matrix 7 | 8 | 9 | #include 10 | using namespace std; 11 | int findMaxSquareWithAllZeros(int** arr, int row, int col){ 12 | 13 | /* Don't write main(). 14 | * Don't read input, it is passed as function argument. 15 | * Return output and don't print it. 16 | * Taking input and printing output is handled automatically. 17 | */ 18 | int dp[row][col]={0}; 19 | 20 | //Initialization 21 | int ans=0; 22 | for(int i=0;i 21 | int countStepsTo1(int n){ 22 | 23 | int a[n+1]; 24 | 25 | a[1]=0; a[2]=a[3]=1; 26 | int b,c; 27 | for(int i=4 ;i 46 | int countstepsto1(int n ,int *arr) 47 | { 48 | if(n==1) 49 | { 50 | arr[n]=0; 51 | return arr[n]; 52 | } 53 | int a=INT_MAX,b=a,c=b; 54 | 55 | if(arr[n]!=-1) 56 | return 1+arr[n]; 57 | a = countstepsto1(n-1,arr); 58 | 59 | if(n%2==0) 60 | b=countstepsto1(n/2,arr); 61 | if(n%3==0) 62 | c=countstepsto1(n/3,arr); 63 | 64 | 65 | arr[n] = min(a,min(b,c)); 66 | 67 | return 1+arr[n]; 68 | } 69 | 70 | int countStepsTo1(int n){ 71 | 72 | if(n==1) return 0; 73 | 74 | int *ans= new int[n+1]; 75 | for(int i=0 ;iu,vectorv) 20 | { 21 | 22 | int** graph = new int * [n+1]; 23 | 24 | for(int i=0 ;i *> createLLForEachLevel(BinaryTreeNode *root) { 14 | 15 | vector*> v; 16 | 17 | if(root==NULL) 18 | { 19 | v.push_back(NULL) ; 20 | 21 | return v; 22 | } 23 | 24 | 25 | queue *> pn; 26 | 27 | pn.push(root); 28 | pn.push(NULL); 29 | 30 | node *head=NULL; 31 | node *tail =head; 32 | 33 | 34 | while(pn.size()!=0) 35 | { 36 | BinaryTreeNode *front=pn.front(); 37 | pn.pop(); 38 | 39 | if(front==NULL) 40 | { tail->next=NULL; 41 | 42 | if(pn.size()==0) 43 | break; 44 | 45 | pn.push(NULL); 46 | 47 | head=NULL; 48 | tail=NULL; 49 | 50 | 51 | 52 | } 53 | 54 | else 55 | { 56 | node *n=new node (front->data); 57 | if(head==NULL) 58 | { 59 | head=tail=n; 60 | v.push_back(head); 61 | } 62 | else 63 | { 64 | tail->next=n; 65 | tail=n; 66 | } 67 | 68 | if(front->left) 69 | pn.push(front->left); 70 | if(front->right) 71 | pn.push(front->right); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /recursion 2/quick sort code: -------------------------------------------------------------------------------- 1 | 2 | void swap(int *a, int *b) 3 | { 4 | int temp = *a; 5 | *a = *b; 6 | *b = temp; 7 | } 8 | int p_front_cn(int a[], int l , int h )// equal to the left 9 | { 10 | int pivot = a[l]; 11 | int count = 0; 12 | for (int i = l + 1 ; i <= h; i++) 13 | {if (a[i] <= pivot) count++; } 14 | 15 | swap(&a[l], &a[l + count]); 16 | pivot = a[l + count]; 17 | int i = l ; int j = l + count + 1; 18 | while (i < l + count && j <= h) 19 | { 20 | if (a[i] <= pivot)i++; 21 | else if (a[j] > pivot)j++; 22 | else 23 | { 24 | swap ( &a[i] , &a[j]); i++ ; j++; 25 | } 26 | } 27 | return l + count; 28 | } 29 | int p_back_clrs(int a[], int l , int h) 30 | { 31 | int pivot = a[h]; 32 | int i = l - 1; 33 | for (int j = l ; j < h ; j++) 34 | { 35 | if (a[j] < pivot) 36 | { 37 | i++; 38 | swap(&a[j], &a[i]); 39 | } 40 | } 41 | swap(&a[h], &a[i + 1]); 42 | return i + 1; 43 | } 44 | int p_front_clrs(int a[] , int l , int h) 45 | { 46 | int pivot = a[l]; 47 | 48 | int i = h + 1; 49 | 50 | for (int j = h; j > l ; j--) 51 | { 52 | if (a[j] > pivot) 53 | { 54 | i--; 55 | swap(&a[j], &a[i]); 56 | } 57 | } 58 | swap(&a[l] , &a[i - 1]); 59 | return i - 1; 60 | 61 | } 62 | void QuickSort(int a[], int s, int e) 63 | { 64 | if (s >= e) 65 | return; 66 | //int p = p_front_cn(a, s, e); 67 | //int p = p_front_clrs(a, s, e); 68 | int p = p_back_clrs(a, s, e); 69 | 70 | QuickSort(a, s, p - 1); 71 | QuickSort(a, p + 1, e); 72 | 73 | 74 | } 75 | void quickSort(int input[], int size) { 76 | 77 | int start = 0; 78 | int end = size - 1; 79 | 80 | QuickSort(input, start, end); 81 | 82 | } 83 | -------------------------------------------------------------------------------- /binary trees/Construct Tree from Preorder and Inorder: -------------------------------------------------------------------------------- 1 | Given Preorder and Inorder traversal of a binary tree, 2 | create the binary tree associated with the traversals.You just need to construct the tree and return the root. 3 | 4 | Sample Input : 5 | 12 6 | 1 2 3 4 15 5 6 7 8 10 9 12 7 | 4 15 3 2 5 1 6 10 8 7 9 12 8 | Sample Output : 9 | 1 10 | 2 6 11 | 3 5 7 12 | 4 8 9 13 | 15 10 12 14 | 15 | 16 | // inorder ,preorder,inorderstart,inorderend,preorderstart,preorderend 17 | BinaryTreeNode* buildTreeHelper(int* in, int* pre, int inS, int inE, int preS, int preE) { 18 | if (inS > inE) { 19 | return NULL; 20 | } 21 | 22 | int rootData = pre[preS]; 23 | int rootIndex = -1; 24 | for (int i = inS; i <= inE; i++) { 25 | if (in[i] == rootData) { 26 | rootIndex = i; 27 | break; 28 | } 29 | } 30 | 31 | int lInS = inS; //left inorder start 32 | int lInE = rootIndex - 1;//left inorder end 33 | int lPreS = preS + 1;//left preorder start 34 | int lPreE = lInE - lInS + lPreS;//left preorder end 35 | int rPreS = lPreE + 1;//right preorder start 36 | int rPreE = preE;//right preorder end 37 | int rInS = rootIndex + 1;//right inorder start 38 | int rInE = inE;//right inorder end 39 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 40 | root->left = buildTreeHelper(in, pre, lInS, lInE, lPreS, lPreE); 41 | root->right = buildTreeHelper(in, pre, rInS, rInE, rPreS, rPreE); 42 | return root; 43 | } 44 | 45 | BinaryTreeNode* buildTree(int *preorder, int preLength, int *inorder, int inLength) { 46 | 47 | 48 | return buildTreeHelper(inorder,preorder,0,inLength-1,0,preLength-1); 49 | } 50 | -------------------------------------------------------------------------------- /Graph 1/has path: -------------------------------------------------------------------------------- 1 | Given an undirected graph G(V, E) and two vertices v1 and v2(as integers), check if there exists any path between them or not. Print true or false. 2 | V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 3 | E is the number of edges present in graph G. 4 | 5 | 6 | #include 7 | using namespace std; 8 | 9 | bool haspath(int**graph ,int v ,bool* visited,int s ,int e) 10 | { 11 | if(graph[s][e]==1) return true; 12 | 13 | visited[s]=true; 14 | 15 | bool res =false; 16 | 17 | for(int i=0 ;i> V >> E; 33 | 34 | int* * graph = new int * [V]; 35 | 36 | for(int i=0 ;i >x>>y; 47 | graph[x][y]=1; 48 | graph[y][x]=1; 49 | } 50 | bool * arr=new bool[V]; 51 | for(int i=0 ;i< V;i++) 52 | arr[V]= false; 53 | int s,e; 54 | 55 | cin>> s>>e; 56 | 57 | if(haspath(graph,V,arr,s,e)) 58 | cout<< "true"; 59 | else 60 | cout<<"false"; 61 | 62 | 63 | delete [] arr; 64 | for(int i = 0 ;i s; 16 | 17 | output[0]=1; 18 | s.push(0); 19 | for(int i=1;iprice[s.top()]) 29 | { 30 | s.pop(); 31 | 32 | } 33 | if(s.top()==NULL) 34 | output[i]=i+1; 35 | else 36 | output[i]=i-s.top(); 37 | 38 | s.push(i); 39 | } 40 | 41 | } 42 | for(int i=0;inext; 6 | count++; 7 | } 8 | return count; 9 | } 10 | node* bubble_sort_LinkedList_itr(node* head) 11 | { 12 | if(head==NULL || head->next==NULL) 13 | return head; 14 | 15 | // node *curr=head; 16 | //node *prev=NULL; 17 | //node *n=head->next; 18 | for(int i=0;inext; 22 | 23 | while(curr->next!=NULL) // traverse though LL 24 | { 25 | if(curr->data > curr->next->data) // if nodes are to be swapped 26 | { 27 | if(prev) //check if previous of the current node exist , u cant point on a garbage value 28 | { 29 | // swapping using those 4 steps 30 | node* t=curr->next->next; 31 | curr->next->next= curr; 32 | prev->next=curr->next; 33 | curr->next=t; 34 | prev=prev->next; 35 | } 36 | else //is it doent exist it would be head node 37 | { 38 | head= curr->next; 39 | curr->next=head->next; 40 | head->next=curr; 41 | prev=head; 42 | } 43 | 44 | } 45 | else // else you simply move to next node 46 | { 47 | prev=curr; 48 | curr=curr->next; 49 | } 50 | } 51 | } 52 | 53 | 54 | return head; 55 | } 56 | -------------------------------------------------------------------------------- /LL 2/merge sort: -------------------------------------------------------------------------------- 1 | Sort a given linked list using Merge Sort. 2 | 3 | int length(node *head) { 4 | 5 | int count=0; 6 | while(head) 7 | { 8 | count++; 9 | head=head->next; 10 | } 11 | return count; 12 | } 13 | node* mergeTwoLLs(node *head1, node *head2) { 14 | 15 | 16 | node *p=NULL,*q=NULL; 17 | if(head1->datadata) 18 | { 19 | p=head1; 20 | q=head1; 21 | head1=head1->next; 22 | 23 | 24 | } 25 | else if(head1->data>=head2->data) 26 | { 27 | p=head2; 28 | q=head2; 29 | head2=head2->next; 30 | 31 | 32 | } 33 | while(head1&&head2) 34 | { 35 | if(head1->datadata) 36 | { 37 | q->next=head1; 38 | q=head1; 39 | head1=head1->next; 40 | q->next=NULL; 41 | } 42 | else if(head1->data>=head2->data) 43 | { 44 | q->next=head2; 45 | q=head2; 46 | head2=head2->next; 47 | q->next=NULL; 48 | } 49 | } 50 | if(head1) 51 | q->next=head1; 52 | if(head2) 53 | q->next=head2; 54 | 55 | 56 | return p; 57 | } 58 | 59 | node* mergeSort(node *head) { 60 | //write your code here 61 | if(head==NULL|| head->next==NULL) 62 | {return head;} 63 | 64 | //breaking node into two half 65 | node *p=head; 66 | for(int i=1;inext; 69 | } 70 | node *head1=p->next; 71 | p->next=NULL; 72 | 73 | head=mergeSort(head); 74 | head1=mergeSort(head1); 75 | 76 | return mergeTwoLLs(head,head1); 77 | 78 | } 79 | -------------------------------------------------------------------------------- /recursion 2/return subset of an array: -------------------------------------------------------------------------------- 1 | Given an integer array (of length n), find and return all the subsets of input array. 2 | Subsets are of length varying from 0 to n, that contain elements of the array. But the order of elements should remain same as in the input array. 3 | Note : The order of subsets are not important. 4 | Input format : 5 | 6 | Line 1 : Size of array 7 | 8 | Line 2 : Array elements (separated by space) 9 | 10 | Sample Input: 11 | 3 12 | 15 20 12 13 | Sample Output: 14 | [] (this just represents an empty array, don't worry about the square brackets) 15 | 12 16 | 20 17 | 20 12 18 | 15 19 | 15 12 20 | 15 20 21 | 15 20 12 22 | 23 | /*** 24 | You need to save all the subsets in the given 2D output array. And return the number of subsets(i.e. number of rows filled in output) from the given function. 25 | 26 | In ith row of output array, 1st column contains length of the ith subset. And from 1st column actual subset follows. 27 | For eg. Input : {1, 2}, then output should contain 28 | {{0}, // Length of this subset is 0 29 | {1, 2}, // Length of this subset is 1 30 | {1, 1}, // Length of this subset is also 1 31 | {2, 1, 2}} // Length of this subset is 2 32 | 33 | Don’t print the subsets, just save them in output. 34 | ***/ 35 | 36 | int subset(int input[], int n, int output[][20]) { 37 | // Write your code here 38 | if(n<=0) { 39 | output[0][0]=0; 40 | return 1; 41 | } 42 | 43 | int smallOutput = subset(input+1,n-1,output); 44 | for(int i=0;i 7 | #include 8 | using namespace std; 9 | 10 | void BFS(int**graph ,int v , int sv,bool* visited) 11 | { 12 | 13 | queue pn; 14 | pn.push(sv); 15 | visited[sv]=true; 16 | 17 | while(!pn.empty()) 18 | { 19 | int t= pn.front(); 20 | 21 | pn.pop(); 22 | 23 | 24 | for(int i=0 ; i> V >> E; 40 | 41 | 42 | int** graph = new int * [V]; 43 | for( int i=0 ;i>x>>y ; 54 | graph[x][y]=1; 55 | graph[y][x]=1; 56 | } 57 | bool * visited = new bool[V]; 58 | for ( int i=0 ;i 0) { 9 | int parentIndex = (childIndex - 1) / 2; 10 | 11 | if(pq[childIndex] < pq[parentIndex]) { 12 | int temp = pq[childIndex]; 13 | pq[childIndex] = pq[parentIndex]; 14 | pq[parentIndex] = temp; 15 | } 16 | else { 17 | break; 18 | } 19 | childIndex = parentIndex; 20 | } 21 | } 22 | 23 | // Remove elements 24 | 25 | int size = n; 26 | 27 | while(size > 1) { 28 | int temp = pq[0]; 29 | pq[0] = pq[size - 1]; 30 | pq[size-1] = temp; 31 | 32 | size--; 33 | 34 | int parentIndex = 0; 35 | int leftChildIndex = 2 * parentIndex + 1; 36 | int rightChildIndx = 2 * parentIndex + 2; 37 | 38 | while(leftChildIndex < size) { 39 | int minIndex = parentIndex; 40 | if(pq[minIndex] > pq[leftChildIndex]) { 41 | minIndex = leftChildIndex; 42 | } 43 | if(rightChildIndx < size && pq[rightChildIndx] < pq[minIndex]) { 44 | minIndex = rightChildIndx; 45 | } 46 | if(minIndex == parentIndex) { 47 | break; 48 | } 49 | int temp = pq[minIndex]; 50 | pq[minIndex] = pq[parentIndex]; 51 | pq[parentIndex] = temp; 52 | 53 | parentIndex = minIndex; 54 | leftChildIndex = 2 * parentIndex + 1; 55 | rightChildIndx = 2 * parentIndex + 2; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /recursion 2/Return all codes - String: -------------------------------------------------------------------------------- 1 | Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. 2 | You are given a numeric string S. 3 | Write a program to return the list of all possible codes that can be generated from the given string. 4 | 5 | 1123 6 | Sample Output: 7 | aabc 8 | kbc 9 | alc 10 | aaw 11 | kw 12 | 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | 18 | void help(string input,string out,vector &str){ 19 | if(input.size()==0){ 20 | str.push_back(out); 21 | return; 22 | } 23 | char c1=(input[0]-48)+96; 24 | 25 | //Ignore the output coming from zero in a string 26 | if(input[0]=='0') 27 | return; 28 | 29 | help(input.substr(1),out+c1,str); 30 | 31 | if(input.size()>1){ 32 | int d=(input[0]-48)*10+(input[1]-48); 33 | if(d>26) 34 | return; 35 | char c2=96+d; 36 | help(input.substr(2),out+c2,str); 37 | } 38 | 39 | } 40 | 41 | 42 | int getCodes(string input, string output[10000]) { 43 | /* 44 | You are given the input text and output string array. Find all possible codes and store in the output string array. Don’t print the codes. 45 | Also, return the number of codes return to the output string. You do not need to print anything. 46 | */ 47 | vector str; 48 | string out=""; 49 | help(input,out,str); 50 | 51 | for(int i=0;i 61 | 62 | using namespace std; 63 | 64 | int main(){ 65 | string input; 66 | cin >> input; 67 | 68 | string output[10000]; 69 | int count = getCodes(input, output); 70 | for(int i = 0; i < count && i < 10000; i++) 71 | cout << output[i] << endl; 72 | return 0; 73 | } 74 | 75 | -------------------------------------------------------------------------------- /recursion 2/Return subsets sum to K: -------------------------------------------------------------------------------- 1 | Given an array A of size n and an integer K, return all subsets of A which sum to K. 2 | Line 1 : Integer n, Size of input array 3 | Line 2 : Array elements separated by space 4 | Line 3 : K 5 | Constraints : 6 | 1 <= n <= 20 7 | Sample Input : 8 | 9 9 | 5 12 3 17 1 18 15 3 17 10 | 6 11 | Sample Output : 12 | 3 3 13 | 5 1 14 | 15 | #include 16 | 17 | using namespace std; 18 | int subsetsumtok(int input[], int n,int si, int output[][50], int k) 19 | { 20 | if(si==n) 21 | { 22 | if(k==0) 23 | { 24 | output[0][0]=0; 25 | return 1; 26 | } 27 | else 28 | return 0; 29 | } 30 | int smalloutput1[1000][50]; 31 | int smalloutput2[1000][50]; 32 | 33 | int s1=subsetsumtok(input,n,si+1,smalloutput1,k); 34 | int s2=subsetsumtok(input,n,si+1,smalloutput2,k-input[si]); 35 | 36 | int row=0; 37 | for(int i=0 ;i> length; 68 | for(int i=0; i < length; i++) 69 | cin >> input[i]; 70 | 71 | cin >> k; 72 | 73 | int size = subsetSumToK(input, length, output, k); 74 | 75 | for( int i = 0; i < size; i++) { 76 | for( int j = 1; j <= output[i][0]; j++) { 77 | cout << output[i][j] << " "; 78 | } 79 | cout << endl; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /z-revision/Connecting Dots.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int dirn [8][2] = {{ -1, 0}, {1, 0}, {0, -1}, {0, 1} }; 6 | 7 | bool valid(int x , int y , int n , int m) 8 | { 9 | return ( x >= 0 && x < n && y >= 0 && y < m); 10 | } 11 | bool check(vector> &board, vector>& visited, int si, int sj, int ci , int cj, int n, int m , char color, int ring) 12 | { 13 | 14 | // cout << endl;// cout << i << " " << j << endl; 15 | visited[ci][cj] = true; 16 | for (int k = 0 ; k < 4; k++ ) 17 | { 18 | int x = ci + dirn[k][0]; 19 | int y = cj + dirn[k][1]; 20 | if (x == si && y == sj && ring > 4)return true; 21 | if ( valid(x, y, n, m) && !visited[x][y] && board[x][y] == color) 22 | { // cout << x << " " << y << endl; 23 | if (check(board , visited , si, sj, x, y, n, m, color, ++ring)) return true; 24 | } 25 | 26 | } 27 | visited[ci][cj] = false; 28 | return false; 29 | 30 | } 31 | bool hasCycle(vector> &board, int n, int m) { 32 | // Write your code here. 33 | vector> visited (n , vector(m , false)); 34 | 35 | 36 | for (int i = 0 ; i < n ; i++) 37 | { 38 | for (int j = 0 ; j < m ; j++) 39 | { 40 | if (!visited[i][j]) 41 | { 42 | char c = board[i][j]; 43 | //cout << c << endl; 44 | if (check(board, visited , i , j , i, j, n, m, c, 1)) 45 | return true; 46 | } 47 | } 48 | } 49 | return false; 50 | 51 | } 52 | 53 | 54 | int main() { 55 | #ifndef ONLINE_JUDGE 56 | freopen("input.txt", "r", stdin); 57 | freopen("output.txt", "w", stdout); 58 | #endif 59 | int n, m; 60 | cin >> n >> m; 61 | 62 | vector> board(n, vector(m)); 63 | 64 | for (int i = 0; i < n; ++i) { 65 | for (int j = 0; j < m; ++j) { 66 | cin >> board[i][j]; 67 | } 68 | } 69 | 70 | cout << (hasCycle(board, n, m) ? "true" : "false"); 71 | } 72 | -------------------------------------------------------------------------------- /Graph 2/dijkstra algorithm: -------------------------------------------------------------------------------- 1 | Given an undirected, connected and weighted graph G(V, E) with V number of vertices (which are numbered from 0 to V-1) and E number of edges. 2 | Find and print the shortest distance from the source vertex (i.e. Vertex 0) to all other vertices (including source vertex also) using Dijkstra's Algorithm. 3 | Print the ith vertex number and the distance from source in one line separated by space. Print different vertices in different lines. 4 | 5 | 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int MinVertex(int* cost,bool*visited ,int v) 12 | { 13 | int min=INT_MAX; 14 | int vertex=-1; 15 | for(int i=0 ;i(graph[minvertex][j] +cost[minvertex])) 40 | cost[j]=graph[minvertex][j] +cost[minvertex]; 41 | } 42 | } 43 | for(int i=0 ;i> V >> E; 55 | 56 | //input a graph 57 | int ** graph =new int* [V]; 58 | for(int i=0 ;i>s>>e>>w; 69 | graph[s][e]=w; 70 | graph[e][s]=w; 71 | } 72 | 73 | Dijkstra(graph,V); 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /Test/Check cousins: -------------------------------------------------------------------------------- 1 | Given the binary Tree and two nodes say ‘p’ and ‘q’. 2 | Determine whether the two nodes are cousins of each other or not. 3 | Two nodes are said to be cousins of each other if they are at same level of the Binary Tree and have different parents. 4 | Do it in O(n). 5 | 6 | bool isSibling(BinaryTreeNode *root, int data_one, 7 | int data_two) 8 | { 9 | if (!root) 10 | return false; 11 | 12 | // Compare the two given nodes with 13 | // the childrens of current node 14 | if (root->left && root->right) { 15 | int left = root->left->data; 16 | int right = root->right->data; 17 | 18 | if (left == data_one && right == data_two) 19 | return true; 20 | else if (left == data_two && right == data_one) 21 | return true; 22 | } 23 | 24 | // Check for left subtree 25 | if (root->left) 26 | isSibling(root->left, data_one, 27 | data_two); 28 | 29 | // Check for right subtree 30 | if (root->right) 31 | isSibling(root->right, data_one, 32 | data_two); 33 | } 34 | 35 | // Recursive function to find level of Node 'ptr' in a binary tree 36 | int level(BinaryTreeNode *root, int ptr, int lev) 37 | { 38 | // base cases 39 | if (root == NULL) return 0; 40 | if (root->data == ptr) return lev; 41 | 42 | // Return level if Node is present in left subtree 43 | int l = level(root->left, ptr, lev+1); 44 | if (l != 0) return l; 45 | 46 | // Else search in right subtree 47 | return level(root->right, ptr, lev+1); 48 | } 49 | 50 | 51 | // Returns 1 if a and b are cousins, otherwise 0 52 | bool isCousin(BinaryTreeNode *root, int a,int b) 53 | { 54 | //1. The two Nodes should be on the same level in the binary tree. 55 | //2. The two Nodes should not be siblings (means that they should 56 | // not have the same parent Node). 57 | if ((level(root,a,1) == level(root,b,1)) && !(isSibling(root,a,b))) 58 | return true; 59 | else return false; 60 | } 61 | 62 | -------------------------------------------------------------------------------- /Graph 1/all connected components: -------------------------------------------------------------------------------- 1 | Given an undirected graph G(V,E), find and print all the connected components of the given graph G. 2 | V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 3 | E is the number of edges present in graph G. 4 | You need to take input in main and create a function which should return all the connected components. And then print them in the main, not inside function. 5 | Print different components in new line. And each component should be printed in increasing order (separated by space). Order of different components doesn't matter. 6 | 7 | 8 | 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | void printDFS(int** graph ,int v,int s,bool* visited ,vector &ans) 15 | { 16 | 17 | ans.push_back(s); 18 | visited[s]= true; 19 | 20 | for(int i =0 ;i< v ;i++) 21 | { 22 | if(!visited[i]&& graph[s][i]==1) 23 | printDFS( graph ,v, i ,visited,ans); 24 | } 25 | 26 | } 27 | void printDFS(int** graph ,int v,int s,bool* visited ) 28 | { 29 | vectorans; 30 | printDFS( graph ,v, s,visited,ans); 31 | 32 | sort(ans.begin() , ans .end()); 33 | 34 | for( auto i :ans ) 35 | cout << i<<" "; 36 | 37 | 38 | } 39 | int main() 40 | { 41 | int V, E; 42 | cin >> V >> E; 43 | 44 | int** graph = new int * [V]; 45 | 46 | for(int i=0 ;i >x>>y; 57 | graph[x][y]=1; 58 | graph[y][x]=1; 59 | } 60 | bool * visited=new bool[V]; 61 | for(int i=0 ;i< V;i++) 62 | visited[V]= false; 63 | 64 | for(int i=0;i 10 | #include 11 | using namespace std; 12 | 13 | 14 | bool getpath ( int ** graph , int v , bool* visited , int s , int e , vector & res) 15 | { 16 | if( s ==e) 17 | { res.push_back(s); 18 | return true; 19 | } 20 | 21 | 22 | 23 | /* if(graph[s][e]==1) 24 | { res.push_back(e); 25 | res.push_back(s); 26 | return true; 27 | }*/ 28 | 29 | 30 | visited[s]=true; 31 | 32 | bool ans =false; 33 | 34 | for(int i=0 ;i> V >> E; 54 | 55 | int** graph = new int * [V]; 56 | 57 | for(int i=0 ;i >x>>y; 68 | graph[x][y]=1; 69 | graph[y][x]=1; 70 | } 71 | bool * visited=new bool[V]; 72 | for(int i=0 ;i< V;i++) 73 | visited[V]= false; 74 | 75 | int s , e ; 76 | cin>> s>> e; 77 | 78 | vector res; 79 | 80 | if(getpath( graph , V , visited , s, e, res )) 81 | for(auto i : res ) 82 | cout<< i <<" "; 83 | 84 | 85 | 86 | 87 | 88 | delete [] visited; 89 | for(int i = 0 ;i 4 | #include 5 | class TrieNode { 6 | public : 7 | char data; 8 | TrieNode **children; 9 | bool isTerminal; 10 | 11 | TrieNode(char data) { 12 | this -> data = data; 13 | children = new TrieNode*[26]; 14 | for(int i = 0; i < 26; i++) { 15 | children[i] = NULL; 16 | } 17 | isTerminal = false; 18 | } 19 | }; 20 | 21 | class Trie { 22 | TrieNode *root; 23 | 24 | public : 25 | int count; 26 | 27 | Trie() { 28 | this->count = 0; 29 | root = new TrieNode('\0'); 30 | } 31 | 32 | bool insertWord(TrieNode *root, string word) { 33 | // Base case 34 | if(word.size() == 0) { 35 | if (!root->isTerminal) { 36 | root -> isTerminal = true; 37 | return true; 38 | } else { 39 | return false; 40 | } 41 | } 42 | 43 | // Small Calculation 44 | int index = word[0] - 'a'; 45 | TrieNode *child; 46 | if(root -> children[index] != NULL) { 47 | child = root -> children[index]; 48 | } 49 | else { 50 | child = new TrieNode(word[0]); 51 | root -> children[index] = child; 52 | } 53 | 54 | // Recursive call 55 | return insertWord(child, word.substr(1)); 56 | } 57 | 58 | // For user 59 | void insertWord(string word) { 60 | if (insertWord(root, word)) { 61 | this->count++; 62 | } 63 | } 64 | bool search(TrieNode *root,string word) { 65 | // Write your code here 66 | if(word.size()==0) 67 | { 68 | return true; 69 | } 70 | if(root->children[word[0]-'a']==NULL) 71 | return false; 72 | 73 | 74 | 75 | return search(root->children[word[0]-'a'],word.substr(1)); 76 | } 77 | bool search(string word) 78 | { return search(root,word);} 79 | bool patternMatching(vector vect, string pattern) { 80 | // Complete this function 81 | // Return true or false 82 | for(int i=0;i {2, 6}, median = 4 27 | S = {6, 2, 1} -> {1, 2, 6}, median = 2 28 | S = {6, 2, 1, 3} -> {1, 2, 3, 6}, median = 2 29 | S = {6, 2, 1, 3, 7} -> {1, 2, 3, 6, 7}, median = 3 30 | S = {6, 2, 1, 3, 7, 5} -> {1, 2, 3, 5, 6, 7}, median = 4 31 | 32 | #include 33 | using namespace std; 34 | void findMedian(int arr[], int n){ 35 | 36 | priority_queue max; 37 | priority_queue , greater> min; 38 | 39 | for(int i=0 ;i 1) 53 | { int x=max.top(); 54 | max.pop(); 55 | min.push(x); 56 | } 57 | else if(int(min.size()-max.size()) > 1) 58 | { int x=min.top(); 59 | min.pop(); 60 | max.push(x); 61 | } 62 | 63 | 64 | int c=max.size()+min.size(); //count 65 | 66 | //checking size of list to find median 67 | if(c%2==0) 68 | cout<<(max.top()+min.top())/2<min.size()) 72 | cout<* tree(int *postorder, int *inorder,int ps,int pe, int is, int ie) 19 | { 20 | if(ps>pe) 21 | return NULL; 22 | 23 | 24 | BinaryTreeNode* root=new BinaryTreeNode(postorder[pe]); 25 | 26 | int k = 0; 27 | for(int i = is; i <= ie; i++) 28 | { if(postorder[pe] == inorder[i]) 29 | { k = i; break; } 30 | } 31 | 32 | int lps=ps; //left prestart 33 | int lis=is; //left instart 34 | int lie=k-1; //left inend 35 | int lpe= lie-lis+lps; //left pre end 36 | 37 | int rps=lpe+1; //right prestart 38 | int rpe=pe-1;// right preend 39 | int ris=k+1; //right instart 40 | int rie=ie; //right inend 41 | 42 | root->left=tree(postorder,inorder,lps,lpe,lis,lie); 43 | root->right=tree(postorder,inorder,rps,rpe,ris,rie); 44 | 45 | return root; 46 | 47 | 48 | } 49 | BinaryTreeNode* getTreeFromPostorderAndInorder(int *postorder, int postLength, int *inorder, int inLength) { 50 | return tree (postorder,inorder,0,postLength-1,0,inLength-1); 51 | 52 | } 53 | 54 | 55 | 56 | /*BinaryTreeNode* tree(int *post,int ps,int pe,int *in,int &postorder ) 57 | { 58 | if(ps>pe) 59 | return NULL; 60 | 61 | 62 | 63 | BinaryTreeNode* temp=new BinaryTreeNode(post[postorder--]); 64 | 65 | int k; 66 | for(k=ps;k<=pe;k++) 67 | { 68 | if(in[k]==post[postorder+1]) 69 | break; 70 | } 71 | 72 | temp->right=tree(post,k+1,pe,in,postorder); 73 | 74 | temp->left=tree(post,ps,k-1,in,postorder); 75 | 76 | return temp; 77 | } 78 | 79 | 80 | BinaryTreeNode* getTreeFromPostorderAndInorder(int *postorder, int postLength, int *inorder, int inLength) { 81 | 82 | int post=postLength-1; 83 | 84 | return tree(postorder,0,postLength-1,inorder,post); 85 | 86 | }*/ 87 | -------------------------------------------------------------------------------- /DP-2/Min Cost Path: -------------------------------------------------------------------------------- 1 | Given an integer matrix of size m*n, you need to find out the value of minimum cost to reach from the cell (0, 0) to (m-1, n-1). 2 | From a cell (i, j), you can move in three directions : (i+1, j), (i, j+1) and (i+1, j+1). 3 | Cost of a path is defined as the sum of values of each cell through which path passes. 4 | 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | 13 | int minCost(int **input, int n, int m,int row=0,int column=0,int **arr) { 14 | 15 | if(arr[row][column]!=-1) 16 | { 17 | return arr[row][column]; 18 | } 19 | if(m-1==column&&n-1==row) 20 | { 21 | return input[row][column]; 22 | } 23 | if(n-1==row) 24 | { 25 | int a=0; 26 | for(int i=column;i 2 | #include 3 | class PriorityQueue { 4 | // Complete this class 5 | vector pq; 6 | 7 | public: 8 | int getSize(){ 9 | return pq.size(); 10 | } 11 | bool isEmpty(){ 12 | return getSize()==0; 13 | } 14 | int getMax() 15 | { 16 | if(pq.size()==0) return INT_MIN; 17 | 18 | return pq[0]; 19 | } 20 | void insert(int element) 21 | { 22 | pq.push_back(element); 23 | int ci=pq.size()-1; 24 | int pi=(ci-1)/2; 25 | 26 | while(pi>=0 && pq[pi]= pq.size()) break; //absence of left child 52 | else 53 | { 54 | if(2*i+2 >= pq.size()) //no right chiid 55 | { 56 | if(pq[i]pq[2*i+2]) //left child is max 68 | { 69 | int temp =pq[i]; 70 | pq[i]=pq[2*i+1]; 71 | pq[2*i+1]=temp; 72 | i=2*i+1; 73 | } 74 | else //right xhild is max 75 | { 76 | int temp =pq[i]; 77 | pq[i]=pq[2*i+2]; 78 | pq[2*i+2]=temp; 79 | i=2*i+2; 80 | } 81 | } 82 | } 83 | } 84 | 85 | 86 | 87 | return ans; 88 | } 89 | }; 90 | -------------------------------------------------------------------------------- /DP-2/Ways To Make Coin Change: -------------------------------------------------------------------------------- 1 | You are given an infinite supply of coins of each of denominations D = {D0, D1, D2, D3, ...... Dn-1}. 2 | You need to figure out the total number of ways W, in which you can make change for Value V using coins of denominations D. 3 | Note : Return 0, if change isn't possible. 4 | Input Format 5 | Line 1 : Integer n i.e. total number of denominations 6 | Line 2 : N integers i.e. n denomination values 7 | Line 3 : Value V 8 | Output Format 9 | Line 1 : Number of ways i.e. W 10 | 11 | 12 | #include 13 | using namespace std; 14 | 15 | int countWaysToMakeChange(int S[], int m, int n){ 16 | 17 | int i, j, x, y; 18 | 19 | // We need n+1 rows as the table 20 | // is constructed in bottom up 21 | // manner using the base case 0 22 | // value case (n = 0) 23 | int table[n + 1][m]; 24 | 25 | // Fill the enteries for 0 26 | // value case (n = 0) 27 | for (i = 0; i < m; i++) 28 | table[0][i] = 1; 29 | 30 | // Fill rest of the table entries 31 | // in bottom up manner 32 | for (i = 1; i < n + 1; i++) 33 | { 34 | for (j = 0; j < m; j++) 35 | { 36 | // Count of solutions including S[j] 37 | x = (i-S[j] >= 0) ? table[i - S[j]][j] : 0; 38 | 39 | // Count of solutions excluding S[j] 40 | y = (j >= 1) ? table[i][j - 1] : 0; 41 | 42 | // total count 43 | table[i][j] = x + y; 44 | } 45 | } 46 | return table[n][m - 1]; 47 | } 48 | 49 | 50 | /*int helper(vector > &dp,int c[],int n,int v){ 51 | if(v<0) 52 | return 0; 53 | if(v==0) 54 | return 1; 55 | if(n==0) 56 | return 0; 57 | ///alredy present 58 | if(dp[n][v]!=0) 59 | return dp[n][v]; 60 | 61 | //Either include nth coin or don't include 62 | int ans=helper(dp,c,n,v-c[n-1])+helper(dp,c,n-1,v); 63 | dp[n][v]=ans; 64 | return ans; 65 | } 66 | int countWaysToMakeChange(int denominations[], int numDenominations, int value){ 67 | 68 | /* Don't write main(). 69 | * Don't read input, it is passed as function argument. 70 | * Return output and don't print it. 71 | * Taking input and printing output is handled automatically. 72 | 73 | 74 | //This problem is of 0-1 knapsack kind. 75 | 76 | 77 | vector > dp(numDenominations+1,vector(value+1,0)); 78 | int ans=helper(dp,denominations,numDenominations,value); 79 | 80 | return ans; 81 | 82 | } 83 | */ 84 | -------------------------------------------------------------------------------- /Graph 1/CODING ninjas: -------------------------------------------------------------------------------- 1 | Given a NxM matrix containing Uppercase English Alphabets only. 2 | Your task is to tell if there is a path in the given matrix which makes the sentence “CODINGNINJA” . 3 | There is a path from any cell to all its neighbouring cells. A neighbour may share an edge or a corner. 4 | 5 | 6 | void initialize(bool **visited,int N,int M){ 7 | 8 | for(int i=0;i=0 && j-1>=0 && Graph[i-1][j-1]==c[0] && !visited[i-1][j-1]) 24 | ans=ans || dfs(Graph,c+1,i-1,j-1,N,M,visited); 25 | 26 | if(i-1>=0 && Graph[i-1][j]==c[0] && !visited[i-1][j]) 27 | ans=ans || dfs(Graph,c+1,i-1,j,N,M,visited); 28 | 29 | if(i-1>=0 && j+1=0 && Graph[i+1][j-1]==c[0] && !visited[i+1][j-1]) 42 | ans=ans || dfs(Graph,c+1,i+1,j-1,N,M,visited); 43 | 44 | if(j-1>=0 && Graph[i][j-1]==c[0] && !visited[i][j-1]) 45 | ans=ans || dfs(Graph,c+1,i,j-1,N,M,visited); 46 | 47 | return ans; 48 | 49 | 50 | 51 | 52 | 53 | } 54 | 55 | int solve(char Graph[][MAXN],int N, int M) 56 | { 57 | // Write your code here. 58 | char c[]="CODINGNINJA"; 59 | bool **visited=new bool*[N]; 60 | for(int i=0;i 29 | 30 | //dynamic programming 31 | int minCount ( int n) 32 | { 33 | if ( sqrt (n) -floor(sqrt(n))==0) return 1; 34 | 35 | int arr[n+1]; 36 | arr[0]=0; 37 | arr[1]=1; 38 | arr[2]=2; 39 | arr[3]=3; 40 | 41 | for(int i=4 ;i<=n ;i++) 42 | { 43 | 44 | arr[i] = i; 45 | 46 | for (int x = 1; x <= ceil(sqrt(i)); x++) { 47 | int temp = x * x; 48 | if (temp > i) 49 | break; 50 | else 51 | arr[i] = min(arr[i], 1 + arr[i - temp]); 52 | } 53 | } 54 | return arr[n]; 55 | 56 | } 57 | 58 | 59 | //memoization 60 | /* 61 | int mincount ( int n , int *arr) 62 | { 63 | 64 | if( sqrt (n) -floor(sqrt(n))==0) 65 | { arr[n]=1; 66 | return arr[n]; 67 | } 68 | if(n <=3) 69 | { arr[n]=n; 70 | return n; 71 | } 72 | int ans= n; 73 | if(arr[n] != 0) return arr[n]; 74 | for(int i=1 ; i*i<=n ; i++) 75 | { 76 | 77 | arr[n] =ans= min(ans , 1 + mincount(n-i*i,arr)); 78 | } 79 | 80 | return arr[n]; 81 | } 82 | 83 | int minCount(int n){ 84 | int arr [n+1]; 85 | for(int i=0 ;i<=n ;i++) 86 | arr[i]=0; 87 | return mincount(n , arr); 88 | 89 | } 90 | 91 | */ 92 | 93 | // brute force 94 | /* 95 | int minCount(int n){ 96 | 97 | if( sqrt (n) -floor(sqrt(n))==0) 98 | return 1; 99 | if(n <=3) 100 | return n; 101 | int ans= n; 102 | for(int i=1 ; i*i<=n ; i++) 103 | { 104 | ans = min(ans , 1 + minCount(n-i*i)); 105 | } 106 | 107 | 108 | return ans; 109 | 110 | }*/ 111 | -------------------------------------------------------------------------------- /binary trees/Min and Max of Binary Tree: -------------------------------------------------------------------------------- 1 | Given a binary tree, find and return the min and max data value of given binary tree. 2 | Return the output as an object of PairAns class, which is already created. 3 | 4 | 5 | #include 6 | #include 7 | 8 | template 9 | class BinaryTreeNode { 10 | public : 11 | T data; 12 | BinaryTreeNode *left; 13 | BinaryTreeNode *right; 14 | 15 | BinaryTreeNode(T data) { 16 | this -> data = data; 17 | left = NULL; 18 | right = NULL; 19 | } 20 | }; 21 | 22 | class PairAns { 23 | public : 24 | int min; 25 | int max; 26 | }; 27 | 28 | using namespace std; 29 | #include "solution.h" 30 | 31 | BinaryTreeNode* takeInput() { 32 | int rootData; 33 | //cout << "Enter root data : "; 34 | cin >> rootData; 35 | if(rootData == -1) { 36 | return NULL; 37 | } 38 | BinaryTreeNode *root = new BinaryTreeNode(rootData); 39 | queue*> q; 40 | q.push(root); 41 | while(!q.empty()) { 42 | BinaryTreeNode *currentNode = q.front(); 43 | q.pop(); 44 | int leftChild, rightChild; 45 | //cout << "Enter left child of " << currentNode -> data << " : "; 46 | cin >> leftChild; 47 | if(leftChild != -1) { 48 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 49 | currentNode -> left =leftNode; 50 | q.push(leftNode); 51 | } 52 | //cout << "Enter right child of " << currentNode -> data << " : "; 53 | cin >> rightChild; 54 | if(rightChild != -1) { 55 | BinaryTreeNode* rightNode = new BinaryTreeNode(rightChild); 56 | currentNode -> right =rightNode; 57 | q.push(rightNode); 58 | } 59 | } 60 | return root; 61 | } 62 | 63 | #include 64 | PairAns minMax(BinaryTreeNode *root) { 65 | if(root->left==NULL && root->right==NULL) 66 | { PairAns ans; 67 | ans.max=ans.min=root->data; 68 | return ans; 69 | } 70 | 71 | PairAns ans; 72 | ans.max=ans.min=root->data; 73 | 74 | if(root->left) 75 | { 76 | PairAns ansleft= minMax(root->left); 77 | ans.max=max(ans.max,ansleft.max); 78 | 79 | ans.min=min(ans.min,ansleft.min); 80 | } 81 | if(root->right) 82 | { 83 | PairAns ansright= minMax(root->right); 84 | ans.max=max(ans.max,ansright.max); 85 | 86 | ans.min=min(ans.min,ansright.min); 87 | } 88 | 89 | return ans; 90 | } 91 | 92 | int main() { 93 | BinaryTreeNode* root = takeInput(); 94 | PairAns ans = minMax(root); 95 | cout << ans.max << " " << ans.min << endl; 96 | } 97 | -------------------------------------------------------------------------------- /recursion 2/Merge Sort Code: -------------------------------------------------------------------------------- 1 | void merging(int input [],int low, int mid, int high) { 2 | 3 | int b[high-low+1]; 4 | int l1=low,l2=mid+1,i=0; 5 | while(l1 <= mid && l2 <= high) { 6 | if(input[l1] <= input[l2]) 7 | b[i++] = input[l1++]; 8 | else 9 | b[i++] = input[l2++]; 10 | } // end while loop here 11 | while(l1 <= mid) 12 | { 13 | b[i++] = input[l1++]; 14 | } 15 | 16 | while(l2 <= high) 17 | { 18 | b[i++] = input[l2++]; 19 | } 20 | 21 | int j=0; 22 | for(i = low; i <= high; i++) 23 | input[i] = b[j++]; 24 | 25 | // } dont end it here 26 | } 27 | void mergeSort1(int input[],int first,int last) 28 | { 29 | 30 | 31 | if(first=e) 104 | return; 105 | else 106 | { 107 | int mid=(s+e)/2; 108 | MergeSorting(a,s,mid); 109 | MergeSorting(a,mid+1,e); 110 | MergeArray(a,s,e); 111 | } 112 | } 113 | 114 | void mergeSort(int input[], int size){ 115 | // Write your code here 116 | 117 | int start =1; 118 | int end = size; 119 | 120 | MergeSorting(input,start,end); 121 | 122 | 123 | } 124 | -------------------------------------------------------------------------------- /Recursion 1/All indices of a number: -------------------------------------------------------------------------------- 1 | int allIndexes(int input[], int size, int x, int output[]) { 2 | if(size == 0) 3 | return 0; 4 | int smallCount= allIndexes(input, size -1, x, output); 5 | if(input[size -1] == x) 6 | { 7 | output[smallCount] = size -1; 8 | return smallCount +1; 9 | } else { 10 | return smallCount; 11 | } 12 | } 13 | 14 | ---------------------------------------------------------------------------------------------------------------------------------------------------- 15 | int allIndexes(int input[], int size, int x, int output[]) { 16 | 17 | if(size==0) 18 | return 0; 19 | int ans =allIndexes(input+1,size-1,x,output); 20 | 21 | // output[k]=output[k]+1;k++; 22 | if(input[0]==x){ 23 | if(ans!=0) // if output contains previous indexes 24 | { 25 | for(int i=ans-1 ;i>=0;i--) // increment their index and shift them 1 right side as we have to add 26 | //at output[0] the current index 27 | { 28 | output[i]++; 29 | output[i+1]=output[i]; 30 | 31 | } 32 | } 33 | 34 | output[0]=0; 35 | return ans+1; 36 | } 37 | else 38 | { //just incrmemnt index 39 | for(int i=ans-1 ;i>=0;i--) 40 | { 41 | output[i]++; 42 | //output[i+1]=output[i]; 43 | } 44 | return ans; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------------------------------------------------------------------------------------- 49 | #include 50 | 51 | using namespace std; 52 | 53 | void help(int input[],int size,int x, int i, int *k,int output[]) 54 | { 55 | if(i==size) 56 | return; 57 | if(input[i]==x) 58 | { 59 | output[0]=i; 60 | output++; 61 | *k=*k+1; 62 | } 63 | help(input,size,x,i+1,k,output); 64 | } 65 | int allIndexes(int input[], int size, int x, int output[]) { 66 | 67 | int i=0;int k=0; 68 | help(input,size,x,i,&k,output); 69 | return k; 70 | 71 | } 72 | 73 | 74 | int main(){ 75 | int n; 76 | cin >> n; 77 | 78 | int *input = new int[n]; 79 | 80 | for(int i = 0; i < n; i++) { 81 | cin >> input[i]; 82 | } 83 | 84 | int x; 85 | 86 | cin >> x; 87 | 88 | int *output = new int[n]; 89 | 90 | int size = allIndexes(input, n, x, output); 91 | for(int i = 0; i < size; i++) { 92 | cout << output[i] << " "; 93 | } 94 | 95 | delete [] input; 96 | 97 | delete [] output; 98 | 99 | 100 | } 101 | 102 | 103 | -------------------------------------------------------------------------------- /OOPS1/complex number class: -------------------------------------------------------------------------------- 1 | A ComplexNumber class contains two data members : one is the real part (R) and the other is imaginary (I) (both integers). 2 | Implement the Complex numbers class that contains following functions - 3 | 1. constructor 4 | You need to create the appropriate constructor. 5 | 2. plus - 6 | This function adds two given complex numbers and updates the first complex number. 7 | e.g. 8 | if C1 = 4 + i5 and C2 = 3 +i1 9 | C1.plus(C2) results in: 10 | C1 = 7 + i6 and C2 = 3 + i1 11 | 3. multiply - 12 | This function multiplies two given complex numbers and updates the first complex number. 13 | e.g. 14 | if C1 = 4 + i5 and C2 = 1 + i2 15 | C1.multiply(C2) results in: 16 | C1 = -6 + i13 and C2 = 1 + i2 17 | 4. print - 18 | This function prints the given complex number in the following format : 19 | a + ib 20 | Note : There is space before and after '+' (plus sign) and no space between 'i' (iota symbol) and b. 21 | Input Format : 22 | Line 1 : Two integers - real and imaginary part of 1st complex number 23 | Line 2 : Two integers - real and imaginary part of 2nd complex number 24 | Line 3 : An integer representing choice (1 or 2) (1 represents plus function will be called and 2 represents multiply function will be called) 25 | Output format : 26 | Check details of 'print' function given above. 27 | Sample Input 1 : 28 | 4 5 29 | 6 7 30 | 1 31 | Sample Output 1 : 32 | 10 + i12 33 | 34 | 35 | class ComplexNumbers { 36 | // Complete this class 37 | private: 38 | int real; 39 | int imag; 40 | 41 | public: 42 | ComplexNumbers(int real ,int imag) 43 | { 44 | this->real=real; 45 | this->imag=imag; 46 | } 47 | 48 | void print() 49 | { 50 | cout<real=real+c2.real; ///this is nnot compulsory to use as it already know about it; 56 | imag=imag+c2.imag; 57 | } 58 | void multiply(ComplexNumbers const & c2 ) 59 | { 60 | int x=(real*c2.real)-(imag*c2.imag); 61 | int y=(real*c2.imag)+(imag*c2.real); 62 | real=x; 63 | imag=y; 64 | } 65 | #include 66 | using namespace std; 67 | 68 | 69 | int main() { 70 | int real1, imaginary1, real2, imaginary2; 71 | 72 | cin >> real1 >> imaginary1; 73 | cin >> real2 >> imaginary2; 74 | 75 | ComplexNumbers c1(real1, imaginary1); 76 | ComplexNumbers c2(real2, imaginary2); 77 | 78 | int choice; 79 | cin >> choice; 80 | 81 | if(choice == 1) { 82 | c1.plus(c2); 83 | c1.print(); 84 | } 85 | else if(choice == 2) { 86 | c1.multiply(c2); 87 | c1.print(); 88 | } 89 | else { 90 | return 0; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Graph 1/BFS Traversal: -------------------------------------------------------------------------------- 1 | Given an undirected and disconnected graph G(V, E), print its BFS traversal. 2 | Here you need to consider that you need to print BFS path starting from vertex 0 only. 3 | V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 4 | E is the number of edges present in graph G. 5 | Note : 1. Take graph input in the adjacency matrix. 6 | 2. Handle for Disconnected Graphs as well 7 | 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | 16 | vector * getpath( int ** graph , int v , int s ,int e , bool * visited) 17 | { 18 | queue pn; 19 | unordered_map m; 20 | pn.push(s); 21 | visited[s]=true; 22 | 23 | while(!pn.empty()) 24 | { 25 | int t= pn.front(); 26 | 27 | pn.pop(); 28 | 29 | 30 | for(int i=0 ; i * ans = new vector(); 41 | 42 | ans->push_back(e); 43 | int x =e; 44 | while(m[x]!=s) 45 | { 46 | ans->push_back(m[x]); 47 | x=m[x]; 48 | } 49 | ans->push_back(s); 50 | 51 | return ans; 52 | } 53 | } 54 | } 55 | 56 | 57 | } 58 | return NULL; 59 | } 60 | 61 | 62 | int main() 63 | { 64 | int V, E; 65 | cin >> V >> E; 66 | 67 | int** graph = new int * [V]; 68 | for( int i=0 ;i>x>>y ; 79 | graph[x][y]=1; 80 | graph[y][x]=1; 81 | } 82 | bool * visited = new bool[V]; 83 | for ( int i=0 ;i>s>>e; 88 | 89 | vector * ans = getpath(graph , V,s,e,visited); 90 | if(ans) 91 | { 92 | for(int i=0 ;i< ans->size(); i++) 93 | cout<< ans->at(i) << " "; 94 | } 95 | 96 | delete ans; 97 | 98 | for(int i=0 ;i 11 | bool bfs( vector< vector > &board , int n , int m ,int ci , int cj,vector< vector >&visited,string s) 12 | { 13 | if(s.size()==0) 14 | { 15 | return true; 16 | } 17 | visited[ci][cj]=true; 18 | 19 | 20 | bool ans = false; 21 | if(ci+1=0 && !visited[ci-1][cj] && board[ci-1][cj]==s[0])// up 28 | 29 | { 30 | if( bfs(board,n,m,ci-1,cj,visited, s.substr(1))) 31 | return true; 32 | } 33 | if(cj-1>=0 && !visited[ci][cj-1] && board[ci][cj-1]==s[0])// left 34 | { 35 | if( bfs(board,n,m,ci,cj-1,visited, s.substr(1))) 36 | return true; 37 | } 38 | 39 | if(cj+1=0&&!visited[ci+1][cj-1] && board[ci+1][cj-1]==s[0])// down left 47 | { 48 | if( bfs(board,n,m,ci+1,cj-1,visited, s.substr(1))) 49 | return true; 50 | } 51 | 52 | if(ci+1=0 && cj-1>=0 && !visited[ci-1][cj-1] && board[ci-1][cj-1]==s[0])// up left 60 | { 61 | if( bfs(board,n,m,ci-1,cj-1,visited, s.substr(1))) 62 | return true; 63 | } 64 | 65 | if(ci-1>=0 && cj+1> &board, int n, int m) { 80 | vector >visited(n,vector(m, false)); 81 | for(int i=0; i*root, int k) 5 | { 6 | // Base Case 7 | if (root == NULL || k < 0) return; 8 | 9 | // If we reach a k distant node, print it 10 | if (k==0) 11 | { 12 | cout << root->data << endl; 13 | return; 14 | } 15 | 16 | // Recur for left and right subtrees 17 | printkdistanceNodeDown(root->left, k-1); 18 | printkdistanceNodeDown(root->right, k-1); 19 | } 20 | // Prints all nodes at distance k from a given target node. 21 | // The k distant nodes may be upward or downward. This function 22 | // Returns distance of root from target node, it returns -1 if target 23 | // node is not present in tree rooted with root. 24 | 25 | // Write your code here 26 | int printkdistanceNode(BinaryTreeNode* root, int target , int k) 27 | { 28 | // Base Case 1: If tree is empty, return -1 29 | if (root == NULL) return -1; 30 | 31 | // If target is same as root. Use the downward function 32 | // to print all nodes at distance k in subtree rooted with 33 | // target or root 34 | if (root->data == target) 35 | { 36 | printkdistanceNodeDown(root, k); 37 | return 0; 38 | } 39 | 40 | // Recur for left subtree 41 | int dl = printkdistanceNode(root->left, target, k); 42 | 43 | // Check if target node was found in left subtree 44 | if (dl != -1) 45 | { 46 | // If root is at distance k from target, print root 47 | // Note that dl is Distance of root's left child from target 48 | if (dl + 1 == k) 49 | cout << root->data << endl; 50 | 51 | // Else go to right subtree and print all k-dl-2 distant nodes 52 | // Note that the right child is 2 edges away from left child 53 | else 54 | printkdistanceNodeDown(root->right, k-dl-2); 55 | 56 | // Add 1 to the distance and return value for parent calls 57 | return 1 + dl; 58 | } 59 | 60 | // MIRROR OF ABOVE CODE FOR RIGHT SUBTREE 61 | // Note that we reach here only when node was not found in left subtree 62 | int dr = printkdistanceNode(root->right, target, k); 63 | if (dr != -1) 64 | { 65 | if (dr + 1 == k) 66 | cout << root->data << endl; 67 | else 68 | printkdistanceNodeDown(root->left, k-dr-2); 69 | return 1 + dr; 70 | } 71 | 72 | // If target was neither present in left nor in right subtree 73 | return -1; 74 | } 75 | void nodesAtDistanceK(BinaryTreeNode *root, int node, int k) { 76 | int x= printkdistanceNode(root,node,k); 77 | } 78 | -------------------------------------------------------------------------------- /BST/pair sum in BST: -------------------------------------------------------------------------------- 1 | Given a binary search tree and an integer S, 2 | find pair of nodes in the BST which sum to S. You can use extra space only O(log n). 3 | 4 | 5 | #include 6 | int countnodes(BinaryTreeNode *root) 7 | { 8 | if(root==NULL) return 0; 9 | 10 | return 1+ countnodes(root->left) +countnodes (root->right); 11 | } 12 | void printNodesSumToS(BinaryTreeNode *root, int s) { 13 | 14 | int totalnodes=countnodes(root); 15 | int count=0; 16 | 17 | stack* > inorder; 18 | stack* > revinorder; 19 | 20 | BinaryTreeNode *temp=root; 21 | 22 | while(temp) 23 | { 24 | inorder.push(temp); 25 | 26 | temp=temp->left; 27 | } 28 | temp=root; 29 | while(temp) 30 | { 31 | revinorder.push(temp); 32 | 33 | temp=temp->right; 34 | } 35 | 36 | while (count *top1=inorder.top(); 39 | BinaryTreeNode *top2=revinorder.top(); 40 | if(top1->data + top2->data == s) 41 | {cout<< top1->data <<" "<data< *top=top1; 44 | inorder.pop(); 45 | count++; 46 | if(top->right) 47 | { 48 | top=top->right; 49 | while(top) 50 | { inorder.push(top); 51 | top=top->left; 52 | } 53 | } 54 | top=top2; 55 | revinorder.pop(); 56 | count++; 57 | if(top->left) 58 | { 59 | top=top->left; 60 | while(top) 61 | { revinorder.push(top); 62 | top=top->right; 63 | } 64 | } 65 | 66 | } 67 | else if(top1->data + top2->data > s) 68 | { 69 | BinaryTreeNode *top=top2; 70 | revinorder.pop(); 71 | count++; 72 | if(top->left) 73 | { 74 | top=top->left; 75 | while(top) 76 | { revinorder.push(top); 77 | top=top->right; 78 | } 79 | } 80 | } 81 | else 82 | { 83 | BinaryTreeNode *top=top1; 84 | inorder.pop(); 85 | count++; 86 | if(top->right) 87 | { 88 | top=top->right; 89 | while(top) 90 | { inorder.push(top); 91 | top=top->left; 92 | } 93 | } 94 | } 95 | 96 | } 97 | } 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /Graph 2/Kruskal's Algorithm: -------------------------------------------------------------------------------- 1 | Given an undirected, connected and weighted graph G(V, E) with V number of vertices (which are numbered from 0 to V-1) and E number of edges. 2 | Find and print the Minimum Spanning Tree (MST) using Kruskal's algorithm. 3 | For printing MST follow the steps - 4 | 1. In one line, print an edge which is part of MST in the format - 5 | v1 v2 w 6 | where, v1 and v2 are the vertices of the edge which is included in MST and whose weight is w. And v1 <= v2 i.e. print the smaller vertex first while printing an edge. 7 | 2. Print V-1 edges in above format in different lines. 8 | 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | class edge 14 | { 15 | public: 16 | 17 | int s;//source 18 | int d;//destination 19 | int w;//weight 20 | 21 | edge(){} 22 | edge(int s,int d ,int w) 23 | { 24 | this->s=s; 25 | this->d=d; 26 | this->w=w; 27 | } 28 | }; 29 | 30 | bool comp(edge const & a , edge const & b) 31 | { 32 | return a.w < b.w; 33 | } 34 | int findparent(int * parent ,int v) 35 | { 36 | if(parent[v]==v) 37 | return v; 38 | 39 | return findparent(parent,parent[v]); 40 | } 41 | void kruskalMST(edge * input, int v , int e) 42 | {//sort in ascending order on basis of weights of edges 43 | sort(input,input+e, comp); 44 | 45 | int* parent =new int[v]; 46 | for(int i=0 ;i > V >> E; 89 | 90 | // input graph 91 | edge *input= new edge[E]; 92 | for(int i= 0; i>s>>d>>w; 95 | input[i]=edge(s,d,w); 96 | } 97 | 98 | 99 | kruskalMST(input,V,E); 100 | 101 | delete [] input; 102 | 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /Graph 1/connecting dots: -------------------------------------------------------------------------------- 1 | Gary has a board of size NxM. Each cell in the board is a coloured dot. There exist only 26 colours denoted by uppercase Latin characters (i.e. A,B,...,Z). Now Gary is getting bore and wants to play a game. The key of this game is to find a cycle that contain dots of same colour. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: 2 | 1. These k dots are different: if i ≠ j then di is different from dj. 3 | 2. k is at least 4. 4 | 3. All dots belong to the same colour. 5 | 4. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. 6 | Since Gary is colour blind, he wants your help. Your task is to determine if there exists a cycle on the board. 7 | Assume input to be 0-indexed based. 8 | 9 | 10 | void initialize(bool ** visited,int n,int m){ 11 | for(int i=0;i=0 && !(i-1==pi && j==pj)&& visited[i-1][j]); 25 | bool d4=(j-1>=0 && !(i==pi && j-1==pj) && visited[i][j-1]); 26 | 27 | if(d1 || d2 || d3 || d4) 28 | return true; 29 | 30 | bool ans=false; 31 | visited[i][j]=true; 32 | if(i+1=0 && board[i-1][j]==col && !visited[i-1][j]) 39 | ans=ans || dfs(board,col,i,j,i-1,j,n,m,visited); 40 | 41 | if(j-1>=0 && board[i][j-1]==col && !visited[i][j-1]) 42 | ans=ans || dfs(board,col,i,j,i,j-1,n,m,visited); 43 | 44 | return ans; 45 | } 46 | 47 | int solve(char board[][MAXN],int n, int m) 48 | { 49 | // Write your code here. 50 | bool **visited=new bool*[n]; 51 | for(int i=0;i 39 | int buyTicket (int *arr, int n, int k){ 40 | 41 | queue p; //a queue of indices 42 | for(int i=0;i pq; 47 | //build a heap 48 | for(int i=0 ; iarr[p.front()]) 58 | { int x=p.front(); 59 | p.pop(); 60 | p.push(x); 61 | } 62 | 63 | else if(pq.top()==arr[p.front()]) 64 | { pq.pop(); 65 | p.pop(); 66 | time++; //incres time 67 | } 68 | } 69 | return time+1; //now i will be getting the ticket 70 | } 71 | -------------------------------------------------------------------------------- /trees/second largest element in a tree (important): -------------------------------------------------------------------------------- 1 | Given a generic tree, 2 | find and return the node with second largest value in given tree. 3 | Return NULL if no node with required value is present. 4 | 5 | //approach 1 is to find max and replace it by -infinty ans then again find the max 6 | but this change the given tree 7 | 8 | // other approach can be to ask func to bring max and second max 9 | // total cases needed to be handled 10 | 11 | // 2 answers 12 | class helper { 13 | public : 14 | TreeNode* m; 15 | TreeNode* sm; 16 | 17 | helper (TreeNode* m, TreeNode* sm) { 18 | this->m = m; 19 | this->sm = sm; 20 | } 21 | }; 22 | 23 | helper help (TreeNode* root) { 24 | if(root==NULL){ 25 | helper r(NULL,NULL); 26 | return r; 27 | } 28 | helper ans(root, NULL); 29 | for (int i = 0; i < root->children.size(); i++) { 30 | helper child = help (root -> children[i]); 31 | if(child.m->data > ans.m->data){ 32 | if(child.sm==NULL){ 33 | ans.sm=ans.m; 34 | ans.m=child.m; 35 | } 36 | else{ 37 | if(child.sm->data > ans.m->data){ 38 | ans.sm=child.sm; 39 | ans.m=child.m; 40 | } 41 | else{ 42 | ans.sm=ans.m; 43 | ans.m=child.m; 44 | } 45 | } 46 | } 47 | else { 48 | if(ans.m->data!=child.m->data && (ans.sm==NULL || child.m->data > ans.sm->data)){ 49 | ans.sm=child.m; 50 | } 51 | } 52 | } 53 | return ans; 54 | } 55 | 56 | TreeNode * secondLargest(TreeNode *root) { 57 | 58 | if (root == NULL) return NULL; 59 | helper ans = help (root); 60 | return ans.sm; 61 | } 62 | 63 | 64 | 65 | 66 | 67 | void helper(TreeNode *root,TreeNode **first,TreeNode **second){ 68 | if(root==NULL) 69 | { 70 | return; 71 | 72 | } 73 | if(!(*first)){ 74 | *first=root; 75 | } 76 | else if(root->data>(*first)->data){ 77 | *second=*first; 78 | *first=root; 79 | } 80 | else if(!(*second)|| root->data>(*second)->data) 81 | *second=root; 82 | 83 | for(int i=0;ichildren.size();i++) 84 | helper(root->children[i],first,second); 85 | 86 | } 87 | TreeNode * secondLargest(TreeNode *root) { 88 | TreeNode *second=NULL; 89 | TreeNode *first=NULL; 90 | helper(root,&first,&second); 91 | 92 | if(second==NULL) 93 | return NULL; 94 | if(first->data==second->data) 95 | return NULL; 96 | return second; 97 | // Write your code here 98 | 99 | } 100 | -------------------------------------------------------------------------------- /BST/BST class.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | class BST { 5 | BinaryTreeNode* root; 6 | 7 | public: 8 | 9 | BST() { 10 | root = NULL; 11 | } 12 | 13 | ~BST() { 14 | delete root; 15 | } 16 | 17 | private: 18 | BinaryTreeNode* deleteData(int data, BinaryTreeNode* node) { 19 | if (node == NULL) { 20 | return NULL; 21 | } 22 | 23 | if (data > node->data) { 24 | node->right = deleteData(data, node->right); 25 | return node; 26 | } else if (data < node->data) { 27 | node->left = deleteData(data, node->left); 28 | return node; 29 | } else { 30 | if (node->left == NULL && node->right == NULL) { 31 | delete node; 32 | return NULL; 33 | } else if (node->left == NULL) { 34 | BinaryTreeNode* temp = node->right; 35 | node->right = NULL; 36 | delete node; 37 | return temp; 38 | } else if (node->right == NULL) { 39 | BinaryTreeNode* temp = node->left; 40 | node->left = NULL; 41 | delete node; 42 | return temp; 43 | } else { 44 | BinaryTreeNode* minNode = node->right; 45 | while (minNode->left != NULL) { 46 | minNode = minNode->left; 47 | } 48 | int rightMin = minNode->data; 49 | node->data = rightMin; 50 | node->right = deleteData(rightMin, node->right); 51 | return node; 52 | } 53 | } 54 | } 55 | 56 | void printTree(BinaryTreeNode* root) { 57 | if (root == NULL) { 58 | return; 59 | } 60 | cout << root->data << ":"; 61 | if (root->left != NULL) { 62 | cout << "L:" << root->left->data<<","; 63 | } 64 | 65 | if (root->right != NULL) { 66 | cout << "R:" << root->right->data; 67 | } 68 | cout << endl; 69 | printTree(root->left); 70 | printTree(root->right); 71 | } 72 | 73 | 74 | public: 75 | void deleteData(int data) { 76 | root = deleteData(data, root); 77 | } 78 | 79 | void printTree() { 80 | printTree(root); 81 | } 82 | 83 | private: 84 | BinaryTreeNode* insert(int data, BinaryTreeNode* node) { 85 | if (node == NULL) { 86 | BinaryTreeNode* newNode = new BinaryTreeNode(data); 87 | return newNode; 88 | } 89 | 90 | if (data < node->data) { 91 | node->left = insert(data, node->left); 92 | } else { 93 | node->right = insert(data, node->right); 94 | } 95 | return node; 96 | } 97 | 98 | public: 99 | void insert(int data) { 100 | this->root = insert(data, this->root); 101 | } 102 | 103 | private: 104 | bool hasData(int data, BinaryTreeNode* node) { 105 | if (node == NULL) { 106 | return false; 107 | } 108 | 109 | if (node->data == data) { 110 | return true; 111 | } else if (data < node->data) { 112 | return hasData(data, node->left); 113 | } else { 114 | return hasData(data, node->right); 115 | } 116 | } 117 | 118 | public: 119 | bool hasData(int data) { 120 | return hasData(data, root); 121 | } 122 | }; 123 | -------------------------------------------------------------------------------- /trees/print level wise.cpp: -------------------------------------------------------------------------------- 1 | /*Given a generic tree, print the input tree in level wise order. 2 | ####For printing a node with data N, you need to follow the exact format - 3 | N:x1,x2,x3,...,xn 4 | wherer, N is data of any node present in the binary tree. x1, x2, x3, ...., xn are the children of node N 5 | There is no space in between. 6 | You need to print all nodes in the level order form in different lines. 7 | Input format : 8 | Elements in level order form separated by space (as per done in class). Order is - 9 | Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 10 | Output Format : 11 | Level wise print 12 | Sample Input : 13 | 10 3 20 30 40 2 40 50 0 0 0 0 14 | Sample Output : 15 | 10:20,30,40 16 | 20:40,50 17 | 30: 18 | 40: 19 | 40: 20 | 50: 21 | */ 22 | #include 23 | using namespace std; 24 | #include 25 | 26 | template 27 | class TreeNode { 28 | public: 29 | T data; 30 | vector*> children; 31 | 32 | TreeNode(T data) { 33 | this->data = data; 34 | } 35 | 36 | ~TreeNode() { 37 | for (int i = 0; i < children.size(); i++) { 38 | delete children[i]; 39 | } 40 | } 41 | 42 | }; 43 | 44 | 45 | #include 46 | 47 | 48 | TreeNode* takeInputLevelWise() { 49 | int rootData; 50 | cin >> rootData; 51 | TreeNode* root = new TreeNode(rootData); 52 | 53 | queue*> pendingNodes; 54 | 55 | pendingNodes.push(root); 56 | while (pendingNodes.size() != 0) { 57 | TreeNode* front = pendingNodes.front(); 58 | pendingNodes.pop(); 59 | int numChild; 60 | cin >> numChild; 61 | for (int i = 0; i < numChild; i++) { 62 | int childData; 63 | cin >> childData; 64 | TreeNode* child = new TreeNode(childData); 65 | front->children.push_back(child); 66 | pendingNodes.push(child); 67 | } 68 | } 69 | return root; 70 | } 71 | void printLevelWise(TreeNode* root) { 72 | 73 | if(root->data==NULL) 74 | return; 75 | 76 | 77 | queue*> pendingnodes; 78 | pendingnodes.push(root); 79 | 80 | while(pendingnodes.size()!=0) 81 | { 82 | TreeNode*front=pendingnodes.front(); 83 | pendingnodes.pop(); 84 | cout<data<<":"; 85 | for(int i=0;ichildren.size();i++) 86 | { 87 | pendingnodes.push(front->children[i]); 88 | if(i==front->children.size()-1) 89 | cout<children[i]->data; 90 | 91 | else 92 | cout<children[i]->data<<","; 93 | } 94 | 95 | cout<* root = takeInputLevelWise(); 102 | printLevelWise(root); 103 | } 104 | 105 | -------------------------------------------------------------------------------- /tries and huffman coding/auto complete: -------------------------------------------------------------------------------- 1 | Givan n number of words and an incomplete word w. You need to auto-complete that word w. 2 | That means, find and print all the possible words which can be formed using the incomplete word w. 3 | 4 | // #include "TrieNode.h" 5 | #include 6 | #include 7 | class TrieNode { 8 | public : 9 | char data; 10 | TrieNode **children; 11 | bool isTerminal; 12 | 13 | TrieNode(char data) { 14 | this -> data = data; 15 | children = new TrieNode*[26]; 16 | for(int i = 0; i < 26; i++) { 17 | children[i] = NULL; 18 | } 19 | isTerminal = false; 20 | } 21 | }; 22 | 23 | class Trie { 24 | TrieNode *root; 25 | 26 | public : 27 | int count; 28 | 29 | Trie() { 30 | this->count = 0; 31 | root = new TrieNode('\0'); 32 | } 33 | 34 | bool insertWord(TrieNode *root, string word) { 35 | // Base case 36 | if(word.size() == 0) { 37 | if (!root->isTerminal) { 38 | root -> isTerminal = true; 39 | return true; 40 | } else { 41 | return false; 42 | } 43 | } 44 | 45 | // Small Calculation 46 | int index = word[0] - 'a'; 47 | TrieNode *child; 48 | if(root -> children[index] != NULL) { 49 | child = root -> children[index]; 50 | } 51 | else { 52 | child = new TrieNode(word[0]); 53 | root -> children[index] = child; 54 | } 55 | 56 | // Recursive call 57 | return insertWord(child, word.substr(1)); 58 | } 59 | 60 | // For user 61 | void insertWord(string word) { 62 | if (insertWord(root, word)) { 63 | this->count++; 64 | } 65 | } 66 | bool search(TrieNode *root,string word) { 67 | // Write your code here 68 | if(word.size()==0) return true; 69 | 70 | if(root->children[word[0]-'a']==NULL) 71 | return false; 72 | 73 | 74 | 75 | return search(root->children[word[0]-'a'],word.substr(1)); 76 | } 77 | bool search(string word) 78 | { return search(root,word);} 79 | 80 | 81 | void autocomplete(TrieNode *root ,string s) 82 | { 83 | if(root->isTerminal==true) 84 | cout<children[i]!=NULL) 88 | { char c= i + 'a'; 89 | autocomplete(root->children[i],s+c); 90 | } 91 | } 92 | return; 93 | } 94 | void autoComplete(vector input, string pattern) { 95 | //build a trie 96 | for(int i=0 ;ichildren[pattern[0]-'a']; 107 | pattern=pattern.substr(1); 108 | } 109 | 110 | autocomplete( root , s); 111 | } 112 | 113 | 114 | 115 | 116 | }; 117 | -------------------------------------------------------------------------------- /hashmap/Longest consecutive Sequence: -------------------------------------------------------------------------------- 1 | You are given with an array of integers that contain numbers in random order. 2 | Write a program to find the longest possible sequence of consecutive numbers using the numbers from given array. 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | vector longestConsecutiveIncreasingSequence(int *arr, int n){ 10 | vector ans; 11 | unordered_map a; 12 | for(int i=0;i0) 24 | continue; 25 | while(a.count(x)>0 ) 26 | { 27 | 28 | j++; 29 | x++; 30 | } 31 | if(j>max) 32 | { 33 | max=j; 34 | k=arr[i]; 35 | //cout<<" j:"< longestConsecutiveIncreasingSequence(int *arr, int n){ 52 | 53 | unordered_map m; 54 | unordered_map index; 55 | for(int i=0;i0 && m[j]==true) //forward (if present and not visited) 73 | { 74 | nsize+=1; 75 | m[j]=false; 76 | j++; 77 | } 78 | // cout<0 && m[j]==true) //backward (if present and not visited) 82 | { 83 | nstart =j; 84 | nsize+=1; 85 | m[j]=false; 86 | j--; 87 | } 88 | // cout<< nsize<<" " <=size) //update 90 | { 91 | if(size==nsize) // the starting point comes first in input array. 92 | { 93 | if(index[start]>index[nstart]) 94 | start=nstart; 95 | } 96 | else start =nstart; 97 | 98 | size=nsize; 99 | 100 | } 101 | // cout<< nsize<<" " < v; 104 | for( int i=0 ;i< size ;i++) 105 | v.push_back(start), start++; 106 | 107 | return v; 108 | }*/ 109 | -------------------------------------------------------------------------------- /priority queues/remove min :: min heap sort: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class PriorityQueue { 4 | vector pq; 5 | 6 | public : 7 | 8 | PriorityQueue() { 9 | 10 | } 11 | 12 | bool isEmpty() { 13 | return pq.size() == 0; 14 | } 15 | 16 | // Return the size of priorityQueue - no of elements present 17 | int getSize() { 18 | return pq.size(); 19 | } 20 | 21 | int getMin() { 22 | if(isEmpty()) { 23 | return 0; // Priority Queue is empty 24 | } 25 | return pq[0]; 26 | } 27 | 28 | void insert(int element) { 29 | pq.push_back(element); 30 | 31 | int ci = pq.size() - 1; 32 | int pi = (ci - 1) / 2; 33 | 34 | 35 | 36 | while(pi>=0 && pq[ci] < pq[pi] ) { 37 | int temp = pq[ci]; 38 | pq[ci] = pq[pi]; 39 | pq[pi] = temp; 40 | 41 | 42 | ci=pi; 43 | pi=(ci-1)/2; 44 | } 45 | 46 | 47 | 48 | 49 | } 50 | 51 | 52 | int removeMin() { 53 | // Complete this function 54 | if(pq.size()==0) 55 | return -1; 56 | int m =pq[0]; //return m in end 57 | 58 | int lastindex=pq.size()-1; 59 | 60 | int temp = pq[0]; //swap to last for CBT 61 | pq[0] = pq[lastindex]; 62 | pq[lastindex] = temp; 63 | 64 | pq.pop_back(); 65 | // delete pq[lastindex]; 66 | 67 | int i =0; 68 | while(i=pq.size()) 70 | break; 71 | 72 | else 73 | { 74 | if(2*i+2>=pq.size()) 75 | if(pq[i]>pq[2*i+1]) 76 | { int temp = pq[i]; 77 | pq[i] =pq[2*i+1]; 78 | pq[2*i+1]= temp; 79 | i=2*i+1; 80 | } 81 | else break; 82 | else 83 | { 84 | 85 | if( pq[i]> min(pq[2*i+1],pq[2*i+2])) 86 | 87 | { //storing idex of smallest children 88 | if(pq[2*i+1]>pq[2*i+2]) 89 | {int temp = pq[i]; 90 | pq[i] =pq[2*i+2]; 91 | pq[2*i+2]= temp; 92 | i=2*i+2; 93 | } 94 | 95 | else 96 | { 97 | 98 | int temp = pq[i]; 99 | pq[i] =pq[2*i+1]; 100 | pq[2*i+1]= temp; 101 | i=2*i+1; 102 | 103 | 104 | } 105 | } 106 | else break; 107 | } 108 | 109 | } 110 | } 111 | return m; 112 | } 113 | 114 | 115 | }; 116 | --------------------------------------------------------------------------------