├── BST ├── BSTClass.hpp ├── BSTfromSortedArray.cpp ├── ConstructLinkedList.cpp ├── IsBST.hpp ├── LCAofBST.hpp ├── LCAofBinaryTree.hpp ├── PairSumBinaryTree.hpp ├── ReplaceWithSumOfGreaterNodes.hpp ├── SearchInBST.cpp ├── insertDuplicateNodes.cpp ├── pathSumRootToLeafEqualK.hpp ├── printElementsInRange.hpp └── printNodesAtDistanceKfromNode.hpp ├── Binary Trees ├── Balanced.hpp ├── FindaNode.cpp ├── HeightOfBinaryTree.cpp ├── LevelOrderTraversal.hpp ├── SumOfNodes.cpp ├── ZigZagTree.cpp ├── constructTreeFronPostOrder.cpp ├── getMinAndMax.cpp ├── levelWiseLinkedList.hpp ├── mirror.cpp ├── nodeWithoutSiblings.hpp └── removeLeafNodes.hpp ├── DP1 ├── MinCostPath.cpp ├── MinCount.cpp ├── NoOfBalancedBTs.cpp ├── StaircaseDP.cpp └── minStepsTo1.cpp ├── DP2 ├── CoinTower.cpp ├── EditDistance.cpp ├── LCS.cpp ├── LIS.cpp ├── LootHouses.cpp ├── getAllWays.cpp └── knapsack.cpp ├── README.md ├── Recursion 2 ├── ReturnAllCodesString.cpp ├── checkAB.cpp ├── printAllCodesString.cpp ├── printKeypadCombinationCode.cpp ├── printPermutations.cpp ├── printSubsetsOfArray.cpp ├── printSubsetsSumToK.cpp ├── returnKeypadCode.cpp ├── returnPermutations.cpp ├── returnSubsetsOfArray.cpp └── returnSubsetsSumToK.cpp ├── Skill Tests └── Group1 │ └── Donut.cpp ├── Test3 ├── checkCousins.hpp ├── longestLeafToRootPath.hpp └── removeLeafNodesInTree.hpp ├── Tree ├── NextLarger.cpp ├── NodeWithMaximumChildSum.cpp ├── PrintLevelWise.cpp ├── SecondLargestElement.cpp ├── StructurallyIdentical.cpp ├── containsX.cpp ├── getLargestNodeCount.cpp ├── maxDataNode.cpp └── replaceWithDepth.cpp ├── TripletSum.cpp ├── graph-1 ├── 3cycle.cpp ├── BFSPath.cpp ├── CodingNinjas.cpp ├── IsConnected.cpp ├── allConnectedPaths.cpp ├── connectingDots.cpp ├── getPathBFS.cpp ├── getPathDFS.cpp ├── hasPath.cpp ├── islands.cpp └── largestPiece.cpp ├── graph-2 ├── Dijkstra.cpp ├── Kruskal.cpp └── PrimAlgo.cpp └── printElementsInRange.cpp /BST/BSTClass.hpp: -------------------------------------------------------------------------------- 1 | class BST 2 | { 3 | BinaryTreeNode *root; 4 | 5 | public: 6 | BST() 7 | { 8 | root = nullptr; 9 | } 10 | ~BST() 11 | { 12 | delete root; 13 | } 14 | 15 | private: 16 | bool search(int data, BinaryTreeNode *node) 17 | { 18 | if (node == nullptr) 19 | { 20 | return false; 21 | } 22 | if (node->data == data) 23 | { 24 | return true; 25 | } 26 | else if (data < node->data) 27 | { 28 | return search(data, node->left); 29 | } 30 | else 31 | { 32 | return search(data, node->right); 33 | } 34 | } 35 | 36 | public: 37 | bool search(int data) 38 | { 39 | return search(data, root); 40 | } 41 | 42 | private: 43 | BinaryTreeNode *insert(int data, BinaryTreeNode *node) 44 | { 45 | if (node == nullptr) 46 | { 47 | BinaryTreeNode *newNode = new BinaryTreeNode(data); 48 | return newNode; 49 | } 50 | if (data <= node->data) 51 | { 52 | node->left = insert(data, node->left); 53 | } 54 | else 55 | { 56 | node->right = insert(data, node->right); 57 | } 58 | return node; 59 | } 60 | 61 | public: 62 | void insert(int data) 63 | { 64 | root = insert(data, root); 65 | } 66 | 67 | private: 68 | BinaryTreeNode *remove(int data, BinaryTreeNode *node) 69 | { 70 | if (node == nullptr) 71 | { 72 | return nullptr; 73 | } 74 | if (node->data > data) 75 | { 76 | node->left = remove(data, node->left); 77 | return node; 78 | } 79 | else if (node->data < data) 80 | { 81 | node->right = remove(data, node->right); 82 | return node; 83 | } 84 | else 85 | { 86 | if (node->left == nullptr && node->right == nullptr) 87 | { 88 | delete node; 89 | return nullptr; 90 | } 91 | else if (node->left == nullptr) 92 | { 93 | BinaryTreeNode *temp = node->right; 94 | node->right = nullptr; 95 | delete node; 96 | return temp; 97 | } 98 | else if (node->right == nullptr) 99 | { 100 | BinaryTreeNode *temp = node->left; 101 | node->left = nullptr; 102 | delete node; 103 | return temp; 104 | } 105 | else 106 | { 107 | BinaryTreeNode *minNode = node->right; 108 | while (minNode->left != nullptr) 109 | { 110 | minNode = minNode->left; 111 | } 112 | int minData = minNode->data; 113 | node->data = minData; 114 | node->right = remove(minData, node->right); 115 | return node; 116 | } 117 | } 118 | } 119 | 120 | public: 121 | void remove(int data) 122 | { 123 | root = remove(data, root); 124 | } 125 | 126 | private: 127 | void printTree(BinaryTreeNode *node) 128 | { 129 | if (node == nullptr) 130 | { 131 | return; 132 | } 133 | cout << node->data << ":"; 134 | if (node->left != nullptr) 135 | { 136 | cout << "L:" << node->left->data << ","; 137 | } 138 | if (node->right != nullptr) 139 | { 140 | cout << "R:" << node->right->data; 141 | } 142 | cout << endl; 143 | printTree(node->left); 144 | printTree(node->right); 145 | } 146 | 147 | public: 148 | void print() 149 | { 150 | printTree(root); 151 | } 152 | }; 153 | -------------------------------------------------------------------------------- /BST/BSTfromSortedArray.cpp: -------------------------------------------------------------------------------- 1 | BinaryTreeNode *constructTree(int *arr,int si,int ei) 2 | { 3 | if(si>ei) return NULL; 4 | int mid=(ei+si)/2; 5 | BinaryTreeNode *root=new BinaryTreeNode(arr[mid]); 6 | root->left=constructTree(arr,si,mid-1); 7 | root->right=constructTree(arr,mid+1,ei); 8 | return root; 9 | } 10 | BinaryTreeNode *constructTree(int *arr,int n) 11 | { 12 | return constructTree(arr,0,n-1); 13 | } 14 | -------------------------------------------------------------------------------- /BST/ConstructLinkedList.cpp: -------------------------------------------------------------------------------- 1 | pair*,Node *> headAndTail(BinaryTreeNode *root) 2 | { 3 | pair*,Node*> p; 4 | p.first=nullptr; 5 | p.second=nullptr; 6 | if(root==nullptr) return p; 7 | Node *middle=new Node(root->data); 8 | pair*,Node*> left=headAndTail(root->left); 9 | pair*,Node*> right=headAndTail(root->right); 10 | if(left.second) left.second->next=middle; 11 | else left.first=middle; 12 | if(right.first) middle->next=right.first; 13 | else right.second=middle; 14 | p.first=left.first; 15 | p.second=right.second; 16 | return p; 17 | } 18 | Node* constructLinkedList(BinaryTreeNode* root) { 19 | return headAndTail(root).first; 20 | } 21 | -------------------------------------------------------------------------------- /BST/IsBST.hpp: -------------------------------------------------------------------------------- 1 | bool isBST(BinaryTreeNode *root) 2 | { 3 | if(root==NULL) return 1; 4 | if(root->left && root->left->data > root->data) return 0; 5 | if(root->right && root->right->data < root->data) return 0; 6 | return isBST(root->left) & isBST(root->right); //you can use '&&' operator here as well 7 | } 8 | -------------------------------------------------------------------------------- /BST/LCAofBST.hpp: -------------------------------------------------------------------------------- 1 | int getLCA(BinaryTreeNode * root , int a, int b) { 2 | if(root == NULL) return -1; 3 | int d = root->data; 4 | if(d==a || d==b) return d; 5 | int left=-1,right=-1; 6 | if(a>d && b >= d) right = getLCA(root->right,a,b); 7 | else if(a < d && b < d) left = getLCA(root->left,a,b); 8 | else{ 9 | left = getLCA(root->left,a,b); 10 | right = getLCA(root->right,a,b); 11 | } 12 | if(left != -1 && right != -1) return d; 13 | else if(left != -1) return left; 14 | return right; 15 | } 16 | -------------------------------------------------------------------------------- /BST/LCAofBinaryTree.hpp: -------------------------------------------------------------------------------- 1 | 2 | int getLCA(BinaryTreeNode * root , int a, int b) { 3 | if(root == NULL) return -1; 4 | int d = root->data; 5 | if(d==a || d==b) return d; 6 | int left = getLCA(root->left,a,b); 7 | int right = getLCA(root->right,a,b); 8 | if(left != -1 && right != -1) return d; 9 | else if(left != -1 && right == -1) return left; 10 | else if(left == -1 && right != -1) return right; 11 | else return -1; 12 | } 13 | -------------------------------------------------------------------------------- /BST/PairSumBinaryTree.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define _BTN_ BinaryTreeNode* 4 | #define vi vector 5 | 6 | vi v; 7 | void helper(_BTN_ root){ 8 | if(root){ 9 | v.push_back(root->data); 10 | helper(root->left); 11 | helper(root->right); 12 | } 13 | } 14 | void pairSum(_BTN_ root, int sum) { 15 | helper(root); 16 | sort(begin(v),end(v)); 17 | int i=0,j=v.size()-1; 18 | while(i* 3 | /* 4 | int replace(_BTN_ root,int sum){ 5 | if(!root) return sum; 6 | sum = replace(root->right,sum); 7 | sum += root->data; 8 | root->data = sum; 9 | sum = replace(root->left,sum); 10 | } 11 | 12 | void replaceWithLargerNodesSum(_BTN_ root){ 13 | replace(root,0); 14 | } 15 | */ 16 | 17 | int _sum_(_BTN_ root){ 18 | if(!root) return 0; 19 | return root->data + _sum_(root->left) + _sum_(root->right); 20 | } 21 | void replaceWithLargerNodesSum(_BTN_ root,int sum=0) { 22 | if(!root) return; 23 | int rsum = _sum_(root->right); 24 | root->data += rsum + sum; 25 | replaceWithLargerNodesSum(root->right,sum); 26 | sum = root->data; 27 | replaceWithLargerNodesSum(root->left,sum); 28 | } 29 | -------------------------------------------------------------------------------- /BST/SearchInBST.cpp: -------------------------------------------------------------------------------- 1 | bool searchInBST(BinaryTreeNode *root, int x) 2 | { 3 | if(root==NULL) return false; 4 | if(root->data == x) return true; 5 | else if(root->data > x) return searchInBST(root->left,x); 6 | else return searchInBST(root->right,x); 7 | } 8 | -------------------------------------------------------------------------------- /BST/insertDuplicateNodes.cpp: -------------------------------------------------------------------------------- 1 | void insertDuplicateNode(BinaryTreeNode *root) { 2 | if(root==nullptr) return; 3 | insertDuplicateNode(root->left); 4 | insertDuplicateNode(root->right); 5 | BinaryTreeNode *newNode=new BinaryTreeNode(root->data); 6 | BinaryTreeNode *temp=root->left; 7 | root->left=newNode; 8 | newNode->left=temp; 9 | } 10 | -------------------------------------------------------------------------------- /BST/pathSumRootToLeafEqualK.hpp: -------------------------------------------------------------------------------- 1 | #define _VI_ vector 2 | #define _BTN_ BinaryTreeNode* 3 | #define _PB_ push_back 4 | 5 | void rootToLeafPathsSumToK(_BTN_ root, int k,_VI_ path = {}) { 6 | if(!root) return; 7 | k -= root->data; 8 | path._PB_(root->data); 9 | if(!root->left && !root->right){ 10 | if(k==0){ //correct path 11 | for(auto &x:path) printf("%d ",x); 12 | printf("\n"); 13 | } 14 | path.pop_back(); 15 | return; 16 | } 17 | rootToLeafPathsSumToK(root->left,k,path); 18 | rootToLeafPathsSumToK(root->right,k,path); 19 | } 20 | -------------------------------------------------------------------------------- /BST/printElementsInRange.hpp: -------------------------------------------------------------------------------- 1 | void elementsInRangeK1K2(BinaryTreeNode* root, int k1, int k2) { 2 | if(root){ 3 | int val = root->data; 4 | if(val >=k1 && val <=k2){ 5 | elementsInRangeK1K2(root->left,k1,k2); 6 | printf("%d ",val); 7 | elementsInRangeK1K2(root->right,k1,k2); 8 | }else if(val < k1) elementsInRangeK1K2(root->right,k1,k2); 9 | else if(val > k2) elementsInRangeK1K2(root->left,k1,k2); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /BST/printNodesAtDistanceKfromNode.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a Binary Tree of type integer, a target node, and an integer value K. 3 | Print the data of all nodes that have a distance K from the target node. The order in which they would be printed will not matter. 4 | Sample Input 1: 5 | 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 6 | 3 1 7 | Sample Output 1: 8 | 9 9 | 6 10 | Sample Input 2: 11 | 1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1 12 | 3 3 13 | Sample Output 2: 14 | 4 15 | 5 16 | */ 17 | #define _BTN_ BinaryTreeNode* 18 | 19 | void printer(_BTN_ root,int k){ 20 | if(root){ 21 | if(k==0){ 22 | printf("%d\n",root->data); 23 | return; 24 | } 25 | printer(root->left,k-1); 26 | printer(root->right,k-1); 27 | } 28 | } 29 | int helper(_BTN_ root,int node,int k){ 30 | if(!root) return -1; 31 | if(root->data == node){ 32 | printer(root,k); 33 | return 0; 34 | } 35 | int leftDistance = helper(root->left,node,k); 36 | if(leftDistance != -1){ 37 | if(leftDistance + 1 == k){printf("%d\n",root->data);} else{ printer(root->right,k-leftDistance-2);}; 38 | return 1+leftDistance; 39 | } 40 | int rightDistance = helper(root->right,node,k); 41 | if(rightDistance != -1){ 42 | if(rightDistance + 1 == k){printf("%d\n",root->data);} else {printer(root->left,k-rightDistance-2);}; 43 | return 1 + rightDistance; 44 | } 45 | return -1; 46 | } 47 | 48 | void nodesAtDistanceK(_BTN_ root, int node, int k) { 49 | helper(root,node,k); 50 | } 51 | -------------------------------------------------------------------------------- /Binary Trees/Balanced.hpp: -------------------------------------------------------------------------------- 1 | #define _BTN_ BinaryTreeNode* 2 | #define _PB_ pair 3 | #define balanced second 4 | #define height first 5 | 6 | _PB_ check(_BTN_ root){ 7 | if(root == NULL) return {0,1}; 8 | _PB_ left = check(root->left); 9 | _PB_ right = check(root->right); 10 | bool flag = 1; 11 | if(!left.balanced || !right.balanced || abs(left.height - right.height) > 1) flag=0; 12 | return {max(left.height,right.height)+1,flag}; 13 | } 14 | bool isBalanced(_BTN_ root) { return check(root).balanced; } 15 | -------------------------------------------------------------------------------- /Binary Trees/FindaNode.cpp: -------------------------------------------------------------------------------- 1 | bool isNodePresent(BinaryTreeNode *root,int x) 2 | { 3 | if(root==nullptr) return false; 4 | if(root->data == x) return true; 5 | return isNodePresent(root->left,x)||isNodePresent(root->right,x); 6 | } 7 | -------------------------------------------------------------------------------- /Binary Trees/HeightOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | int height(BinaryTreeNode *root) 2 | { 3 | if(root==nullptr) return 0; 4 | int leftHeight=height(root->left); 5 | int rightHeight=height(root->right); 6 | return max(leftHeight,rightHeight)+1; 7 | } 8 | -------------------------------------------------------------------------------- /Binary Trees/LevelOrderTraversal.hpp: -------------------------------------------------------------------------------- 1 | #define _BTN_ BinaryTreeNode* 2 | 3 | void printLevelWise(_BTN_ root) { 4 | if(root == NULL) return; 5 | queue<_BTN_> q; 6 | q.push(root); 7 | q.push(NULL); 8 | while(!q.empty()){ 9 | auto front = q.front(); 10 | q.pop(); 11 | if(front==NULL){ 12 | if(q.empty()) break; 13 | printf("\n"); 14 | q.push(NULL); 15 | continue; 16 | } 17 | printf("%d ",front->data); 18 | if(front->left) q.push(front->left); 19 | if(front->right) q.push(front->right); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Binary Trees/SumOfNodes.cpp: -------------------------------------------------------------------------------- 1 | int getSum(BinaryTreeNode* root) { 2 | if(root==nullptr) return 0; 3 | return root->data+getSum(root->left)+getSum(root->right); 4 | } 5 | -------------------------------------------------------------------------------- /Binary Trees/ZigZagTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | void zigZagOrder(BinaryTreeNode *root) 3 | { 4 | 5 | stack *> stRtoL; 6 | stack *> stLtoR; 7 | stRtoL.push(root); 8 | while (!(stRtoL.empty() && stLtoR.empty())) 9 | { 10 | 11 | while (!stRtoL.empty()) 12 | { 13 | BinaryTreeNode *front = stRtoL.top(); 14 | stRtoL.pop(); 15 | cout << front->data << " "; 16 | if (front->left != nullptr) 17 | { 18 | stLtoR.push(front->left); 19 | } 20 | if (front->right != nullptr) 21 | { 22 | stLtoR.push(front->right); 23 | } 24 | } 25 | cout << endl; 26 | while (!stLtoR.empty()) 27 | { 28 | BinaryTreeNode *top = stLtoR.top(); 29 | stLtoR.pop(); 30 | cout << top->data << " "; 31 | if (top->right != nullptr) 32 | { 33 | stRtoL.push(top->right); 34 | } 35 | if (top->left != nullptr) 36 | { 37 | stRtoL.push(top->left); 38 | } 39 | } 40 | cout << endl; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Binary Trees/constructTreeFronPostOrder.cpp: -------------------------------------------------------------------------------- 1 | BinaryTreeNode* binaryTreeHelper(int *postOrder,int *inOrder,int poS,int poE,int inS,int inE) 2 | { 3 | if(poS>poE || inS > inE) 4 | { 5 | return nullptr; 6 | } 7 | int rootData=postOrder[poE]; 8 | int rootIndex=-1; 9 | for(int i=inS;i<=inE;i++) 10 | { 11 | if(inOrder[i]==rootData) 12 | { 13 | rootIndex=i; 14 | break; 15 | } 16 | } 17 | int leftInS=inS; 18 | int leftInE=rootIndex-1; 19 | int leftPoS=poS; 20 | int leftPoE=poS+rootIndex-inS-1; 21 | int rightInS=rootIndex+1; 22 | int rightInE=inE; 23 | int rightPoS=leftPoE+1; 24 | int rightPoE=poE-1; 25 | BinaryTreeNode *root=new BinaryTreeNode(rootData); 26 | root->left=binaryTreeHelper(postOrder,inOrder,leftPoS,leftPoE,leftInS,leftInE); 27 | root->right=binaryTreeHelper(postOrder,inOrder,rightPoS,rightPoE,rightInS,rightInE); 28 | return root; 29 | 30 | } 31 | BinaryTreeNode* buildTree(int *postorder, int postLength, int *inorder, int inLength) { 32 | // Write your code here 33 | return binaryTreeHelper(postorder,inorder,0,postLength-1,0,inLength-1); 34 | } 35 | -------------------------------------------------------------------------------- /Binary Trees/getMinAndMax.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define _PI_ pair 5 | #define _MIN_ first 6 | #define _MAX_ second 7 | 8 | _PI_ getMinAndMax(BinaryTreeNode *root) { 9 | if(root == NULL) return {INT_MAX,INT_MIN}; 10 | _PI_ ans = {root->data,root->data}; 11 | _PI_ left = getMinAndMax(root->left); 12 | _PI_ right = getMinAndMax(root->right); 13 | ans._MIN_ = min({ans._MIN_,left._MIN_,right._MIN_}); 14 | ans._MAX_ = max({ans._MAX_,left._MAX_,right._MAX_}); 15 | return ans; 16 | } 17 | -------------------------------------------------------------------------------- /Binary Trees/levelWiseLinkedList.hpp: -------------------------------------------------------------------------------- 1 | #define _NODE_ Node 2 | #define _V_(T) vector 3 | #define _BTN_ BinaryTreeNode* 4 | 5 | _V_(_NODE_*) constructLinkedListForEachLevel(_BTN_ root){ 6 | if(root == NULL) return {}; 7 | queue<_BTN_> q; 8 | q.push(root); 9 | q.push(NULL); 10 | _NODE_ *head = NULL,*tail=NULL; 11 | _V_(_NODE_*) ans; 12 | while(!q.empty()){ 13 | auto front = q.front(); 14 | q.pop(); 15 | if(front == NULL){ 16 | ans.push_back(head); 17 | head = NULL; 18 | tail = NULL; 19 | if(q.empty()) break; 20 | q.push(NULL); 21 | continue; 22 | } 23 | if(front->left) q.push(front->left); 24 | if(front->right) q.push(front->right); 25 | _NODE_ *newNode = new _NODE_(front->data); 26 | if(head){ 27 | tail->next = newNode; 28 | tail = newNode; 29 | }else{ 30 | head = newNode; 31 | tail = newNode; 32 | } 33 | } 34 | return ans; 35 | } 36 | -------------------------------------------------------------------------------- /Binary Trees/mirror.cpp: -------------------------------------------------------------------------------- 1 | #define BTN BinaryTreeNode* 2 | void swap(BTN root){ 3 | if(root->left && root->right){ 4 | BTN temp = root->left; 5 | root->left = root->right; 6 | root->right = temp; 7 | } 8 | } 9 | void mirrorBinaryTree(BTN root) { 10 | if(root == NULL) return; 11 | swap(root); 12 | mirrorBinaryTree(root->left); 13 | mirrorBinaryTree(root->right); 14 | } 15 | -------------------------------------------------------------------------------- /Binary Trees/nodeWithoutSiblings.hpp: -------------------------------------------------------------------------------- 1 | void printNodesWithoutSibling(BinaryTreeNode *root) { 2 | if(root == NULL) return; 3 | if(root->left && !root->right) printf("%d ",root->left->data); 4 | if(root->right && !root->left) printf("%d ",root->right->data); 5 | printNodesWithoutSibling(root->left); 6 | printNodesWithoutSibling(root->right); 7 | } 8 | -------------------------------------------------------------------------------- /Binary Trees/removeLeafNodes.hpp: -------------------------------------------------------------------------------- 1 | #define _BTN_ BinaryTreeNode* 2 | 3 | _BTN_ removeLeafNodes(_BTN_ root) { 4 | if(root == NULL) return root; 5 | if(root->left == NULL && root->right == NULL) return NULL; 6 | root->left = removeLeafNodes(root->left); 7 | root->right = removeLeafNodes(root->right); 8 | return root; 9 | } 10 | -------------------------------------------------------------------------------- /DP1/MinCostPath.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: Ankit Bhankharia 3 | **/ 4 | #include 5 | using namespace std; 6 | //tabulation method(DP) 7 | int minCostPathDP(int **arr,int n,int m){ 8 | int **dp=new int*[n]; 9 | for(int i=0;i=0;j--){ //j denotes col 17 | dp[n-1][j]=dp[n-1][j+1]+arr[n-1][j]; 18 | } 19 | //filling last col (bottom to top) 20 | for(int i=n-2;i>=0;i--){ //i denotes row 21 | dp[i][m-1]=dp[i+1][m-1]+arr[i][m-1]; 22 | } 23 | /************************************************/ 24 | //filling remaining cells 25 | for(int i=n-2;i>=0;i--){ 26 | for(int j=m-2;j>=0;j--){ 27 | dp[i][j]=arr[i][j]+min({dp[i+1][j],dp[i][j+1],dp[i+1][j+1]}); 28 | } 29 | } 30 | return dp[0][0]; 31 | } 32 | //memorisation method 33 | int minCostPathMem(int **arr,int i,int j,int n,int m,int **dp){ 34 | if(i==n-1 && j==m-1){ 35 | return arr[i][j]; 36 | } 37 | if(i>=n || j>=m-1){ 38 | return __INT_MAX__; 39 | } 40 | if(dp[i][j]!=-1){ //check if ans already exist 41 | return dp[i][j]; 42 | } 43 | int x=minCostPathMem(arr,i+1,j,n,m,dp); 44 | int z=minCostPathMem(arr,i+1,j+1,n,m,dp); 45 | int y=minCostPathMem(arr,i,j+1,n,m,dp); 46 | dp[i][j]=arr[i][j]+min({x,y,z}); //saving small ans 47 | return dp[i][j]; //returning small ans 48 | } 49 | int minCostPathMem(int **arr,int n,int m){ 50 | int **dp=new int*[n+1]; 51 | for(int i=0;i=n || j>=m) return __INT_MAX__; 65 | int x=minCostPath(a,i+1,j,n,m); 66 | int y=minCostPath(a,i,j+1,n,m); 67 | int z=minCostPath(a,i+1,j+1,n,m); 68 | return a[i][j]+min({x,y,z}); 69 | } 70 | int main(){ 71 | int row,col; 72 | cin>>row>>col; 73 | int **a=new int*[row]; 74 | for(int i=0;i>a[i][j]; 80 | } 81 | } 82 | //cout< 2 | using namespace std; 3 | //tabulate method(DP) 4 | int minCountDP(int n){ 5 | int dp[n+1]; 6 | dp[0]=0; 7 | dp[1]=1; 8 | for(int i=2;i<=n;i++){ 9 | dp[i]=__INT_MAX__; 10 | for(int j=0;j*j<=i;j++){ 11 | dp[i]=min(dp[i],dp[i-(j*j)]); 12 | } 13 | dp[i]++; 14 | } 15 | return dp[n]; 16 | } 17 | //memorisation method 18 | int minCount(int n,int *dp){ //helper function 19 | if(n<=1) return n; 20 | if(dp[n]!=-1) return dp[n]; //check if small ans id already calculated 21 | int ans=__INT_MAX__; 22 | for(int i=1;i*i<=n;i++){ 23 | ans=min(ans,minCount(n-(i*i),dp)); 24 | } 25 | dp[n]=ans+1; //saving the small ans 26 | return dp[n]; //return the ans 27 | } 28 | int minCountMem(int n){ 29 | int dp[n+1]; 30 | memset(dp,-1,sizeof(dp)); 31 | return minCount(n,dp); 32 | } 33 | //recursive Method 34 | int minCountRec(int n){ 35 | if(n<=1) return n; 36 | int ans=INT_MAX; 37 | for(int i=1;i*i<=n;i++){ 38 | ans=min(ans,minCountRec(n-(i*i))); 39 | } 40 | return ans+1; 41 | } 42 | //sample input= 12 43 | //sample output = 3 44 | int main(){ 45 | int n; 46 | cin>>n; 47 | cout< 5 | using namespace std; 6 | int mod=1e9+7; 7 | //tabulate method(dp) 8 | int balancedBTsDP(int n){ 9 | int dp[n+1]; 10 | dp[0]=1; 11 | dp[1]=1; 12 | for(int i=2;i<=n;i++){ 13 | dp[i]=(dp[i-1]*dp[i-1])+(2*dp[i-1]*dp[i-2]); //take care of integer overflow 14 | } 15 | return dp[n]; 16 | } 17 | //memorisation 18 | int balancedBTsMem(int n,int *dp){ 19 | if(n<=1) return 1; 20 | if(dp[n]!=-1) return dp[n]; 21 | int x=balancedBTsMem(n-1,dp); 22 | int y=balancedBTsMem(n-2,dp); 23 | int temp1=(int)(((long)(x)*x)%mod); 24 | int temp2=(int)((2*(long)(x)*y)%mod); 25 | int ans=(temp1+temp2)%mod; 26 | dp[n]=ans; 27 | return ans; 28 | } 29 | int balancedBTsMem(int n){ 30 | int dp[n+1]; 31 | memset(dp,-1,sizeof(dp)); 32 | return balancedBTsMem(n,dp); 33 | } 34 | //recursion 35 | int balancedBTs(int n) { 36 | if(n<=1) return 1; 37 | int x=balancedBTs(n-1); 38 | int y=balancedBTs(n-2); 39 | int temp1=(int)(((long)(x)*x)%mod); 40 | int temp2=(int)((2*(long)(x)*y)%mod); 41 | int ans=(temp1+temp2)%mod; 42 | return ans; 43 | } 44 | 45 | int main(){ 46 | int h; 47 | cin>>h; 48 | cout< 2 | using namespace std; 3 | //tabulation method 4 | long staircaseDP(long n){ 5 | long dp[n+1]; 6 | dp[0]=1; 7 | dp[1]=1; 8 | dp[2]=2; 9 | for(int i=3;i<=n;i++){ 10 | dp[i]=dp[i-1]+dp[i-2]+dp[i-3]; 11 | } 12 | return dp[n]; 13 | } 14 | 15 | //memorisation method 16 | long staircaseMem(long n,long *dp){ 17 | if(n<=1) return 1; 18 | else if(n==2) return 2; 19 | if(dp[n]!=-1) return dp[n]; //if small ans already exist 20 | long ans1=staircaseMem(n-1,dp); 21 | long ans2=staircaseMem(n-2,dp); 22 | long ans3=staircaseMem(n-3,dp); 23 | dp[n]=ans1+ans2+ans3; //save the small ans 24 | return dp[n]; //return small ans 25 | } 26 | long staircaseMem(long n){ 27 | long dp[n+1]; 28 | memset(dp,-1,sizeof(dp)); 29 | return staircaseMem(n,dp); 30 | } 31 | 32 | //recursion method 33 | long staircaseRec(long n){ 34 | if(n<=1) return 1; 35 | else if(n==2) return 2; 36 | long ans1=staircaseRec(n-1); 37 | long ans2=staircaseRec(n-2); 38 | long ans3=staircaseRec(n-3); 39 | return ans1+ans2+ans3; 40 | } 41 | 42 | int main(){ 43 | long n; 44 | cin>>n; 45 | cout< 2 | using namespace std; 3 | //tabulate method(DP) 4 | int minStepsTo1DP(int n){ 5 | int dp[n+1]; 6 | dp[0]=0; //only dp[1] is enough 7 | dp[1]=0; 8 | for(int i=2;i<=n;i++){ 9 | int x=dp[i-1]; 10 | int y=__INT_MAX__,z=__INT_MAX__; 11 | if(i&1==0) y=dp[i>>1]; //change bitwise operators to operational operators for all test cases to pass 12 | if(i%3==0) z=dp[i/3]; 13 | dp[i]=1+min({x,y,z}); 14 | } 15 | return dp[n]; 16 | } 17 | 18 | //memorisation method (DP) 19 | int minStepTo1Mem(int n,int *dp){ 20 | if(n<=1) return 0; 21 | if(dp[n]!=-1) return dp[n]; //ans already exist 22 | int x=minStepTo1Mem(n-1,dp); 23 | int y=__INT_MAX__,z=__INT_MAX__; 24 | if(n&1 == 0) y=minStepTo1Mem(n>>1,dp); 25 | if(n%3==0) z=minStepTo1Mem(n/3,dp); 26 | dp[n]=1+min({x,y,z}); 27 | return dp[n]; 28 | } 29 | int minStepTo1Mem(int n){ 30 | int dp[n+1]; 31 | memset(dp,-1,sizeof(dp)); 32 | return minStepTo1Mem(n,dp); 33 | } 34 | //recursion method(Brute Force) 35 | int minStepTo1Rec(int n){ 36 | if(n<=1) return 0; //base case 37 | int x=minStepTo1Rec(n-1); 38 | int y=__INT_MAX__,z=__INT_MAX__; 39 | if(n&1 == 0) y=minStepTo1Rec(n>>1); 40 | if(n%3==0) z=minStepTo1Rec(n/3); 41 | return 1+min(x,min(y,z)); 42 | } 43 | 44 | int main(){ 45 | int n; 46 | cin>>n; 47 | cout< 2 | using namespace std; 3 | string findWinner(int n,int x,int y){ 4 | if(x>y) swap(x,y); 5 | bool dp[n+1]; 6 | for(int i=1;i<=n;i++){ 7 | if(i==1||i==x||i==y) dp[i]=true; 8 | else if(i>x>>y>>z; 18 | cout< 5 | using namespace std; 6 | //tabulation method 7 | int editDistanceDP(string s,string t){ 8 | int m=s.size(); 9 | int n=t.size(); 10 | int **dp=new int*[m+1]; 11 | for(int i=0;i<=m;i++) dp[i]=new int[n+1]; 12 | for(int j=0;j<=n;j++) dp[0][j]=j; //fill 1st row 13 | for(int i=0;i<=m;i++) dp[i][0]=i; //fill 1st col 14 | for(int i=1;i<=m;i++){ 15 | for(int j=1;j<=n;j++){ 16 | if(s[m-i]==t[n-j]) dp[i][j]= dp[i-1][j-1]; //check if 1st element matches 17 | else dp[i][j]=1+min({dp[i-1][j-1],dp[i][j-1],dp[i-1][j]}); 18 | } 19 | } 20 | return dp[m][n]; 21 | } 22 | //memorisation method 23 | int editDistanceMem(string s, string t,int **dp){ 24 | int m=s.size(); 25 | int n=t.size(); 26 | if(n==0 || m==0) return max(n,m); //base case 27 | if(dp[m][n]!=-1) return dp[m][n]; //check if ans already exist or not 28 | if(s[0]==t[0]) return editDistanceMem(s.substr(1),t.substr(1),dp); 29 | int a=editDistanceMem(s.substr(1),t,dp); //insert cost 30 | int b=editDistanceMem(s,t.substr(1),dp); //remove cost 31 | int c=editDistanceMem(s.substr(1),t.substr(1),dp);//replace cost 32 | dp[m][n]=1+min({a,b,c}); 33 | return dp[m][n]; 34 | } 35 | int editDistanceMem(string s,string t){ 36 | int **dp=new int*[s.size()+1]; 37 | for(int i=0;i<=s.size();i++){ 38 | dp[i]=new int[t.size()+1]; 39 | for(int j=0;j<=t.size();j++){ 40 | dp[i][j]=-1; 41 | } 42 | } 43 | return editDistanceMem(s,t,dp); 44 | } 45 | //recursion 46 | int editDistanceRec(string s,string t){ 47 | if(s.size()==0 || t.size()==0) return max(s.size(),t.size()); 48 | if(s[0]==t[0]) return editDistanceRec(s.substr(1),t.substr(1)); 49 | int a=editDistanceRec(s.substr(1),t); //insert cost 50 | int b=editDistanceRec(s,t.substr(1)); //remove cost 51 | int c=editDistanceRec(s.substr(1),t.substr(1));//replace cost 52 | return 1+min({a,b,c}); 53 | } 54 | int main(){ 55 | string s,t; 56 | cin>>s>>t; 57 | cout< 5 | using namespace std; 6 | //tabulate method (DP) 7 | int lcsDP(string s,string t){ 8 | int m=s.size(),n=t.size(); 9 | int **dp=new int*[m+1]; 10 | for(int i=0;i<=m;i++) dp[i]=new int[n+1]; //create output array 11 | for(int j=0;j<=n;j++) dp[0][j]=0; //fill first row 12 | for(int i=0;i<=m;i++) dp[i][0]=0; //fill first col 13 | for(int i=1;i<=m;i++){ 14 | for(int j=1;j<=n;j++){ 15 | //check if first matches 16 | if(s[m-i]==t[n-j]) dp[i][j]=1+dp[i-1][j-1]; 17 | else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 18 | } 19 | } 20 | return dp[m][n]; 21 | } 22 | //memorisation 23 | int lcsMem(string s,string t,int **dp){ 24 | if(s.size()==0 || t.size()==0) return 0; 25 | //check if ans already exist 26 | if(dp[s.size()][t.size()]!=-1) return dp[s.size()][t.size()]; 27 | int ans; 28 | if(s[0]==t[0]){ 29 | ans=1+lcsMem(s.substr(1),t.substr(1),dp); 30 | } 31 | else{ 32 | int a=lcsMem(s.substr(1),t,dp); 33 | int b=lcsMem(s,t.substr(1),dp); 34 | ans= max(a,b); 35 | } 36 | dp[s.size()][t.size()]=ans; //saving ans 37 | return ans; //return answer 38 | } 39 | int lcsMem(string s,string t){ 40 | int **dp=new int*[s.size()+1]; 41 | for(int i=0;i<=s.size();i++){ 42 | dp[i]=new int[t.size()+1]; 43 | for(int j=0;j<=t.size();j++){ 44 | dp[i][j]=-1; 45 | } 46 | } 47 | return lcsMem(s,t,dp); 48 | } 49 | //recursion 50 | int LCSRec(string s,string t){ 51 | if(s.size() == 0 || t.size()==0) return 0; //base case 52 | //recursive calls 53 | if(s[0]==t[0]) return 1+LCSRec(s.substr(1),t.substr(1)); 54 | else{ 55 | int a=LCSRec(s.substr(1),t); 56 | int b=LCSRec(s,t.substr(1)); 57 | return max(a,b); 58 | } 59 | } 60 | int main(){ 61 | string s,t; 62 | cin>>s>>t; 63 | cout< 2 | using namespace std; 3 | //tabualate method 4 | int longestIncreasingSubsequenceDP(int *arr,int n){ 5 | int dp[n]; 6 | dp[0]=1; 7 | for(int i=1;i=0;j--){ 10 | if(arr[i]>arr[j]){ 11 | if(dp[j]+1 > dp[i]){ 12 | dp[i]=dp[j]+1; 13 | } 14 | } 15 | } 16 | } 17 | int best=0; 18 | for(int i=0;i>n; 27 | int a[n]; 28 | for(int i=0;i>a[i]; 29 | cout< 5 | using namespace std; 6 | //tabulation method 7 | int maxMoneyLootedDP(int *arr,int n){ 8 | int dp[n]; 9 | dp[0]=arr[0]; //initialize dp 10 | dp[1]=max(arr[1],dp[0]); 11 | for(int i=2;i>n; 31 | int a[n]; 32 | for(int i=0;i>a[i]; 33 | cout< 2 | using namespace std; 3 | int getAllWays(int a,int b,int num) 4 | { 5 | int val=x-pow(num,b); 6 | if(val==0) return 1; 7 | else if(val < 0) return 0; 8 | return getAllWays(val,b,num+1)+getAllWays(a,b,num+1); 9 | } 10 | int getAllWays(int a,int b){ 11 | return getAllWays(a,b,1); 12 | } 13 | int main(){ 14 | int a,b; 15 | cin>>a>>b; 16 | cout< 5 | using namespace std; 6 | //tabulation method (DP) 7 | int knapsackDP(int *weights,int *val,int n,int w){ 8 | int dp[n+1][w+1]; 9 | for(int j=0;j<=w;j++) dp[0][j]=0; //fill 1st row 10 | for(int i=0;i<=n;i++) dp[i][0]=0; //fill 1st col 11 | for(int i=1;i<=n;i++){ 12 | for(int j=1;j<=w;j++){ 13 | if(weights[i-1]>j) dp[i][j]=dp[i-1][j]; 14 | else dp[i][j]=max(val[i-1]+dp[i-1][j-weights[i-1]],dp[i-1][j]); 15 | } 16 | } 17 | return dp[n][w]; 18 | } 19 | //memoization 20 | int knapsackMem(int *weights, int *val, int n, int w, int **dp) 21 | { 22 | if (n == 0 || w == 0) return 0; 23 | if(dp[n][w]!=-1) return dp[n][w]; 24 | int ans; 25 | if (weights[0] > w) 26 | ans = knapsackMem(weights + 1, val + 1, n - 1, w, dp); 27 | else{ 28 | int x = knapsackMem(weights + 1, val + 1, n - 1, w, dp); 29 | int y = knapsackMem(weights + 1, val + 1, n - 1, w - weights[0], dp) + val[0]; 30 | ans = max(x, y); 31 | } 32 | dp[n][w]=ans; 33 | return ans; 34 | } 35 | int knapsackMem(int *weights, int *val, int n, int m) 36 | { 37 | int **dp=new int*[n+1]; 38 | for(int i=0;i<=n;i++){ 39 | dp[i]=new int[m+1]; 40 | for(int j=0;j<=m;j++){ 41 | dp[i][j]=-1; 42 | } 43 | } 44 | return knapsackMem(weights, val, n, m, dp); 45 | } 46 | //recursive 47 | int knapsackRec(int *weights, int *val, int n, int w) 48 | { 49 | if (n == 0 || w == 0) 50 | return 0; 51 | if (weights[0] > w) return knapsackRec(weights + 1, val + 1, n - 1, w); 52 | int x = knapsackRec(weights + 1, val + 1, n - 1, w); 53 | int y = knapsackRec(weights + 1, val + 1, n - 1, w - weights[0]) + val[0]; 54 | return max(x, y); 55 | } 56 | 57 | int main() 58 | { 59 | int n; 60 | cin >> n; 61 | int weights[n]; 62 | for (int i = 0; i < n; i++) cin >> weights[i]; 63 | int val[n]; 64 | for (int i = 0; i < n; i++) cin >> val[i]; 65 | int w; 66 | cin >> w; 67 | cout << knapsackRec(weights, val, n, w) << "\n"; 68 | cout << knapsackMem(weights, val, n, w) << "\n"; 69 | cout< 2 | using namespace std; 3 | int atoi(char a) 4 | { 5 | int i=a-'0'; 6 | return i; 7 | } 8 | char itoa(int i) 9 | { 10 | char c='a'+i-1; 11 | return c; 12 | } 13 | int getCodes(string input, string output[10000]) { 14 | if(input.size()==0) 15 | { 16 | output[0]=""; 17 | return 1; 18 | } 19 | if(input.size()==1) 20 | { 21 | output[0]=itoa(atoi(input[0])); 22 | return 1; 23 | } 24 | string result1[10000],result2[10000]; 25 | int size2=0; 26 | 27 | int size1=getCodes(input.substr(1),result1); 28 | if(input.size()>1) 29 | { 30 | if(atoi(input[0])*10+atoi(input[1])>=10&&atoi(input[0])*10+atoi(input[1])<27) 31 | { 32 | size2=getCodes(input.substr(2),result2); 33 | } 34 | 35 | } 36 | int k=0; 37 | for(int i=0;i 2 | using namespace std; 3 | char hashmap[]={'\0','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; 4 | 5 | void print(string input, string output){ 6 | if(input.empty()){ 7 | cout<=i && tem<=27){ 16 | print(input.substr(i),output+hashmap[tem]); 17 | } 18 | } 19 | 20 | } 21 | 22 | void printAllPossibleCodes(string input) { 23 | print(input,""); 24 | } 25 | -------------------------------------------------------------------------------- /Recursion 2/printKeypadCombinationCode.cpp: -------------------------------------------------------------------------------- 1 | void printKeypad(int num,string output) 2 | { 3 | 4 | if(num==0) 5 | { 6 | cout< 3 | void printSubsetsOfArray(int arr[],int n) 4 | { 5 | int count=pow(2,n); 6 | for(int i=0;i 2 | using namespace std; 3 | int returnPermutations(string input, string output[]){ 4 | if(input.empty()){ 5 | output[0]=""; 6 | return 1; 7 | } 8 | int len = input.length(); 9 | // int ans; 10 | int k=0; 11 | string newout[10000]; 12 | for(int i=0;i 5 | 6 | using namespace std; 7 | 8 | typedef long long ll; 9 | typedef long double ld; 10 | typedef complex cd; 11 | 12 | typedef pair pi; 13 | typedef pair pl; 14 | typedef pair pd; 15 | 16 | typedef vector vi; 17 | typedef vector vd; 18 | typedef vector vl; 19 | typedef vector vpi; 20 | typedef vector vpl; 21 | typedef vector vcd; 22 | 23 | template using pq = priority_queue; 24 | template using pqg = priority_queue, greater>; 25 | 26 | #define FOR(i, a, b) for (int i=a; i<(b); i++) 27 | #define F0R(i, a) for (int i=0; i<(a); i++) 28 | #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) 29 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 30 | #define trav(a,x) for (auto& a : x) 31 | #define uid(a, b) uniform_int_distribution(a, b)(rng) 32 | 33 | #define sz(x) (int)(x).size() 34 | #define mp make_pair 35 | #define pb push_back 36 | #define ff first 37 | #define ss second 38 | #define lb lower_bound 39 | #define ub upper_bound 40 | #define all(x) x.begin(), x.end() 41 | #define ins insert 42 | #define nl '\n' 43 | template bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; } 44 | template bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; } 45 | const int MOD = 1e9+7; 46 | const int N = 1e5+2; 47 | void ankit(){ 48 | int n; 49 | cin>>n; 50 | vi v(n); 51 | trav(x,v) cin>>x; 52 | sort(all(v)); 53 | int x = n/4; 54 | int idx = n-3; 55 | int ans=0; 56 | F0R(i,x){ 57 | ans += (v[idx]); 58 | idx -= 3; 59 | } 60 | cout<sync_with_stdio(0); 64 | cin.exceptions(cin.failbit); 65 | int t=1; 66 | //test 67 | cin>>t; 68 | while(t--){ 69 | ankit(); 70 | } 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /Test3/checkCousins.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given the binary Tree and two nodes say ‘p’ and ‘q’. Determine whether the two nodes are cousins of each other or not. 4 | Two nodes are said to be cousins of each other if they are at same level of the Binary Tree and have different parents. 5 | 6 | (Do it in O(n)). 7 | Sample Input : 8 | 5 6 10 2 3 4 -1 -1 -1 -1 9 -1 -1 -1 -1 9 | 2 10 | 4 11 | 12 | Sample Output : 13 | true 14 | 15 | */ 16 | 17 | #define _VI_ vector 18 | #define _BTN_ BinaryTreeNode* 19 | 20 | const int N = 1e5+5; 21 | 22 | _VI_ v(N,-1); 23 | bool isSiblingAndHelper(_BTN_ root,int level,int p,int q){ 24 | if(root == NULL) return 0; 25 | if(root->left && root->left->data == p && root->right && root->right->data == q) return 1; 26 | if(root->left && root->left->data == q && root->right && root->right->data == p) return 1; 27 | v[root->data]=level; 28 | return isSiblingAndHelper(root->left,level+1,p,q) || isSiblingAndHelper(root->right,level+1,p,q); 29 | } 30 | 31 | bool isCousin(_BTN_ root, int p, int q) { 32 | if(root == NULL) return 0; 33 | if(root->data == p || root->data == q) return 0; 34 | if(!isSiblingAndHelper(root,0,p,q)) return v[p]==v[q]; 35 | else return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Test3/longestLeafToRootPath.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 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. 4 | 5 | Sample Input 1 : 6 | 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 7 | 8 | Sample Output 1 : 9 | 9 10 | 3 11 | 6 12 | 5 13 | 14 | */ 15 | 16 | #define _BTN_ BinaryTreeNode* 17 | #define _V_ vector 18 | #define pb push_back 19 | 20 | _V_* longestPath(_BTN_ root) { 21 | if(root == NULL) return NULL; 22 | if(!root->left && !root->right){ 23 | _V_ *ans = new _V_(); 24 | ans->pb(root->data); 25 | return ans; 26 | } 27 | _V_ *left = longestPath(root->left); 28 | _V_ *right = longestPath(root->right); 29 | if(!left){ 30 | right->pb(root->data); 31 | return right; 32 | } 33 | else if(!right){ 34 | left->pb(root->data); 35 | return left; 36 | }else{ 37 | if(left->size() > right->size()){ 38 | left->pb(root->data); 39 | delete right; 40 | return left; 41 | }else{ 42 | right->pb(root->data); 43 | delete left; 44 | return right; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Test3/removeLeafNodesInTree.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Remove all leaf nodes from a given generic Tree. Leaf nodes are those nodes, which don't have any children. 4 | Note : 5 | Root will also be a leaf node if it doesn't have any child. You don't need to print the tree, just remove all leaf nodes and return the updated root. 6 | 7 | Sample Input 1 : 8 | 10 3 20 30 40 2 40 50 0 0 0 0 9 | 10 | Sample Output 1 : (Level wise, each level in new line) 11 | 10 12 | 20 13 | 14 | */ 15 | 16 | #define tn TreeNode* 17 | 18 | tn removeLeafNodes(tn root){ 19 | if(root == NULL || root->numChildren()==0) return NULL; 20 | for(int i=0;inumChildren();i++){ 21 | tn child = root->getChild(i); 22 | if(child->numChildren()==0){ 23 | root->removeChild(i); 24 | i--; 25 | } 26 | } 27 | for(int i=0;inumChildren();i++){ 28 | tn temp = removeLeafNodes(root->getChild(i)); 29 | if(temp == NULL) root->removeChild(i); 30 | } 31 | return root; 32 | } 33 | -------------------------------------------------------------------------------- /Tree/NextLarger.cpp: -------------------------------------------------------------------------------- 1 | TreeNode* getNextLargerElement(TreeNode* root, int x) { 2 | if(root == NULL) return root; 3 | TreeNode *ans = NULL; 4 | if(root->data > x) ans = root; 5 | for(auto &node:root->children){ 6 | TreeNode *temp = getNextLargerElement(node,x); 7 | if(ans == NULL) ans = temp; 8 | else if(temp != NULL && temp->data < ans->data) ans = temp; 9 | } 10 | return ans; 11 | } 12 | -------------------------------------------------------------------------------- /Tree/NodeWithMaximumChildSum.cpp: -------------------------------------------------------------------------------- 1 | int sum(TreeNode *root){ 2 | if(root == NULL) return 0; 3 | int ans = root->data; 4 | for(auto &node:root->children) ans += node->data; 5 | return ans; 6 | } 7 | TreeNode* maxSumNode(TreeNode* root) { 8 | if(root == NULL) return root; 9 | int s = sum(root); 10 | TreeNode *ans = root; 11 | for(auto &node:root->children){ 12 | TreeNode *temp = maxSumNode(node); 13 | int tempS = sum(temp); 14 | if(tempS > s){ 15 | s = tempS; 16 | ans = temp; 17 | } 18 | } 19 | return ans; 20 | } 21 | -------------------------------------------------------------------------------- /Tree/PrintLevelWise.cpp: -------------------------------------------------------------------------------- 1 | void printLevelWise(TreeNode *root) 2 | { 3 | queue*> child; 4 | child.push(root); 5 | while(!child.empty()) 6 | { 7 | TreeNode* front=child.front(); 8 | child.pop(); 9 | cout<data<<":"; 10 | for(int i=0;ichildren.size();i++) 11 | { 12 | TreeNode *childo=front->children[i]; 13 | cout<data; 14 | if(i!=front->children.size()-1) 15 | { 16 | cout<<','; 17 | } 18 | child.push(childo); 19 | } 20 | cout<*,TreeNode*> 2 | #define ss second 3 | #define ff first 4 | 5 | pt *largest(TreeNode *root){ 6 | if(root == NULL) return new pt({NULL,NULL}); 7 | pt *ans = new pt({root,NULL}); 8 | for(auto &node:root->children){ 9 | pt *sub = largest(node); 10 | if(sub->ff->data > ans->ff->data){ 11 | if(sub->ss == NULL){ 12 | ans->ss = ans->ff; 13 | ans->ff = sub->ff; 14 | }else{ 15 | if(sub->ss->data > ans->ff->data){ 16 | ans->ss = sub->ss; 17 | ans->ff = sub->ff; 18 | }else{ 19 | ans->ss = ans->ff; 20 | ans->ff = sub->ff; 21 | } 22 | } 23 | }else if(ans->ff->data != sub->ff->data && (ans->ss == NULL || sub->ff->data > ans->ss->data)) ans->ss = sub->ff; 24 | } 25 | return ans; 26 | } 27 | TreeNode* getSecondLargestNode(TreeNode* root) { 28 | return largest(root)->ss; 29 | } 30 | -------------------------------------------------------------------------------- /Tree/StructurallyIdentical.cpp: -------------------------------------------------------------------------------- 1 | bool areIdentical(TreeNode *root1, TreeNode * root2) { 2 | if(root1 == NULL && root2 != NULL) return false; 3 | if(root1 != NULL && root2 == NULL) return false; 4 | if(root1 == NULL && root2 == NULL) return 1; 5 | if(root1->data != root2->data) return 0; 6 | if(root1->children.size() != root2->children.size()) return 0; 7 | for(int i=0;ichildren.size();i++) if(!areIdentical(root1->children[i],root2->children[i])) return 0; 8 | return 1; 9 | } 10 | -------------------------------------------------------------------------------- /Tree/containsX.cpp: -------------------------------------------------------------------------------- 1 | bool isPresent(TreeNode* root, int x) { 2 | if(root == NULL) return 0; //not necessary on CN platform 3 | if(root->data == x) return 1; 4 | for(auto &node:root->children) if(isPresent(node,x)) return 1; 5 | } 6 | -------------------------------------------------------------------------------- /Tree/getLargestNodeCount.cpp: -------------------------------------------------------------------------------- 1 | int getLargeNodeCount(TreeNode* root, int x) { 2 | // Write your code here 3 | int count=0; 4 | for(int i=0;ichildren.size();i++) 5 | { 6 | count+=getLargeNodeCount(root->children[i],x); 7 | } 8 | if(root->data > x) return count+1; 9 | return count; 10 | } 11 | -------------------------------------------------------------------------------- /Tree/maxDataNode.cpp: -------------------------------------------------------------------------------- 1 | TreeNode* maxDataNode(TreeNode* root) { 2 | if(root==nullptr) return root; 3 | TreeNode *maxNode=root; 4 | for(int i=0;ichildren.size();i++) 5 | { 6 | TreeNode * maxNodeTemp=maxDataNode(root->children[i]); 7 | if(maxNode->data < maxNodeTemp->data) 8 | { 9 | maxNode=maxNodeTemp; 10 | } 11 | } 12 | return maxNode; 13 | } 14 | -------------------------------------------------------------------------------- /Tree/replaceWithDepth.cpp: -------------------------------------------------------------------------------- 1 | #define tn TreeNode* 2 | void replaceWithDepthValue(tn root,int m=0) { 3 | root->data = m; 4 | for(auto &node:root->children) replaceWithDepthValue(node,m+1); 5 | } 6 | -------------------------------------------------------------------------------- /TripletSum.cpp: -------------------------------------------------------------------------------- 1 | int pairSum(int *arr, int startIndex, int endIndex, int num) 2 | { 3 | int numPair = 0; 4 | while (startIndex < endIndex) 5 | { 6 | if (arr[startIndex] + arr[endIndex] < num) 7 | { 8 | startIndex++; 9 | 10 | } 11 | else if (arr[startIndex] + arr[endIndex] > num) 12 | { 13 | endIndex--; 14 | 15 | } 16 | else 17 | { 18 | int elementAtStart = arr[startIndex]; 19 | int elementAtEnd = arr[endIndex]; 20 | if (elementAtStart == elementAtEnd) 21 | { 22 | int totalElementsFromStartToEnd = (endIndex - startIndex) + 1; 23 | numPair += (totalElementsFromStartToEnd * (totalElementsFromStartToEnd - 1) / 2); 24 | return numPair; 25 | 26 | } 27 | int tempStartIndex = startIndex + 1; 28 | int tempEndIndex = endIndex - 1; 29 | while (tempStartIndex <= tempEndIndex && arr[tempStartIndex] == elementAtStart) 30 | { 31 | tempStartIndex += 1; 32 | 33 | } 34 | while (tempEndIndex >= tempStartIndex && arr[tempEndIndex] == elementAtEnd) 35 | { 36 | tempEndIndex -= 1; 37 | } 38 | int totalElementsFromStart = (tempStartIndex - startIndex); 39 | int totalElementsFromEnd = (endIndex - tempEndIndex); 40 | numPair += (totalElementsFromStart * totalElementsFromEnd); 41 | startIndex = tempStartIndex; endIndex = tempEndIndex; 42 | } 43 | } 44 | return numPair; 45 | } 46 | int tripletSum(int *arr, int n, int num) 47 | { 48 | sort(arr, arr + n); 49 | int numTriplets = 0; 50 | for (int i = 0; i < n; i++) 51 | { 52 | int pairSumFor = num - arr[i]; 53 | int numPairs = pairSum(arr, (i + 1), (n - 1), pairSumFor); 54 | numTriplets += numPairs; 55 | } 56 | return numTriplets; 57 | } 58 | -------------------------------------------------------------------------------- /graph-1/3cycle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int solve(bool **edge,int n){ 5 | int count=0; 6 | for(int i=0;i>n>>e; 23 | bool **edge=new bool*[n]; 24 | for(int i=0;i>f>>s; 33 | edge[f][s]=1; 34 | edge[s][f]=1; 35 | } 36 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void print(int **arr, int n, int starting_vertex, bool *visited) 7 | { 8 | queue q; 9 | q.push(starting_vertex); 10 | visited[starting_vertex] = true; 11 | while (!q.empty()) { 12 | 13 | cout << q.front() << " "; 14 | int current_element = q.front(); 15 | q.pop(); 16 | 17 | for (int i = 1; i < n; i++) { 18 | if (arr[current_element][i] == 1 && !visited[i] && i != current_element){ 19 | q.push(i); 20 | visited[i] = true; 21 | 22 | } 23 | } 24 | } 25 | } 26 | void BFS( int **arr , bool* visited , int starting_index , int v){ 27 | 28 | for (int i = 0; i < v; i++){ 29 | if (!visited[i]) { 30 | print(arr, v, i, visited); 31 | } 32 | } 33 | } 34 | int main() 35 | { 36 | int v, e; 37 | cin >> v >> e; 38 | int **arr = new int *[v]; 39 | for (int i = 0; i < v; i++){ 40 | arr[i] = new int[v]; 41 | for (int j = 0; j < v; j++){ 42 | arr[i][j] = 0; 43 | } 44 | } 45 | while (e--){ 46 | int a, b; 47 | cin >> a >> b; 48 | arr[a][b] = 1; 49 | arr[b][a] = 1; 50 | } 51 | bool *visited = new bool[v]; 52 | // for (int i = 0; i < v; i++){ 53 | // visited[i] = false; 54 | // } 55 | memset(visited,false,sizeof(visited)); 56 | BFS( arr , visited ,0 , v ); 57 | } 58 | -------------------------------------------------------------------------------- /graph-1/CodingNinjas.cpp: -------------------------------------------------------------------------------- 1 | const pair dir[8] = {{-1,-1},{0,-1},{1,-1},{1,0},{1,1},{0,1},{-1,1},{-1,0}}; 2 | const string word = "CODINGNINJA"; 3 | bool validMove(int x,int y,int n,int m){ 4 | return x>=0 && y>=0 && x> &board,int n,int m,vector> &vis,int wordIdx,int x,int y){ 7 | bool found = 0; 8 | if(wordIdx == 11) return 1; 9 | vis[x][y]=1; 10 | for(int i=0;i<8;i++){ 11 | int newX = x+dir[i].first; 12 | int newY = y+dir[i].second; 13 | if(validMove(newX,newY,n,m) && !vis[newX][newY] && board[newX][newY]==word[wordIdx]){ 14 | found |= dfs(board,n,m,vis,wordIdx + 1,newX,newY); 15 | } 16 | } 17 | vis[x][y]=0; 18 | return found; 19 | } 20 | bool hasPath(vector> &board, int n, int m) { 21 | // Write your code here. 22 | bool foundPath = 0; 23 | vector> vis(n,vector(m,0)); 24 | for(int i=0;i 2 | using namespace std; 3 | bool isConnected(bool **edges,int n,int sv,bool *visited){ 4 | queue q; 5 | q.push(sv); 6 | visited[sv]=true; 7 | while(!q.empty()){ 8 | int curr_ele=q.front(); 9 | q.pop(); 10 | for(int i=0;i>n>>e; 25 | bool **edges=new bool*[n]; 26 | for(int i=0;i>f>>s; 36 | edges[f][s]=1; 37 | edges[s][f]=1; 38 | } 39 | //visited array 40 | bool *visited=new bool[n]; 41 | memset(visited,false,sizeof(visited)); 42 | //working function 43 | bool ans=isConnected(edges,n,0,visited); 44 | ans?cout<<"true":cout<<"false"; 45 | } 46 | -------------------------------------------------------------------------------- /graph-1/allConnectedPaths.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector BFS(bool **edge,int n,int sv,unordered_map& visited){ 4 | queue q; 5 | q.push(sv); 6 | visited[sv]=1; 7 | vector output; 8 | while(!q.empty()){ 9 | int front=q.front(); 10 | q.pop(); 11 | output.push_back(front); 12 | for(int i=0;i visited; 23 | for(int i=0;i ans=BFS(edge,n,i,visited); 29 | sort(ans.begin(),ans.end()); 30 | for(int j=0;j>n>>e; 40 | bool **edge=new bool*[n]; 41 | for(int i=0;i>f>>s; 50 | edge[f][s]=1; 51 | edge[s][f]=1; 52 | } 53 | unordered_map visited; 54 | for(int i=0;i dir[4] = {{0,-1},{1,0},{0,1},{-1,0}}; 2 | bool validMove(int x,int y,int n,int m){return x>=0 && y>=0 && x> &board,vector> &vis ,int n, int m,int x,int y,char needColor,int fromX = -1,int fromY=-1){ 5 | if(board[x][y]!=needColor) return; 6 | if(!validMove(x,y,n,m)) return; 7 | if(vis[x][y]){ 8 | cycle = 1; 9 | return; 10 | } 11 | vis[x][y]=1; 12 | for(int i=0;i<4;i++){ 13 | int newX = x+dir[i].first; 14 | int newY = y+dir[i].second; 15 | if(newX == fromX && newY == fromY) continue; 16 | if(validMove(newX,newY,n,m)) dfs(board,vis,n,m,newX,newY,needColor,x,y); 17 | } 18 | } 19 | bool hasCycle(vector> &board, int n, int m) { 20 | vector> vis(n,vector(m,0)); 21 | for(int i=0;i 2 | using namespace std; 3 | /************************MemoryEfficient MEthod********************/ 4 | void printBFS(bool **edges, int n, int s, int e, unordered_map visited) 5 | { 6 | bool path_exist=false; 7 | queue q; 8 | q.push(s); 9 | unordered_map mp; 10 | visited[s] = true; 11 | while (!q.empty()) 12 | { 13 | int curr_ele = q.front(); 14 | q.pop(); 15 | if (curr_ele == e){ 16 | path_exist=true; 17 | break; 18 | } 19 | for (int i = 0; i < n; i++) 20 | { 21 | if (!visited[i] && edges[curr_ele][i]) 22 | { 23 | q.push(i); 24 | visited[i] = true; 25 | mp[i] = curr_ele; 26 | } 27 | } 28 | } 29 | if(!path_exist) return; 30 | int i = e; 31 | cout << e << " "; 32 | while (i != s) 33 | { 34 | cout << mp[i] << " "; 35 | i = mp[i]; 36 | } 37 | } 38 | /**************Second Approach*****************/ 39 | vector *getPathBFS(bool **edges,int n,int start,int end,unordered_map visited){ 40 | queue q; 41 | q.push(start); 42 | visited[start]=true; 43 | bool done=false; 44 | unordered_map mp; 45 | while(!q.empty() && !done){ 46 | int curr=q.front(); 47 | q.pop(); 48 | for(int i=0;i *output=new vector(); 62 | int cur=end; 63 | output->push_back(end); 64 | while(cur!=start){ 65 | cur=mp[cur]; 66 | output->push_back(cur); 67 | } 68 | return output; 69 | } 70 | int main() 71 | { 72 | int n, e; //n->vertices,e->edges 73 | cin >> n >> e; 74 | bool **edges = new bool *[n]; //edges array(2D) 75 | for (int i = 0; i < n; i++) 76 | { 77 | edges[i] = new bool[n]; 78 | for (int j = 0; j < n; j++) 79 | { 80 | edges[i][j] = false; 81 | } 82 | } 83 | //taking input of edges 84 | for (int i = 0; i < e; i++) 85 | { 86 | int f, s; 87 | cin >> f >> s; 88 | edges[f][s] = 1; 89 | edges[s][f] = 1; 90 | } 91 | //call your working function below 92 | unordered_map visitedMap; 93 | for(int i=0;i> start >> end; 98 | vector *ans=getPathBFS(edges,n,start,end,visitedMap); 99 | if(ans!=nullptr){ 100 | for(int i=0;isize();i++){ 101 | cout<at(i)<<" "; 102 | } 103 | } 104 | for (int i = 0; i < n; i++) 105 | { 106 | delete[] edges[i]; 107 | } 108 | delete[] edges; 109 | delete ans; 110 | } 111 | -------------------------------------------------------------------------------- /graph-1/getPathDFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | vector *DFS(bool **edges,int n,int sv,int ev,bool *visited){ 6 | if(sv==ev){ 7 | vector *v=new vector(); 8 | v->push_back(ev); 9 | return v; 10 | } 11 | visited[sv]=true; 12 | for(int i=0;i *temp=DFS(edges,n,i,ev,visited); 15 | if(temp!=nullptr){ 16 | temp->push_back(sv); 17 | return temp; 18 | } 19 | } 20 | } 21 | return nullptr; 22 | } 23 | int main(){ 24 | int n,e; //n->vertices,e->edges 25 | cin>>n>>e; 26 | bool **edges=new bool*[n]; //edges array(2D) 27 | for(int i=0;i>f>>s; 37 | edges[f][s]=1; 38 | edges[s][f]=1; 39 | } 40 | //visited array 41 | bool *visited=new bool[n]; 42 | memset(visited,false,sizeof(visited)); 43 | //call your working function below 44 | int start,end; 45 | cin>>start>>end; 46 | vector *ans=DFS(edges,n,start,end,visited); 47 | if(ans!=nullptr){ 48 | for(int i=0;isize();i++){ 49 | cout<at(i)<<" "; 50 | } 51 | } 52 | for(int i=0;i 2 | using namespace std; 3 | /**************DFS METHOD**********************/ 4 | bool hasPathDFS(int **edges,int n,int start,int end,bool *visited){ 5 | if(edges[start][end]) return true; 6 | visited[start]=true; 7 | for(int i=0;i q; 17 | q.push(start); 18 | visited[start]=true; 19 | while(!q.empty()){ 20 | int curr_ele=q.front(); 21 | q.pop(); 22 | if(edges[curr_ele][end]) return true; 23 | for(int i=0;i>n>>e; 38 | int **edges=new int*[n]; 39 | for(int i=0;i>f>>s; 49 | edges[f][s]=1; 50 | edges[s][f]=1; 51 | } 52 | bool *visited=new bool[n]; 53 | memset(visited,false,sizeof(visited)); 54 | int start,end; 55 | cin>>start>>end; 56 | // bool ans=hasPathDFS(edges,n,start,end,visited); 57 | bool ans=hasPathBFS(edges,n,start,end,visited); 58 | ans?cout<<"true":cout<<"false"; 59 | for(int i=0;i 2 | using namespace std; 3 | const int N= 1005; 4 | vector adj[N]; 5 | vector vis(N,0); 6 | void dfs(int v){ 7 | vis[v]=1; 8 | for(auto &u:adj[v]) if(!vis[u]) dfs(u); 9 | } 10 | int main() { 11 | int v,e; 12 | scanf("%d %d",&v,&e); 13 | for(int i=0;i dir[4] = {{-1,0},{0,-1},{1,0},{0,1}}; 2 | bool validMove(int x,int y,int n){ return x>=0 && y>=0 && x> &cake, int n,vector> &vis,int x,int y){ 4 | if(vis[x][y]) return 0; 5 | vis[x][y]=1; 6 | int cnt=1; 7 | for(int i=0;i<4;i++){ 8 | int X = x+dir[i].first; 9 | int Y = y+dir[i].second; 10 | if(validMove(X,Y,n) && cake[X][Y]) cnt += dfs(cake,n,vis,X,Y); 11 | } 12 | return cnt; 13 | } 14 | int getBiggestPieceSize(vector> &cake, int n) { 15 | int mx = 0; 16 | vector> vis(n,vector(n,0)); 17 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | void dijkstra(int **edge,int n,bool *visited,int *dist){ 8 | for(int i=0;i dist[j]){ 13 | minDist=dist[j]; 14 | vertexMinDist=j; 15 | } 16 | } 17 | visited[vertexMinDist]=1; 18 | for(int j=0;jdist[vertexMinDist]+edge[vertexMinDist][j] && edge[vertexMinDist][j]>0){ 21 | dist[j]=dist[vertexMinDist]+edge[vertexMinDist][j]; 22 | } 23 | 24 | } 25 | } 26 | } 27 | int main(){ 28 | int n,e; 29 | cin>>n>>e; 30 | int **edge=new int*[n]; 31 | for(int i=0;i>f>>s>>w; 40 | edge[f][s]=w; 41 | edge[s][f]=w; 42 | } 43 | bool *visited=new bool[n]; 44 | for(int i=0;i 2 | #include 3 | 4 | using namespace std; 5 | class Edge{ 6 | public: 7 | int source; 8 | int dest; 9 | int weight; 10 | }; 11 | bool mysort(Edge x,Edge y){ 12 | return x.weight < y.weight; 13 | } 14 | int find_parent(int v1,int *parent){ 15 | int pv1=v1; 16 | while(parent[pv1] !=pv1){ 17 | pv1=parent[pv1]; 18 | } 19 | return pv1; 20 | } 21 | int main(){ 22 | int n,e; 23 | cin>>n>>e; 24 | Edge input[e],output[n-1]; 25 | for(int i=0;i>source>>dest>>weight; 28 | input[i].source=source; 29 | input[i].dest=dest; 30 | input[i].weight=weight; 31 | } 32 | int parent[n]; 33 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | int min_vertex(bool *visited,int *weight,int n){ 9 | int min_vertex=-1; 10 | for(int i=0;iedge[minV][j]){ 33 | weight[j]=edge[minV][j]; 34 | parent[j]=minV; 35 | } 36 | } 37 | } 38 | } 39 | for(int i=1;i>n>>e; 53 | int **edge=new int*[n]; 54 | for(int i=0;i>f>>s>>w; 63 | edge[f][s]=w; 64 | edge[s][f]=w; 65 | } 66 | //function 67 | primAlgo(edge,n); 68 | for(int i=0;i *root,int k1,int k2) 2 | { 3 | if(root==nullptr) return; 4 | elementsInRangeK1K2(root->left,k1,k2); 5 | if(root->data >=k1 && root->data <= k2) cout<data<<" "; 6 | elementsInRangeK1K2(root->right,k1,k2); 7 | } 8 | --------------------------------------------------------------------------------