├── heapsort.cpp ├── README.md ├── hello.cpp ├── Trees ├── Tree │ ├── TreeNode.h │ └── vectoruse.cpp ├── SumOfAllNodes.cpp ├── FindHeight.cpp └── CountLeafNodes.cpp ├── tiling.cpp ├── Tries └── TrieImplementation │ ├── TrieNode.h │ ├── TrieUse.cpp │ └── Trie.h ├── BST ├── CheckBST1 │ └── BinaryTreeNode.h ├── CheckBST2 │ └── BinaryTreeNode.h ├── CheckBST3 │ └── BinaryTreeNode.h └── RootToNodePath │ └── BinaryTreeNode.h ├── BinaryTrees ├── BinTrees │ ├── BinaryTreeNode.h │ └── BinaryTreeUse.cpp ├── Diameter │ └── BinaryTreeNode.h ├── TakeInputQueue │ └── BinaryTreeNode.h ├── TakeInputPrintRecursive │ ├── BinaryTreeNode.h │ └── BinaryTreeUse.cpp └── Depth of a Binary Tree.cpp ├── Recursion -1 ├── Fibonacci.cpp ├── Count Zeroes.cpp ├── Recursion&Strings.cpp ├── is_sorted.cpp ├── Check Palindrom(recursive).cpp ├── First_Index_of_Number.cpp ├── Last Index of Number.cpp └── All Indices of Number.cpp ├── Arrays & Strings ├── Introduction_Char_Array.cpp ├── Strings2.cpp ├── SizeOf.cpp ├── Recover_Array.cpp ├── Find_Duplicate.cpp ├── Find_an_element.cpp ├── Strings.cpp ├── Check_Permuations.cpp ├── Reverse Word Wise.cpp ├── Break Words.cpp ├── Compress_the_String.cpp ├── Print Like a Wave.cpp ├── Pallindrome Substrings.cpp ├── Leaders In Array.cpp ├── Reverse_Each_Word.cpp ├── Print Spiral.cpp ├── Largest Unique Substring.cpp ├── Count Platforms.cpp ├── PrintIntersection.cpp ├── Merge_two_Sorted_Arrays.cpp ├── Sort_0_1_2.cpp └── Push_Zeroes To End.cpp ├── Dynamic Allocation ├── Dynamic Allocation.cpp ├── Address_typecasting.cpp └── Reference Pass By Reference.cpp ├── Priority Queues ├── priority_queue.h ├── Insert.h ├── CheckMaxHeap.cpp ├── KSmallestElements.cpp ├── KthLargest.cpp └── KLargestElements.cpp ├── Hashing ├── Remove Duplicates.cpp ├── Inbuilt Hash Unordered_Maps.cpp ├── Iterators.cpp ├── Nearest Repititon.cpp ├── Hashmap Implementation(Insert).cpp ├── Zero sum Sub array.cpp ├── Longest Subset.cpp ├── Max Freq.cpp ├── Longest Consecutive Subsequence.cpp ├── Make String Anagrams.cpp ├── Pair Sum to Zero.cpp └── Print Intersection.cpp ├── DP (1D) ├── Max_Rectangle.cpp ├── LIS.cpp ├── Kadane_Max_sum_subarray.cpp ├── (TODO)FairWorkLoad.cpp ├── NoOf Balance BTs.cpp ├── Tetrahedron.cpp ├── NoOf Balanced BSTs.cpp ├── Loot Houses.cpp ├── Boredom.cpp ├── CoinTower.cpp ├── MinCount.cpp ├── Number_of_APs.cpp ├── ByteLand.cpp └── Min Number of chocolates.cpp ├── BitTricks ├── Find1stSetBit.cpp ├── Set_ith_Bit.cpp ├── CheckPowerOf4.cpp ├── TurnOff1stSetBit.cpp ├── Unset_ith_bit.cpp └── ClearAllBitsFromMSB.cpp ├── SubsequenceGeneration.cpp ├── mergesort.cpp ├── Backtracking ├── Lexicograhical Order.cpp ├── NoOf Number with Duplicates.cpp ├── PrintSubsetsOfArray.cpp └── PrintSubsetsSumOfArray.cpp ├── Recursion -2 ├── String To Integer.cpp ├── Staircase.cpp ├── Remove Duplictes Recursively.cpp ├── Replace Pi.cpp ├── Increasing Numbers.cpp ├── Replace Character Recursively.cpp ├── Generate All Parathenses.cpp ├── Flags.cpp ├── Print Keypad Combination Code.cpp ├── Quick Sort.cpp ├── String of Lenght k.cpp ├── Interleaving.cpp ├── Return all codes-Strings.cpp ├── Merge Sort.cpp └── Return Keypad Code.cpp ├── BalancedtreeArray.cpp ├── binarytree.cpp ├── KMP-stringMatching.cpp ├── Stack&Queue ├── MinBracketReversal.cpp ├── BalancedParanthesis.cpp ├── Sort_a_Stack.cpp └── ReverseFirstKelements.cpp ├── MaxSumFromAnyNodetoAnyNode.cpp ├── DP (2D) ├── ShortestUncommenSubsequence.cpp ├── MinCostPath.cpp ├── MaxSumRectangle.cpp ├── MaxSubSquare with all zeros.cpp ├── MCM.cpp ├── Edit_Distance.cpp ├── WaysToMakeCoinChange.cpp ├── Smallest SuperSequence.cpp ├── Knapsack0-1.cpp └── LCS.cpp ├── a4.py ├── Graphs ├── LargestPiece.cpp ├── BFS.cpp ├── HasPath.cpp ├── IsConnected.cpp ├── ThreeCycle.cpp └── Island.cpp ├── Graphs2 ├── CountWays.cpp └── Bellman–Ford Algorithm.cpp ├── LinkedList ├── PallindromList.cpp └── LenghtofLL(recursive).cpp └── LinkedList2 ├── MidPointofLL.cpp ├── ReverseLL(iterative).cpp ├── ReverseLL(recursive).cpp └── MergeSortLL.cpp /heapsort.cpp: -------------------------------------------------------------------------------- 1 | #include -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | Repository meant for understanding and practice the use of various data structures and algorithms used in programming. 4 | -------------------------------------------------------------------------------- /hello.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(){ 4 | int n; 5 | cin>>n; 6 | cout< 2 | using namespace std; 3 | 4 | template 5 | class TreeNode { 6 | public: 7 | T data; 8 | vector*> children; 9 | 10 | TreeNode(T data) { 11 | this->data = data; 12 | } 13 | 14 | }; 15 | -------------------------------------------------------------------------------- /tiling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int ways(int n) 5 | { 6 | if(n<=3) 7 | return 1; 8 | 9 | 10 | 11 | return ways(n-1)+ways(n-4); 12 | } 13 | 14 | int main() 15 | { 16 | int n; 17 | cin>>n; 18 | 19 | cout< data = data; 9 | children = new TrieNode*[26]; 10 | for(int i = 0; i < 26; i++) { 11 | children[i] = NULL; 12 | } 13 | isTerminal = false; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Tries/TrieImplementation/TrieUse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include "Trie.h" 4 | 5 | 6 | int main() { 7 | Trie t; 8 | t.insertWord("and"); 9 | t.insertWord("are"); 10 | t.insertWord("dot"); 11 | 12 | cout << t.search("and") << endl; 13 | 14 | t.removeWord("and"); 15 | cout << t.search("and") << endl; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /BST/CheckBST1/BinaryTreeNode.h: -------------------------------------------------------------------------------- 1 | template 2 | class BinaryTreeNode { 3 | public: 4 | T data; 5 | BinaryTreeNode* left; 6 | BinaryTreeNode* right; 7 | 8 | BinaryTreeNode(T data) { 9 | this->data = data; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | 14 | ~BinaryTreeNode() { 15 | delete left; 16 | delete right; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /BST/CheckBST2/BinaryTreeNode.h: -------------------------------------------------------------------------------- 1 | template 2 | class BinaryTreeNode { 3 | public: 4 | T data; 5 | BinaryTreeNode* left; 6 | BinaryTreeNode* right; 7 | 8 | BinaryTreeNode(T data) { 9 | this->data = data; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | 14 | ~BinaryTreeNode() { 15 | delete left; 16 | delete right; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /BST/CheckBST3/BinaryTreeNode.h: -------------------------------------------------------------------------------- 1 | template 2 | class BinaryTreeNode { 3 | public: 4 | T data; 5 | BinaryTreeNode* left; 6 | BinaryTreeNode* right; 7 | 8 | BinaryTreeNode(T data) { 9 | this->data = data; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | 14 | ~BinaryTreeNode() { 15 | delete left; 16 | delete right; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /BST/RootToNodePath/BinaryTreeNode.h: -------------------------------------------------------------------------------- 1 | template 2 | class BinaryTreeNode { 3 | public: 4 | T data; 5 | BinaryTreeNode* left; 6 | BinaryTreeNode* right; 7 | 8 | BinaryTreeNode(T data) { 9 | this->data = data; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | 14 | ~BinaryTreeNode() { 15 | delete left; 16 | delete right; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /BinaryTrees/BinTrees/BinaryTreeNode.h: -------------------------------------------------------------------------------- 1 | template 2 | class BinaryTreeNode { 3 | public: 4 | T data; 5 | BinaryTreeNode* left; 6 | BinaryTreeNode* right; 7 | 8 | BinaryTreeNode(T data) { 9 | this->data = data; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | 14 | ~BinaryTreeNode() { 15 | delete left; 16 | delete right; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /BinaryTrees/Diameter/BinaryTreeNode.h: -------------------------------------------------------------------------------- 1 | template 2 | class BinaryTreeNode { 3 | public: 4 | T data; 5 | BinaryTreeNode* left; 6 | BinaryTreeNode* right; 7 | 8 | BinaryTreeNode(T data) { 9 | this->data = data; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | 14 | ~BinaryTreeNode() { 15 | delete left; 16 | delete right; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /BinaryTrees/TakeInputQueue/BinaryTreeNode.h: -------------------------------------------------------------------------------- 1 | template 2 | class BinaryTreeNode { 3 | public: 4 | T data; 5 | BinaryTreeNode* left; 6 | BinaryTreeNode* right; 7 | 8 | BinaryTreeNode(T data) { 9 | this->data = data; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | 14 | ~BinaryTreeNode() { 15 | delete left; 16 | delete right; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /BinaryTrees/TakeInputPrintRecursive/BinaryTreeNode.h: -------------------------------------------------------------------------------- 1 | template 2 | class BinaryTreeNode { 3 | public: 4 | T data; 5 | BinaryTreeNode* left; 6 | BinaryTreeNode* right; 7 | 8 | BinaryTreeNode(T data) { 9 | this->data = data; 10 | left = NULL; 11 | right = NULL; 12 | } 13 | 14 | ~BinaryTreeNode() { 15 | delete left; 16 | delete right; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Recursion -1/Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fib(int n) { 5 | if (n == 0) { 6 | return 0; 7 | } 8 | 9 | if (n == 1) { 10 | return 1; 11 | } 12 | 13 | int smallOutput1 = fib(n - 1); 14 | int smallOutput2 = fib(n - 2); 15 | return smallOutput1 + smallOutput2; 16 | } 17 | 18 | int main() { 19 | cout << fib(3) << endl; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /BinaryTrees/BinTrees/BinaryTreeUse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BinaryTreeNode.h" 3 | using namespace std; 4 | 5 | int main() { 6 | BinaryTreeNode* root = new BinaryTreeNode(1); 7 | BinaryTreeNode* node1 = new BinaryTreeNode(2); 8 | BinaryTreeNode* node2 = new BinaryTreeNode(3); 9 | root->left = node1; 10 | root->right = node2; 11 | } 12 | 13 | -------------------------------------------------------------------------------- /Arrays & Strings/Introduction_Char_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int a[5] = {1, 2, 3}; 6 | 7 | char b[] = "abcd"; 8 | 9 | //cin >> b; 10 | 11 | 12 | cin.getline(b, 40, 'o'); //This is for taking string inputs for space in between 13 | 14 | cout << b << endl; 15 | 16 | /* 17 | cout << a << endl; 18 | 19 | b[1] = '\0'; 20 | cout << b << endl; 21 | */ 22 | } -------------------------------------------------------------------------------- /Dynamic Allocation/Dynamic Allocation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int m, n; 6 | cin >> m >> n; 7 | int** p = new int*[m]; 8 | for (int i = 0; i < m; i++) { 9 | p[i] = new int[i + 1]; 10 | for (int j = 0;j > p[i][j]; 12 | } 13 | } 14 | 15 | for (int i = 0; i < m; i++) { 16 | delete [] p[i]; 17 | } 18 | delete [] p; 19 | return 0; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Dynamic Allocation/Address_typecasting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int i = 65; 6 | char c = i; 7 | cout << c << endl; 8 | 9 | int * p = &i; 10 | char * pc = (char*)p; 11 | 12 | cout << p << endl; 13 | cout << pc << endl; 14 | 15 | cout << *p << endl; 16 | cout << *pc << endl; 17 | cout << *(pc + 1) << endl; 18 | cout << *(pc + 2) << endl; 19 | cout << *(pc + 3) << endl; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Priority Queues/priority_queue.h: -------------------------------------------------------------------------------- 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 | }; 29 | -------------------------------------------------------------------------------- /Dynamic Allocation/Reference Pass By Reference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void increment(int& i) { 5 | i++; 6 | } 7 | 8 | // bad practice 9 | int& f(int n) { 10 | int a = n; 11 | return a; 12 | } 13 | 14 | // bad practice 15 | int* f2() { 16 | int i = 10; 17 | return &i; 18 | } 19 | 20 | int main() { 21 | int* p = f2(); 22 | 23 | int i; 24 | i = 10; 25 | 26 | int& k1 = f(i); 27 | 28 | 29 | increment(i); 30 | cout << i << endl; 31 | 32 | int& j = i; 33 | 34 | i++; 35 | cout << j << endl; 36 | j++; 37 | cout << i << endl; 38 | 39 | int k = 100; 40 | j = k; 41 | cout << i << endl; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Hashing/Remove Duplicates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector removeDuplicates(int* a, int size) { 7 | vector output; 8 | unordered_map seen; 9 | for (int i = 0; i < size; i++) { 10 | if (seen.count(a[i]) > 0) { 11 | continue; 12 | } 13 | seen[a[i]] = true; 14 | output.push_back(a[i]); 15 | } 16 | return output; 17 | } 18 | 19 | int main() { 20 | int a[] = {1,2,3,3,2,1,4,3,6,5,5}; 21 | vector output = removeDuplicates(a, 11); 22 | for (int i = 0; i < output.size(); i++) { 23 | cout << output[i] << endl; 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /DP (1D)/Max_Rectangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D array, find the maximum sum rectangle in it. In other words find maximum sum over all rectangles in the matrix. 3 | Input 4 | First line contains 2 numbers n and m denoting number of rows and number of columns. Next n lines contain m space separated integers denoting elements of matrix nxm. 5 | Output 6 | Output a single integer, maximum sum rectangle. 7 | Constraints 8 | 1<=n,m<=100 9 | Sample Input 10 | 4 5 11 | 1 2 -1 -4 -20 12 | -8 -3 4 2 1 13 | 3 8 10 1 3 14 | -4 -1 1 7 -6 15 | Sample Output 16 | 29 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | 22 | int main() 23 | { 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Arrays & Strings/Strings2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | string* sp = new string; 7 | *sp = "def"; 8 | cout << sp << endl; 9 | cout << *sp << endl; 10 | 11 | string s = "abc"; 12 | //getline(cin, s); 13 | cout << s << endl; 14 | 15 | s = "defdef"; 16 | cout << s[0] << endl; 17 | s[0] = 'a'; 18 | string s1; 19 | s1 = "def"; 20 | 21 | string s2 = s + s1; 22 | cout << s2 << endl; 23 | 24 | s += s1; 25 | 26 | cout << s1 << endl; 27 | cout << s << endl; 28 | 29 | cout << s.size() << endl; 30 | cout << s.substr(3) << endl; 31 | cout << s.substr(3, 3) << endl; 32 | 33 | cout << s.find("def") << endl; 34 | 35 | 36 | 37 | 38 | 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Arrays & Strings/SizeOf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void test(int a, int b[]) { 5 | cout << a << endl; 6 | cout << b[0] << endl; 7 | } 8 | 9 | void printArray(int input[], int n) { 10 | 11 | cout << "Function : " << sizeof(input) << endl; 12 | 13 | 14 | //int size = sizeof(input) / sizeof(int); 15 | for(int i = 0; i < n; i++) { 16 | cout << input[i] << " "; 17 | } 18 | 19 | 20 | } 21 | 22 | int main() { 23 | int input[] = {1, 2, 3}; 24 | cout << "Main : " << sizeof(input) << endl; 25 | /* 26 | int n; 27 | 28 | cin >> n; 29 | 30 | for(int i = 0; i < n; i++) { 31 | cin >> input[i]; 32 | } 33 | */ 34 | 35 | int a = 6; 36 | 37 | test(a, input); 38 | 39 | printArray(input, 3); 40 | } 41 | -------------------------------------------------------------------------------- /BitTricks/Find1stSetBit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer N. You need to return an integer M, in which only one bit is set which at position of lowest set bit of N (from right to left). 3 | Input Format : 4 | 5 | Integer N 6 | 7 | Output Format : 8 | 9 | Integer M 10 | 11 | Sample Input 1 : 12 | 13 | 7 14 | 15 | Sample Output 1 : 16 | 17 | 1 18 | 19 | Sample Input 2 : 20 | 21 | 12 22 | 23 | Sample Output 2 : 24 | 25 | 4 26 | 27 | */ 28 | #include 29 | using namespace std; 30 | 31 | int returnFirstSetBit(int n){ 32 | int ans=n & (~(n-1)); 33 | return ans; 34 | 35 | } 36 | 37 | 38 | 39 | int main() { 40 | int n; 41 | 42 | cin >> n; 43 | 44 | cout<< returnFirstSetBit(n) < 35 | #include "solution.h" 36 | using namespace std; 37 | 38 | int main() { 39 | int n; 40 | cin >> n; 41 | cout << countZeros(n) << endl; 42 | } 43 | -------------------------------------------------------------------------------- /SubsequenceGeneration.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void print(vector v) 5 | { 6 | for(int i=0;i v,int ind) 15 | { 16 | if(v.size()>=0) 17 | { 18 | print(v); 19 | if(ind==s.size()) 20 | return; 21 | } 22 | 23 | for(int i=ind;i>s; 39 | 40 | vector v; 41 | 42 | generate(s,v,0); 43 | return 0; 44 | } -------------------------------------------------------------------------------- /Recursion -1/Recursion&Strings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void removeX(char s[]) { 5 | if (s[0] == '\0') { 6 | return; 7 | } 8 | 9 | if (s[0] != 'x') { 10 | removeX(s + 1); 11 | } else { 12 | int i = 1; 13 | for (; s[i] != '\0'; i++) { 14 | s[i - 1] = s[i]; 15 | } 16 | s[i - 1] = s[i]; 17 | removeX(s); 18 | } 19 | } 20 | 21 | int length(char s[]) { 22 | if (s[0] == '\0') { 23 | return 0; 24 | } 25 | int smallStringLength = length(s + 1); 26 | return 1 + smallStringLength; 27 | } 28 | 29 | int main() { 30 | char str[100]; 31 | cin >> str; 32 | 33 | int l = length(str); 34 | cout << l << endl; 35 | removeX(str); 36 | cout << str << endl; 37 | l = length(str); 38 | cout << l << endl; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Recursion -1/is_sorted.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool is_sorted2(int a[], int size) { 5 | if (size == 0 || size ==1) { 6 | return true; 7 | } 8 | 9 | bool isSmallerOutput = is_sorted2(a + 1, size -1); 10 | if (!isSmallerOutput) { 11 | return false; 12 | } 13 | if (a[0] > a[1]) { 14 | return false; 15 | } else { 16 | return true; 17 | } 18 | 19 | } 20 | 21 | bool is_sorted(int a[], int size) { 22 | if (size == 0 || size ==1) { 23 | return true; 24 | } 25 | 26 | if (a[0] > a[1]) { 27 | return false; 28 | } 29 | bool isSmallerSorted = is_sorted(a + 1, size - 1); 30 | return isSmallerSorted; 31 | /*if (isSmallerSorted) { 32 | return true; 33 | } else { 34 | return false; 35 | }*/ 36 | } 37 | 38 | int main() { 39 | 40 | } 41 | 42 | -------------------------------------------------------------------------------- /BitTricks/Set_ith_Bit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two integers N and i. You need to make ith bit of binary representation of N to 1 and return the updated N. 3 | Counting of bits start from 0 from right to left. 4 | Input Format : 5 | 6 | Two integers N and i (separated by space) 7 | 8 | Output Format : 9 | 10 | Updated N 11 | 12 | Sample Input 1 : 13 | 14 | 4 1 15 | 16 | Sample Output 1 : 17 | 18 | 6 19 | 20 | Sample Input 2 : 21 | 22 | 4 4 23 | 24 | Sample Output 2 : 25 | 26 | 20 27 | 28 | */ 29 | 30 | int turnOnIthBit(int n, int i){ 31 | 32 | int ans=n | (1< 38 | using namespace std; 39 | 40 | int main() { 41 | int n, i; 42 | 43 | cin >> n >> i; 44 | 45 | cout<< turnOnIthBit(n, i) < 2 | using namespace std; 3 | 4 | void recoverArray(int input[], int n, int output[]) { 5 | int left, right; 6 | 7 | int mid = n/2; 8 | int i = 0; 9 | if(n % 2 != 0) { 10 | output[mid] = input[i]; 11 | left = mid - 1; 12 | right = mid + 1; 13 | i++; 14 | } 15 | else { 16 | left = mid - 1; 17 | right = mid; 18 | } 19 | 20 | while(i < n) { 21 | output[left] = input[i]; 22 | left--; 23 | i++; 24 | output[right] = input[i]; 25 | right++; 26 | i++; 27 | } 28 | } 29 | 30 | int main() { 31 | int input[100]; 32 | int n; 33 | 34 | int output[100]; 35 | 36 | cin >> n; 37 | 38 | for(int i = 0; i < n; i++) { 39 | cin >> input[i]; 40 | } 41 | 42 | recoverArray(input, n, output); 43 | 44 | for(int i = 0; i < n; i++) { 45 | cout << output[i] << " "; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /DP (1D)/LIS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int lis(int* input, int n) { 5 | int* output = new int[n]; 6 | output[0] = 1; 7 | for (int i = 1; i < n; i++) { 8 | output[i] = 1; 9 | for (int j = i - 1; j >= 0; j--) { 10 | if (input[j] > input[i]) { 11 | continue; 12 | } 13 | int possibleAns = output[j] + 1; 14 | if (possibleAns > output[i]) { 15 | output[i] = possibleAns; 16 | } 17 | } 18 | } 19 | int best = 0; 20 | for (int i = 0; i < n; i++) { 21 | if (best < output[i]) { 22 | best = output[i]; 23 | } 24 | } 25 | delete [] output; 26 | return best; 27 | } 28 | 29 | int main() { 30 | int n; 31 | cin >> n; 32 | int * input = new int[n]; 33 | for (int i = 0; i < n; i++) { 34 | cin >> input[i]; 35 | } 36 | int ans = lis(input, n); 37 | cout << ans << endl; 38 | delete [] input; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /BitTricks/CheckPowerOf4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer N. You need to check if N is power of 4 or not. Return true or false accordingly. 3 | Note : Do it in O(1) time. 4 | Input Format : 5 | 6 | Integers N 7 | 8 | Output Format : 9 | 10 | true or false 11 | 12 | Sample Input 1 : 13 | 14 | 4 15 | 16 | Sample Output 1 : 17 | 18 | true 19 | 20 | Sample Input 2 : 21 | 22 | 8 23 | 24 | Sample Output 2 : 25 | 26 | false 27 | 28 | */ 29 | 30 | bool isPowerOf4(int n){ 31 | 32 | bool ans=!(n&(n-1)) && (n & 0x5555555); 33 | return ans; 34 | 35 | } 36 | 37 | #include 38 | using namespace std; 39 | 40 | int main() { 41 | int n; 42 | 43 | cin >> n; 44 | 45 | if(isPowerOf4(n)) { 46 | cout << "true" << endl; 47 | } 48 | else { 49 | cout << "false" << endl; 50 | } 51 | 52 | return 0; 53 | } 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Hashing/Inbuilt Hash Unordered_Maps.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | unordered_map ourmap; 8 | 9 | // insert 10 | pair p("abc", 1); 11 | ourmap.insert(p); 12 | ourmap["def"] = 2; 13 | 14 | // find or access 15 | cout << ourmap["abc"] << endl; 16 | cout << ourmap.at("abc") << endl; 17 | 18 | //cout << ourmap.at("ghi") << endl; 19 | cout << "size : " << ourmap.size() << endl; 20 | cout << ourmap["ghi"] << endl; 21 | cout << "size : " << ourmap.size() << endl; 22 | 23 | // check Presense 24 | if (ourmap.count("ghi") > 0) { 25 | cout << "ghi is present" << endl; 26 | } 27 | 28 | // erase 29 | ourmap.erase("ghi"); 30 | cout << "size : " << ourmap.size() << endl; 31 | if (ourmap.count("ghi") > 0) { 32 | cout << "ghi is present" << endl; 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Arrays & Strings/Find_Duplicate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include "solution.h" 4 | 5 | 6 | // arr - input array 7 | // size - size of array 8 | 9 | int MissingNumber(int arr[], int size){ 10 | /* Don't write main(). 11 | * Don't read input, it is passed as function argument. 12 | * Return output and don't print it. 13 | * Taking input and printing output is handled automatically. 14 | */ 15 | int sum=(size*(size-1))/2; 16 | 17 | int calsum=0; 18 | for(int i=0;i> size; 30 | int *input = new int[1 + size]; 31 | 32 | for(int i = 0; i < size; i++) 33 | cin >> input[i]; 34 | 35 | cout << MissingNumber(input, size); 36 | 37 | delete [] input; 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Hashing/Iterators.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() { 8 | unordered_map ourmap; 9 | ourmap["abc"] = 1; 10 | ourmap["abc1"] = 2; 11 | ourmap["abc2"] = 3; 12 | ourmap["abc3"] = 4; 13 | ourmap["abc4"] = 5; 14 | ourmap["abc5"] = 6; 15 | 16 | unordered_map::iterator it = ourmap.begin(); 17 | while (it != ourmap.end()) { 18 | cout << "Key : " << it->first << " Value: " << it->second << endl; 19 | it++; 20 | } 21 | 22 | // find 23 | unordered_map::iterator it2 = ourmap.find("abc"); 24 | ourmap.erase(it2, it2 + 4); 25 | 26 | 27 | vector v; 28 | v.push_back(1); 29 | v.push_back(2); 30 | v.push_back(3); 31 | v.push_back(4); 32 | v.push_back(5); 33 | 34 | vector::iterator it1 = v.begin(); 35 | while (it1 != v.end()) { 36 | cout << *it1 << endl; 37 | it1++; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void selectionsort(int * arr,int n) 4 | { 5 | 6 | for(int i=0;iarr[j]){m=arr[j];index=j;} 12 | } 13 | swap(arr[i],arr[index]); 14 | } 15 | return; 16 | } 17 | 18 | void bubblesort(int *arr, int n) 19 | { 20 | for(int i=0;iarr[j]){ 24 | swap(arr[i],arr[j]); 25 | } 26 | } 27 | } 28 | } 29 | 30 | void printArray(int *arr,int n){ 31 | for(int i=0;i 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 childIndex = pq.size() - 1; 32 | 33 | while(childIndex > 0) { 34 | int parentIndex = (childIndex - 1) / 2; 35 | 36 | if(pq[childIndex] < pq[parentIndex]) { 37 | int temp = pq[childIndex]; 38 | pq[childIndex] = pq[parentIndex]; 39 | pq[parentIndex] = temp; 40 | } 41 | else { 42 | break; 43 | } 44 | childIndex = parentIndex; 45 | } 46 | 47 | } 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | }; 58 | -------------------------------------------------------------------------------- /BitTricks/TurnOff1stSetBit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer Ni. You need to make first set bit of binary representation of N to 0 and return the updated N. 3 | Counting of bits start from 0 from right to left. 4 | Input Format : 5 | 6 | Integer N 7 | 8 | Output Format : 9 | 10 | Updated N 11 | 12 | Sample Input 1 : 13 | 14 | 4 15 | 16 | Sample Output 1 : 17 | 18 | 0 19 | 20 | Sample Input 2 : 21 | 22 | 12 23 | 24 | Sample Output 2 : 25 | 26 | 8 27 | 28 | */ 29 | 30 | int turnOffFirstSetBit(int n){ 31 | /* Don't write main(). 32 | * Don't read input, it is passed as function argument. 33 | * Return output and don't print it. 34 | * Taking input and printing output is handled automatically. 35 | */ 36 | int ans = n & (n-1); 37 | return ans; 38 | 39 | } 40 | 41 | 42 | #include 43 | using namespace std; 44 | 45 | int main() { 46 | int n; 47 | 48 | cin >> n; 49 | 50 | cout<< turnOffFirstSetBit(n) < 2 | using namespace std; 3 | 4 | 5 | void findElement(int input[][100], int m, int n, int x) { 6 | int i = 0, j = n - 1; 7 | while(i < m && j >= 0) { 8 | if(input[i][j] == x) { 9 | cout << i << " " << j << endl; 10 | return; 11 | } 12 | else if(x > input[i][j]) { 13 | i++; 14 | } 15 | else { 16 | j--; 17 | } 18 | } 19 | cout << "-1" << endl; 20 | } 21 | 22 | void printArray(int input[][100], int m, int n) { 23 | for(int i = 0; i < m; i++) { 24 | for(int j = 0; j < n; j++) { 25 | cout << input[i][j] << " "; 26 | } 27 | cout << endl; 28 | } 29 | 30 | } 31 | 32 | int main() { 33 | int a[100][100]; 34 | int m, n; 35 | 36 | // Rows - m 37 | // Cols - n 38 | cin >> m >> n; 39 | 40 | 41 | // Taking input 42 | for(int i = 0; i < m; i++) { 43 | for(int j = 0; j < n; j++) { 44 | cin >> a[i][j]; 45 | } 46 | } 47 | 48 | int x; 49 | cin >> x; 50 | 51 | findElement(a, m, n, x); 52 | 53 | //printArray(a, m, n); 54 | 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Trees/Tree/vectoruse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | //vector * vp = new vector(); 7 | vector v; 8 | 9 | for (int i = 0; i < 100; i++) { 10 | cout << "cap:" << v.capacity() << endl; 11 | cout << "size:" << v.size() << endl; 12 | v.push_back(i + 1); 13 | } 14 | 15 | v.push_back(10); 16 | v.push_back(20); 17 | v.push_back(30); 18 | 19 | v[1] = 100; 20 | 21 | // dont use [] for inserting elements 22 | //v[3] = 1002; 23 | //v[4] = 1234; 24 | 25 | v.push_back(23); 26 | v.push_back(234); 27 | 28 | v.pop_back(); 29 | 30 | /* 31 | for (int i = 0; i < v.size(); i++) { 32 | cout << v[i] << endl; 33 | } 34 | 35 | 36 | cout << v[0] << endl; 37 | cout << v[1] << endl; 38 | cout << v[2] << endl; 39 | cout << v[3] << endl; 40 | cout << v[4] << endl; 41 | cout << v[5] << endl; 42 | cout << v[6] << endl; 43 | 44 | cout << "Size: " << v.size() << endl; 45 | 46 | cout << v.at(2) << endl; 47 | cout << v.at(6) << endl; 48 | */ 49 | } 50 | 51 | -------------------------------------------------------------------------------- /BitTricks/Unset_ith_bit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two integers N and i. You need to make ith bit of binary representation of N to 0 and return the updated N. 3 | Counting of bits start from 0 from right to left. 4 | Input Format : 5 | 6 | Two integers N and i (separated by space) 7 | 8 | Output Format : 9 | 10 | Updated N 11 | 12 | Sample Input 1 : 13 | 14 | 7 2 15 | 16 | Sample Output 1 : 17 | 18 | 3 19 | 20 | Sample Input 2 : 21 | 22 | 12 1 23 | 24 | Sample Output 2 : 25 | 26 | 12 27 | 28 | */ 29 | 30 | int turnOffIthBit(int n, int i){ 31 | /* Don't write main(). 32 | * Don't read input, it is passed as function argument. 33 | * Return output and don't print it. 34 | * Taking input and printing output is handled automatically. 35 | */ 36 | int ans=n; 37 | if((n | (1< 45 | using namespace std; 46 | 47 | int main() { 48 | int n, i; 49 | 50 | cin >> n >> i; 51 | 52 | cout<< turnOffIthBit(n, i) < 33 | #include 34 | using namespace std; 35 | 36 | /* 37 | int csti(string s){ 38 | int ans=0; 39 | for(int i=0;in) 47 | return; 48 | for(int i=0;i<=9;i++){ 49 | x=x*10+i; 50 | if(x==0) 51 | continue; 52 | if(x<=n) 53 | cout<> n; 71 | lexicographicalOrder(n); 72 | } 73 | -------------------------------------------------------------------------------- /Recursion -2/String To Integer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | Input format : 4 | 5 | Numeric string (string, Eg. "1234") 6 | 7 | Output format : 8 | 9 | Corresponding integer (int, Eg. 1234) 10 | 11 | Sample Input 1 : 12 | 13 | 1231 14 | 15 | Sample Output 1: 16 | 17 | 1231 18 | 19 | Sample Input 2 : 20 | 21 | 12567 22 | 23 | Sample Output 2 : 24 | 25 | 12567 26 | */ 27 | 28 | #include 29 | using namespace std; 30 | int stringToNumber(char input[]) { 31 | // Write your code here 32 | if (input[0]=='\0') 33 | return 0; 34 | int ans=stringToNumber(input+1); 35 | 36 | int size=strlen(input); 37 | int d=(input[0]-48)*pow(10,size-1); 38 | return ans+d; 39 | 40 | } 41 | 42 | 43 | 44 | #include 45 | #include "solution.h" 46 | using namespace std; 47 | 48 | int main() { 49 | char input[50]; 50 | cin >> input; 51 | cout << stringToNumber(input) << endl; 52 | } 53 | -------------------------------------------------------------------------------- /Recursion -2/Staircase.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A child is running up a staircase with N steps, and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up to the stairs. You need to return number of possible ways W. 3 | Input format : 4 | 5 | Line 1 : Integer N (No. of steps) 6 | 7 | Output Format : 8 | 9 | Line 1 : Integer W i.e. Number of possible ways 10 | 11 | Constraint : 12 | (1 <= N <= 30) 13 | Sample Input 1: 14 | 15 | 4 16 | 17 | Sample Output : 18 | 19 | 7 20 | */ 21 | 22 | #include 23 | using namespace std; 24 | 25 | 5 26 | int staircase(int n){ 27 | /* Don't write main(). 28 | * Don't read input, it is passed as function argument. 29 | * Return output and don't print it. 30 | * Taking input and printing output is handled automatically. 31 | */ 32 | if(n==1 || n==0) 33 | return 1; 34 | if(n==2) 35 | return 2; 36 | 37 | int ans=staircase(n-1)+staircase(n-2)+staircase(n-3); 38 | return ans; 39 | 40 | } 41 | 42 | int main() { 43 | int n, output; 44 | cin >> n; 45 | output=staircase(n); 46 | cout<< output < 30 | using namespace std; 31 | bool chp(char input[],int start,int end){ 32 | if(end 49 | #include "solution.h" 50 | using namespace std; 51 | 52 | int main() { 53 | char input[50]; 54 | cin >> input; 55 | 56 | if(checkPalindrome(input)) { 57 | cout << "true" << endl; 58 | } 59 | else { 60 | cout << "false" << endl; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Recursion -2/Remove Duplictes Recursively.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, remove consecutive duplicates from it recursively. 3 | Input Format : 4 | 5 | String S 6 | 7 | Output Format : 8 | 9 | Output string 10 | 11 | Constraints : 12 | 1 <= Length of String S <= 10^3 13 | Sample Input : 14 | 15 | aabccba 16 | 17 | Sample Output : 18 | 19 | abcba 20 | 21 | */ 22 | 23 | void removeConsecutiveDuplicates(char *input) { 24 | /* Don't write main(). 25 | * Don't read input, it is passed as function argument. 26 | * Change in the given string itself. 27 | * No need to return or print anything 28 | * Taking input and printing output is handled automatically. 29 | */ 30 | 31 | if(input[0]=='\0') 32 | return; 33 | if(input[0]==input[1]){ 34 | int i=1; 35 | for(;input[i]!='\0';i++) 36 | input[i-1]=input[i]; 37 | input[i-1]=input[i]; 38 | removeConsecutiveDuplicates(input); 39 | } 40 | removeConsecutiveDuplicates(input+1); 41 | 42 | } 43 | #include 44 | using namespace std; 45 | #include "solution.h" 46 | 47 | int main() { 48 | char s[100000]; 49 | cin >> s; 50 | removeConsecutiveDuplicates(s); 51 | cout << s << endl; 52 | } -------------------------------------------------------------------------------- /BalancedtreeArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | ///for trees 6 | #include 7 | using namespace std; 8 | class node{ 9 | public: 10 | node* left; 11 | node* right; 12 | int data; 13 | 14 | node(int d) 15 | { 16 | left=NULL; 17 | right=NULL; 18 | data=d; 19 | } 20 | }; 21 | 22 | node* buildtree(){ 23 | int d; 24 | cin>>d; 25 | if(d==-1) 26 | { 27 | return NULL; 28 | } 29 | node* root = new node(d); 30 | root->left = buildtree(); 31 | root->right=buildtree(); 32 | 33 | return root; 34 | } 35 | node* buildbalancedtree(int arr[],int s,int e){ 36 | if(s>e) 37 | return NULL; 38 | 39 | int mid = (s+e)/2; 40 | 41 | node* root = new node(arr[mid]); 42 | root->left = buildbalancedtree(arr,s,mid-1); 43 | root->right = buildbalancedtree(arr,mid+1,e); 44 | 45 | return root; 46 | 47 | 48 | } 49 | // the the was #incluide 50 | // THis value 51 | 52 | int main() 53 | { 54 | //node* root=buildtree(); 55 | int arr[]={1,2,3,4,5,6,7}; 56 | int size = sizeof(arr)/sizeof(int); 57 | buildbalancedtree(arr,0,size-1); 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /Arrays & Strings/Strings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | 6 | void printAllPrefixes(char input[]) { 7 | // i represents end index of my prefix 8 | for(int i = 0; input[i] != '\0'; i++) { 9 | // j represents start index of my prefix 10 | for(int j = 0; j <= i; j++) { 11 | cout << input[j]; 12 | } 13 | cout << endl; 14 | } 15 | } 16 | 17 | int main() { 18 | char input1[100] = "abcd"; 19 | printAllPrefixes(input1); 20 | 21 | 22 | 23 | 24 | /* 25 | char input2[100] = "xy"; 26 | 27 | cout << "Before copying : "; 28 | cout << "Input 1 : " << input1 << endl; 29 | cout << "Input 2 : " << input2 << endl; 30 | //strcpy(input1, "hello"); 31 | 32 | strncpy(input1, input2, 4); 33 | 34 | cout << "After copying : "; 35 | cout << "Input 1 : " << input1 << endl; 36 | cout << "Input 2 : " << input2 << endl; 37 | */ 38 | 39 | 40 | 41 | 42 | //cin >> input1; 43 | //cin >> input2; 44 | 45 | 46 | /* 47 | if(strcmp(input1, input2) == 0) { 48 | cout << "true" << endl; 49 | } 50 | else { 51 | cout << "false" << endl; 52 | } 53 | */ 54 | 55 | 56 | 57 | 58 | /* 59 | int len = strlen(input); 60 | cout << "Length : " << len << endl; 61 | */ 62 | 63 | 64 | } 65 | 66 | -------------------------------------------------------------------------------- /BitTricks/ClearAllBitsFromMSB.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two integers N and i. You need to clear all bits from MSB to ith bit (start i from right to left) and return the updated N. 3 | Counting of bits starts from 0 from right to left. 4 | Input Format : 5 | 6 | Two integers N and i (separated by space) 7 | 8 | Output Format : 9 | 10 | Updated N 11 | 12 | Sample Input 1 : 13 | 14 | 15 2 15 | 16 | Sample Output 1 : 17 | 18 | 3 19 | 20 | Sample Output 1 Explanation : 21 | We need to clear all bits from MSB to ith bit i.e. clear all bits except 0th and 1st. 22 | Sample Input 2 : 23 | 24 | 4 4 25 | 26 | Sample Output 2 : 27 | 28 | 4 29 | 30 | */ 31 | 32 | 33 | int clearAllBits(int n, int i){ 34 | /* Don't write main(). 35 | * Don't read input, it is passed as function argument. 36 | * Return output and don't print it. 37 | * Taking input and printing output is handled automatically. 38 | */ 39 | int a=1< 50 | using namespace std; 51 | 52 | int main() { 53 | int n, i; 54 | 55 | cin >> n >> i; 56 | 57 | cout<< clearAllBits(n, i) < 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int findSum(int arr[],int n){ 12 | /* Don't write main(). 13 | * Don't read input, it is passed as function argument. 14 | * Don't print output and return the output. 15 | * Taking input and printing output is handled automatically. 16 | */ 17 | 18 | int all_neg=1; 19 | 20 | //Loop to check for all negatives; 21 | 22 | int neg_max=-200; 23 | for(int i=0;i0){ 25 | all_neg=0; 26 | break; 27 | } 28 | neg_max=max(neg_max,arr[i]); 29 | 30 | } 31 | if(all_neg) 32 | return neg_max; 33 | 34 | int maxsum=0; 35 | int sum=0; 36 | for(int i=0;i>n; 50 | int arr[n]; 51 | for(int i =0;i>arr[i]; 53 | } 54 | cout< 30 | using namespace std; 31 | // Change in the given string itself. So no need to return or print anything 32 | 33 | void replacePi(char input[]) { 34 | // Write your code here 35 | if(input[0]=='\0') 36 | return; 37 | if(input[0]=='p' && input[1]=='i'){ 38 | input[0]='3'; 39 | input[1]='.'; 40 | 41 | int size=strlen(input); 42 | for(int i=size+2;i>1;i--){ 43 | input[i]=input[i-2]; 44 | } 45 | input[2]='1'; 46 | input[3]='4'; 47 | } 48 | 49 | replacePi(input+1); 50 | 51 | } 52 | 53 | 54 | #include 55 | #include "solution.h" 56 | using namespace std; 57 | 58 | int main() { 59 | char input[100]; 60 | cin.getline(input, 100); 61 | replacePi(input); 62 | cout << input << endl; 63 | } 64 | -------------------------------------------------------------------------------- /binarytree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class node{ 4 | public: 5 | int val; 6 | node *left; 7 | node *right; 8 | }; 9 | 10 | void printtree(node *root){ 11 | cout<val<<" "; 12 | if(root==NULL) 13 | { return; 14 | } 15 | printtree(root->left); 16 | printtree(root->right); 17 | return; 18 | } 19 | 20 | node* addnode(int value,node *root){ 21 | if(root==NULL) 22 | { node* newnode =new node; 23 | root=newnode; 24 | newnode->val=value; 25 | return ; 26 | } 27 | if(root->left==NULL){ 28 | node* newnode =new node; 29 | root->left=newnode; 30 | newnode->val=value; 31 | return; 32 | } 33 | if(root->right==NULL){ 34 | node* newnode =new node; 35 | root->right=newnode; 36 | newnode->val=value; 37 | 38 | return; 39 | } 40 | addnode(value,root->left); 41 | addnode(value,root->right); 42 | return; 43 | } 44 | 45 | int main(){ 46 | 47 | int arr[]={1,2,3,5,6}; 48 | node *root=NULL; 49 | node *head= 50 | for(int i=0;i<5;i++) 51 | { 52 | addnode(arr[i],root); 53 | } 54 | printtree(root); 55 | return 0; 56 | } -------------------------------------------------------------------------------- /DP (1D)/(TODO)FairWorkLoad.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We are Given N number of cabinets and every cabinets has a certain amount of files. We want to go through each and every file in these cabinets and for that we have x number of workers. Distribute the work amongst x workers such that the difference between the number of files that two worker goes through is minimised and the amount that one worker does is maximised. 3 | The constraint is - a worker can go through only cabinets that are adjacent. 4 | Return the maximum amount of work (Work is defined as the amount of files a worker has to go through) a worker is doing in such an arrangement. 5 | For Example :- 6 | Given 9 cabinets each containing 10 20 30 40 50 60 70 80 90 folders and with 3 workers, we can divide the cabinets in 10 20 30 40 50 | 60 70 | 80 90 . So in this case output should be 170, as it is the maximum amount of work done by any worker. 7 | 8 | Input format : 9 | 10 | Line 1 : N (Number of cabinets) 11 | 12 | Line 2 : N integers denoting the number of files in the cabinets respectively (separated by space) 13 | 14 | Line 3 : x (No. of workers) 15 | 16 | Output format : A single integer, denoting the maximum work any worker is doing such that difference in work between two worker is minimised 17 | 18 | */ 19 | 20 | -------------------------------------------------------------------------------- /DP (1D)/NoOf Balance BTs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer h, find the possible number of balanced binary trees of height h. 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 | Time complexity should be O(h). 5 | Input Format : 6 | 7 | Integer h 8 | 9 | Output Format : 10 | 11 | Count % 10^9 + 7 12 | 13 | Input Constraints : 14 | 1 <= h <= 10^7 15 | Sample Input 1: 16 | 17 | 3 18 | 19 | Sample Output 1: 20 | 21 | 15 22 | 23 | Sample Input 2: 24 | 25 | 4 26 | 27 | Sample Output 2: 28 | 29 | 315 30 | 31 | */ 32 | 33 | #include 34 | #define mod 1000000007 35 | using namespace std; 36 | 37 | int binaryTreesOfHeightH(int h) { 38 | // Write your code here 39 | 40 | vector dp(h+1); 41 | 42 | dp[1]=1; 43 | dp[2]=3; 44 | 45 | if(h==1 || h==2) 46 | return dp[h]; 47 | 48 | for(int i=3;i<=h;i++){ 49 | dp[i]=((dp[i-1]%mod)*(dp[i-1]%mod))%mod+(2*(dp[i-2]%mod)*(dp[i-1]%mod))%mod; 50 | } 51 | return dp[h]; 52 | 53 | } 54 | 55 | 56 | int main() { 57 | int h; 58 | cin >> h; 59 | int ans = binaryTreesOfHeightH(h); 60 | ans = ans % ((int)(pow(10, 9)) + 7); 61 | cout << ans << endl; 62 | } 63 | -------------------------------------------------------------------------------- /Recursion -2/Increasing Numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, print all n digit increasing numbers in increasing order in one line. 3 | Numbers you need to print should be in increasing order and only those numbers should be printed which have digits in increasing order. 4 | Input Format : 5 | 6 | Integer n 7 | 8 | Output Format : 9 | 10 | Numbers in increasing order 11 | 12 | Constraints : 13 | 1 <= n <= 8 14 | Sample Input : 15 | 16 | 2 17 | 18 | Sample Output : 19 | 20 | 12 13 14 15 16 17 18 19 23 24 25 26 27 28 29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89 21 | */ 22 | 23 | #include 24 | using namespace std; 25 | 26 | void helper(int number,int x,int k){ 27 | if(k==0){ 28 | cout< 50 | using namespace std; 51 | #include "solution.h" 52 | 53 | int main() 54 | { 55 | int n; 56 | cin>>n; 57 | printIncreasingNumbers(n); 58 | } 59 | -------------------------------------------------------------------------------- /DP (1D)/Tetrahedron.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a tetrahedron with verticies A, B, C and D. An ant is standing at vertex D. The ant won't sit idle. 3 | It will keep on moving from one vertex to another along some edge of the tetrahedron. Your task is to count 4 | the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, 5 | you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. 6 | As the number can be quite large, you should print it modulo 1000000007 (10^9 + 7). 7 | 8 | 9 | Input Format : 10 | 11 | Line 1 : Integer n (1 ≤ n ≤ 10^5) — the required length of the cyclic path 12 | 13 | Output Format : 14 | 15 | Return the only integer - the required number of ways modulo 1000000007 (10^9 + 7) 16 | 17 | Sample Input : 18 | 19 | 2 20 | 21 | Sample Output : 22 | 23 | 3 24 | 25 | 26 | */ 27 | 28 | #define MOD 1000000007 29 | 30 | long long solve(int n) 31 | { 32 | // Write your code here. 33 | long long zB=1; 34 | 35 | long long zADC=0; 36 | 37 | for(int i=1;i<=n;i++) 38 | { 39 | long long nzB=(zADC*3)%MOD; 40 | long long nzADC= ((zADC*2)%MOD+zB%MOD)%MOD; 41 | 42 | zB=nzB; 43 | zADC=nzADC; 44 | 45 | } 46 | return zB; 47 | } -------------------------------------------------------------------------------- /Recursion -2/Replace Character Recursively.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | Do this recursively. 4 | Input Format : 5 | 6 | Line 1 : Input String S 7 | Line 2 : Character c1 and c2 (separated by space) 8 | 9 | Output Format : 10 | 11 | Updated string 12 | 13 | Constraints : 14 | 1 <= Length of String S <= 10^6 15 | Sample Input : 16 | 17 | abacd 18 | a x 19 | 20 | Sample Output : 21 | 22 | xbxcd 23 | */ 24 | void replaceCharacter(char input[], char c1, char c2) { 25 | /* Don't write main(). 26 | * Don't read input, it is passed as function argument. 27 | * No need to print or return the output. 28 | * Change in the given input string itself. 29 | * Taking input and printing output is handled automatically. 30 | */ 31 | if(input[0]=='\0') 32 | return; 33 | 34 | input[0]=(input[0]==c1)?c2:input[0]; 35 | replaceCharacter(input+1,c1,c2); 36 | } 37 | #include 38 | using namespace std; 39 | #include "Solution.h" 40 | 41 | int main() { 42 | char input[1000000]; 43 | char c1, c2; 44 | cin >> input; 45 | cin >> c1 >> c2; 46 | replaceCharacter(input, c1, c2); 47 | cout << input << endl; 48 | } 49 | -------------------------------------------------------------------------------- /BinaryTrees/TakeInputPrintRecursive/BinaryTreeUse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BinaryTreeNode.h" 3 | using namespace std; 4 | 5 | void printTree(BinaryTreeNode* root) { 6 | if (root == NULL) { 7 | return; 8 | } 9 | cout << root->data << ":"; 10 | if (root->left != NULL) { 11 | cout << "L" << root->left->data; 12 | } 13 | 14 | if (root->right != NULL) { 15 | cout << "R" << root->right->data; 16 | } 17 | cout << endl; 18 | printTree(root->left); 19 | printTree(root->right); 20 | } 21 | 22 | BinaryTreeNode* takeInput() { 23 | int rootData; 24 | cout << "Enter data" << endl; 25 | cin >> rootData; 26 | if (rootData == -1) { 27 | return NULL; 28 | } 29 | 30 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 31 | BinaryTreeNode* leftChild = takeInput(); 32 | BinaryTreeNode* rightChild = takeInput(); 33 | root->left = leftChild; 34 | root->right = rightChild; 35 | return root; 36 | } 37 | 38 | int main() { 39 | /*BinaryTreeNode* root = new BinaryTreeNode(1); 40 | BinaryTreeNode* node1 = new BinaryTreeNode(2); 41 | BinaryTreeNode* node2 = new BinaryTreeNode(3); 42 | root->left = node1; 43 | root->right = node2; 44 | */ 45 | BinaryTreeNode* root = takeInput(); 46 | printTree(root); 47 | delete root; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /KMP-stringMatching.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void helperArray(char pattern[], int m, int lps[]) 4 | { 5 | int len = 0; 6 | lps[0] = 0; 7 | int i = 1; 8 | while (i < m) 9 | { 10 | if (pattern[i]==pattern[len]) 11 | { 12 | len++; 13 | lps[i] = len; 14 | i++; 15 | } 16 | else 17 | { 18 | if (len != 0) 19 | { 20 | len = lps[len - 1]; 21 | } 22 | else 23 | { 24 | lps[i] = 0; 25 | i++; 26 | } 27 | } 28 | } 29 | } 30 | void KMP(char pattern[], char text[]) 31 | { 32 | int m = strlen(pattern); 33 | int n = strlen(text); 34 | int pi[m]; 35 | helperArray(pattern, m, pi); 36 | int i = 0; 37 | int j = 0; 38 | while (i>text>>pattern; 66 | KMP(pattern, text); 67 | return 0; 68 | } 69 | 70 | //= "ABABDABACDABABCABAB"; 71 | // = "ABABCABAB"; -------------------------------------------------------------------------------- /DP (1D)/NoOf Balanced BSTs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer N, find and return the count of unique Binary search trees (BSTs) are possible with nodes valued from 1 to N. 3 | Output count can be very large, so return the count modulo 10^9+7. 4 | Input Format : 5 | 6 | Integer n 7 | 8 | Output Format : 9 | 10 | Count of BSTs 11 | 12 | Contraints : 13 | 1<= N <=1000 14 | Sample Input 1: 15 | 16 | 8 17 | 18 | Sample Output 1: 19 | 20 | 1430 21 | 22 | Sample Input 2: 23 | 24 | 3 25 | 26 | Sample Output 2: 27 | 28 | 5 29 | 30 | */ 31 | 32 | #include 33 | #define mod 1000000007 34 | using namespace std; 35 | 36 | 37 | 38 | int countBST( int n) 39 | { 40 | /* Don't write main(). 41 | * Don't read input, it is passed as function argument. 42 | * Return output and don't print it. 43 | * Taking input and printing output is handled automatically. 44 | */ 45 | vector dp(n+1); 46 | dp[0]=1; 47 | dp[1]=1; 48 | dp[2]=2; 49 | 50 | if(n==1 || n==2) 51 | return dp[n]; 52 | for(int i=3;i<=n;i++){ 53 | 54 | //Make each node root one at time 55 | for(int j=0;j<=i-1;j++){ 56 | dp[i]=((dp[i]%mod)+((int)dp[j]*(int)dp[i-1-j])%mod)%mod; 57 | } 58 | } 59 | return dp[n]%mod; 60 | 61 | } 62 | 63 | 64 | int main() 65 | { 66 | int n ; 67 | cin>>n; 68 | cout< 34 | using namespace std; 35 | 36 | bool isPermutation(char input1[], char input2[]) { 37 | // Write your code here 38 | int size1=strlen(input1),size2=strlen(input2); 39 | sort(input1,input1+size1); 40 | sort(input2,input2+size2); 41 | 42 | if(!strcmp(input1,input2)) 43 | return true; 44 | else 45 | return false; 46 | 47 | } 48 | 49 | #include 50 | using namespace std; 51 | #include "solution.h" 52 | 53 | int main() { 54 | char input1[1000], input2[1000]; 55 | cin.getline(input1, 1000); 56 | cin.getline(input2, 1000); 57 | if(isPermutation(input1, input2) == 1) { 58 | cout << "true"; 59 | } 60 | else { 61 | cout << "false"; 62 | } 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Recursion -2/Generate All Parathenses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate and print all combinations of well-formed parentheses. That is, you need to generate all possible valid set of parenthesis that can be formed with given number of pairs. 3 | Input format : 4 | 5 | Integer n 6 | 7 | Output format : 8 | 9 | Print all possible valid parenthesis in different lines 10 | 11 | Note: Order in which different combinations of well-formed parentheses are printed in different lines doesn't matter. 12 | Constraints : 13 | 1 <= n <= 10 14 | Sample Input : 15 | 16 | 3 17 | 18 | Sample Output : 19 | 20 | ((())) 21 | (()()) 22 | (())() 23 | ()(()) 24 | ()()() 25 | 26 | */ 27 | 28 | 29 | void help(int pos,int n ,int open, int close){ 30 | static char str[1000]; 31 | 32 | if(close==n){ 33 | cout<close){ 38 | str[pos]=')'; 39 | help(pos+1,n,open,close+1); 40 | } 41 | if(open 57 | using namespace std; 58 | #include "solution.h" 59 | 60 | int main() { 61 | int n; 62 | cin >> n; 63 | printWellFormedParanthesis(n); 64 | } 65 | -------------------------------------------------------------------------------- /Priority Queues/CheckMaxHeap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, check whether it represents max-heap or not. 3 | Return true or false. 4 | Input Format : 5 | 6 | Line 1 : An integer N i.e. size of the array 7 | Line 2 : N integers which are elements of the array, separated by spaces 8 | 9 | Output Format : 10 | 11 | true if it represents max-heap and false if it is not a max-heap 12 | 13 | Constraints : 14 | 1 <= N <= 10^5 15 | 1 <= Ai <= 10^5 16 | */ 17 | 18 | 19 | bool checkMaxHeap(int arr[], int n){ 20 | /* Don't write main(). 21 | * Don't read input, it is passed as function argument. 22 | * Taking input and printing output is handled automatically. 23 | */ 24 | 25 | int p=0; 26 | int lc=1; 27 | int rc=2; 28 | while(lc 45 | using namespace std; 46 | 47 | int main() { 48 | int n; 49 | cin>>n; 50 | int *arr = new int[n]; 51 | for(int i=0; i> arr[i]; 53 | } 54 | bool ans = checkMaxHeap(arr, n); 55 | if(ans){ 56 | cout << "true" << endl; 57 | } 58 | else{ 59 | cout << "false" << endl; 60 | } 61 | 62 | delete [] arr; 63 | } 64 | -------------------------------------------------------------------------------- /Arrays & Strings/Reverse Word Wise.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse the given string word wise. That is, the last word in given string should come at 1st place, last second word at 2nd place and so on. Individual words should remain as it is. 3 | Sample Input: 4 | 5 | Welcome to Coding Ninjas 6 | 7 | Sample Output: 8 | 9 | Ninjas Coding to Welcome 10 | 11 | 12 | */ 13 | 14 | // input - given string 15 | // You need to update in the given string itself. No need to print or return anything 16 | #include 17 | using namespace std; 18 | void reverseStringWordWise(char input[]) { 19 | // Write your code here 20 | vector words; 21 | string word=""; 22 | 23 | int size=strlen(input); 24 | for(int i=0;i<=size;i++){ 25 | 26 | if(input[i]!=' ' && input[i]!='\0') 27 | word+=input[i]; 28 | else{ 29 | words.push_back(word); 30 | word=""; 31 | } 32 | } 33 | 34 | reverse(words.begin(),words.end()); 35 | 36 | string ans=""; 37 | for(int i=0;i 49 | #include "solution.h" 50 | using namespace std; 51 | 52 | int main() { 53 | char input[1000]; 54 | cin.getline(input, 1000); 55 | reverseStringWordWise(input); 56 | cout << input << endl; 57 | } 58 | -------------------------------------------------------------------------------- /Stack&Queue/MinBracketReversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string expression which consists only ‘}’ and ‘{‘. The expression may not be balanced. 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 | 6 | String S 7 | 8 | Output Format : 9 | 10 | Required count 11 | 12 | Sample Input 1 : 13 | 14 | {{{ 15 | 16 | Sample Output 1 : 17 | 18 | -1 19 | 20 | Sample Input 2 : 21 | 22 | {{{{}} 23 | 24 | Sample Output 2 : 25 | 26 | 1 27 | 28 | */ 29 | 30 | 31 | #include 32 | using namespace std; 33 | int countBracketReversals(char input[]){ 34 | // Write your code here 35 | stack s; 36 | for(int i=0;input[i]!='\0';i++){ 37 | if(input[i]=='{') 38 | s.push('{'); 39 | else{ 40 | if(!s.empty() && s.top()=='{') 41 | s.pop(); 42 | else 43 | s.push('}'); 44 | } 45 | } 46 | int c=s.size(); 47 | //cout< 69 | 70 | int main() { 71 | char input[10000]; 72 | cin >> input; 73 | cout << countBracketReversals(input) << endl; 74 | } -------------------------------------------------------------------------------- /Arrays & Strings/Break Words.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a sentence contained in given string S. Write a function which will replace all the words within the sentence whose length is even and greater than equal to 4, with a space between the two equal halves of the word. 3 | Space complexity should be O(1). 4 | Input Format : 5 | 6 | String S 7 | 8 | Output Format : 9 | 10 | Updated string 11 | 12 | Constraints : 13 | 1 <= Length of S <= 10000 14 | Sample Input : 15 | 16 | Helloo world good morniing 17 | 18 | Sample Output : 19 | 20 | Hel loo world go od morn iing 21 | 22 | 23 | */ 24 | 25 | #include 26 | using namespace std; 27 | 28 | void splitWord(string &word){ 29 | int mid=word.size()/2; 30 | word.insert(mid," "); 31 | } 32 | 33 | void breakWords(char* S) 34 | { 35 | /* 36 | * Don't write main. 37 | * Don't return or print anything. 38 | * Changes should be done in the given string. 39 | */ 40 | string ans=""; 41 | string word=""; 42 | for(int i=0;S[i]!='\0';i++){ 43 | 44 | if(S[i]!=' ' && S[i]!='\0') 45 | word+=S[i]; 46 | else{ 47 | if (word.size()>=4 && word.size()%2==0){ 48 | splitWord(word); 49 | } 50 | ans+=word+" "; 51 | word=""; 52 | } 53 | } 54 | strcpy(S,ans.c_str()); 55 | 56 | } 57 | 58 | 59 | #include 60 | #include 61 | using namespace std; 62 | #include"solution.h" 63 | int main() 64 | { 65 | char str[100000]; 66 | cin.getline(str,100000); 67 | breakWords(str); 68 | cout< 36 | #include 37 | #include 38 | using namespace std; 39 | 40 | int minDistance(int arr[],int n){ 41 | /* Don't write main(). 42 | * Don't read input, it is passed as function argument. 43 | * Return output and don't print it. 44 | * Taking input and printing output is handled automatically. 45 | */ 46 | unordered_map m; 47 | 48 | int mindup=INT_MAX; 49 | for(int i=0;i 63 | #include 64 | using namespace std; 65 | #include "solution.h" 66 | 67 | int main() { 68 | int n=0; 69 | cin>>n; 70 | int *arr = new int[n]; 71 | for(int i=0;i>arr[i]; 73 | } 74 | 75 | cout << minDistance(arr,n); 76 | 77 | 78 | } 79 | -------------------------------------------------------------------------------- /MaxSumFromAnyNodetoAnyNode.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | ///for trees 7 | #include 8 | using namespace std; 9 | class node{ 10 | public: 11 | node* left; 12 | node* right; 13 | int data; 14 | 15 | node(int d) 16 | { 17 | left=NULL; 18 | right=NULL; 19 | data=d; 20 | } 21 | }; 22 | 23 | class pairr{ 24 | public: 25 | int branchsum; 26 | int maxsum; 27 | 28 | pairr(){ 29 | branchsum=0; 30 | maxsum=0; 31 | } 32 | }; 33 | 34 | pairr MaxSumPath(node* root) 35 | { 36 | pairr p; 37 | if(root==NULL) 38 | { 39 | return p; 40 | } 41 | pairr left = MaxSumPath(root->left); 42 | pairr right = MaxSumPath(root->right); 43 | 44 | //construct two values 45 | int op1 = root->data; 46 | int op2 = left.branchsum + root->data; 47 | int op3 = left.branchsum + right.branchsum + root->data; 48 | int op4 = right.branchsum + root->data; 49 | 50 | int curr_ans_through_root = max(op1,op2,op3,op4); 51 | 52 | //BRANCH SUM 53 | t.branchsum = (max(left.branchsum,right,branchsum,0))+root->data; 54 | 55 | p.maxsum = max(left.maxsum,right.maxsum,curr_ans_through_root); 56 | 57 | 58 | } 59 | 60 | node* buildtree(){ 61 | int d; 62 | cin>>d; 63 | if(d==-1) 64 | { 65 | return NULL; 66 | } 67 | node* root = new node(d); 68 | root->left = buildtree(); 69 | root->right=buildtree(); 70 | 71 | return root; 72 | } 73 | 74 | int main() 75 | { 76 | node* root=buildtree(); 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /DP (2D)/ShortestUncommenSubsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | Note: input data will be such so there will always be a solution. 4 | Input Format : 5 | 6 | Line 1 : String S of length N (1 <= N <= 1000) 7 | Line 2 : String V of length M (1 <= M <= 1000) 8 | 9 | Output Format : 10 | 11 | Length of shortest subsequence in S such that it is not a subsequence in V 12 | 13 | Sample Input : 14 | 15 | babab 16 | babba 17 | 18 | Sample Output : 19 | 20 | 3 21 | 22 | 23 | */ 24 | 25 | 26 | #include 27 | using namespace std; 28 | 29 | int ss(vector < vector > &dp,string s,string v){ 30 | 31 | if(s.size()==0) 32 | return 1550; 33 | 34 | if(v.size()<=0) 35 | return 1; 36 | 37 | if(dp[s.size()][v.size()]) 38 | return dp[s.size()][v.size()]; 39 | int i; 40 | for(i=0;i > dp(S.size()+1,vector(V.size()+1,0)); 62 | int ans=ss(dp,S,V); 63 | 64 | return ans; 65 | 66 | } 67 | 68 | int main() 69 | { 70 | string S,V; 71 | cin>>S>>V; 72 | cout< 57 | #include "solution.h" 58 | using namespace std; 59 | 60 | int main(){ 61 | int N; 62 | cin>>N; 63 | cout< 27 | using namespace std; 28 | 29 | void stringCompression(char input[]) { 30 | // Write your code here 31 | string ans=""; 32 | 33 | for(int i=0;input[i]!=0;){ 34 | int j=i+1; 35 | while(input[i]==input[j]){ 36 | j++; 37 | } 38 | int c=j-i; 39 | //cout< 56 | #include "solution.h" 57 | using namespace std; 58 | 59 | int main() { 60 | char input[1000]; 61 | cin.getline(input, 1000); 62 | stringCompression(input); 63 | cout << input << endl; 64 | } 65 | -------------------------------------------------------------------------------- /Recursion -1/First_Index_of_Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of length N and an integer x, you need to find and return the first index of integer x present in the array. Return -1 if it is not present in the array. 3 | First index means, the index of first occurrence of x in the input array. 4 | Do this recursively. Indexing in the array starts from 0. 5 | Input Format : 6 | 7 | Line 1 : An Integer N i.e. size of array 8 | Line 2 : N integers which are elements of the array, separated by spaces 9 | Line 3 : Integer x 10 | 11 | Output Format : 12 | 13 | first index or -1 14 | 15 | Constraints : 16 | 1 <= N <= 10^3 17 | Sample Input : 18 | 19 | 4 20 | 9 8 10 8 21 | 8 22 | 23 | Sample Output : 24 | 25 | 1 26 | */ 27 | 28 | int firstIndex(int input[], int size, int x) { 29 | /* Don't write main(). 30 | Don't read input, it is passed as function argument. 31 | Return output and don't print it. 32 | Taking input and printing output is handled automatically. 33 | */ 34 | if (size==0) 35 | return -1; 36 | 37 | if(input[0]==x) 38 | return 0; 39 | 40 | int fIndex=firstIndex(input+1,size-1,x); 41 | 42 | if(fIndex==-1) 43 | return -1; 44 | else{ 45 | return fIndex+1; 46 | } 47 | 48 | } 49 | 50 | #include 51 | #include "Solution.h" 52 | using namespace std; 53 | 54 | 55 | int main(){ 56 | int n; 57 | cin >> n; 58 | 59 | int *input = new int[n]; 60 | 61 | for(int i = 0; i < n; i++) { 62 | cin >> input[i]; 63 | } 64 | 65 | int x; 66 | 67 | cin >> x; 68 | 69 | cout << firstIndex(input, n, x) << endl; 70 | 71 | } 72 | 73 | 74 | -------------------------------------------------------------------------------- /Recursion -2/Print Keypad Combination Code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, using phone keypad find out and print all the possible strings that can be made using digits of input n. 3 | Note : The order of strings are not important. Just print different strings in new lines. 4 | Input Format : 5 | 6 | Integer n 7 | 8 | Output Format : 9 | 10 | All possible strings in different lines 11 | 12 | Constraints : 13 | 1 <= n <= 10^6 14 | Sample Input: 15 | 16 | 23 17 | 18 | Sample Output: 19 | 20 | ad 21 | ae 22 | af 23 | bd 24 | be 25 | bf 26 | cd 27 | ce 28 | cf 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | using namespace std; 35 | 36 | string dial(int key){ 37 | unordered_mapm; 38 | m[0]=""; 39 | m[1]=""; 40 | m[2]="abc"; 41 | m[3]="def"; 42 | m[4]="ghi"; 43 | m[5]="jkl"; 44 | m[6]="mno"; 45 | m[7]="pqrs"; 46 | m[8]="tuv"; 47 | m[9]="wxyz"; 48 | return m[key]; 49 | } 50 | void pK(int num,string out){ 51 | 52 | if(num==0){ 53 | cout< 71 | #include 72 | #include "solution.h" 73 | using namespace std; 74 | 75 | int main(){ 76 | int num; 77 | cin >> num; 78 | 79 | printKeypad(num); 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /Arrays & Strings/Print Like a Wave.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a two dimensional n*m array, print the array in a sine wave order. i.e. print the first column top to bottom, next column bottom to top and so on. 3 | Note : Print the elements separated by space. 4 | Input format : 5 | 6 | n, m, array elements (separated by space) 7 | 8 | Sample Input : 9 | 10 | 3 4 1 2 3 4 5 6 7 8 9 10 11 12 11 | 12 | Sample Output : 13 | 14 | 1 5 9 10 6 2 3 7 11 12 8 4 15 | 16 | 17 | */ 18 | #include 19 | using namespace std; 20 | 21 | void wavePrint(int input[][1000], int row, int col){ 22 | /* Don't write main(). 23 | * Don't read input, it is passed as function argument. 24 | * Print output and don't return it. 25 | * Taking input is handled automatically. 26 | */ 27 | int flagdown=1; 28 | int k=1; 29 | int r1=0; 30 | while(k<=row*col){ 31 | if(flagdown){ 32 | for(int i=0;i=0;i--){ 41 | k++; 42 | cout< 53 | #include "solution.h" 54 | using namespace std; 55 | 56 | int main() { 57 | int input[1500][1000]; 58 | int row, col; 59 | cin >> row >> col; 60 | 61 | for(int i = 0; i < row; i++) { 62 | for(int j = 0; j < col; j++) { 63 | cin >> input[i][j]; 64 | } 65 | } 66 | wavePrint(input, row, col); 67 | } -------------------------------------------------------------------------------- /Backtracking/NoOf Number with Duplicates.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a number n, find number of numbers that are greater than n using the same set of digits as n. n might have duplicate digits. 3 | Input Format : 4 | 5 | Integer n 6 | 7 | Output Format : 8 | 9 | Count of greater numbers 10 | 11 | Sample Input : 12 | 13 | 122 14 | 15 | Sample Output : 16 | 17 | 2 18 | 19 | */ 20 | 21 | #include 22 | using namespace std; 23 | 24 | 25 | 26 | long NON(deque &digarr,vector &freq,vector &fact,int n,int start){ 27 | if(n==0 || n==1) 28 | return 0; 29 | 30 | long ans=0; 31 | long denom=1; 32 | for(int i=1;i<=9;i++){ 33 | denom*=fact[freq[i]]; 34 | } 35 | for(int i=digarr[start]+1;i<=9;i++){ 36 | 37 | ans+=(fact[n-1]*freq[i])/denom; 38 | } 39 | 40 | freq[digarr[start]]--; 41 | ans+=NON(digarr,freq,fact,n-1,start+1); 42 | return ans; 43 | } 44 | 45 | long numberOfNumbersWithDuplicates(long num){ 46 | // Write your code here 47 | 48 | deque digarr; 49 | vector freq(10); 50 | vector fact; 51 | 52 | fact.push_back(1); //0! and 1!=1 53 | fact.push_back(1); 54 | while(num!=0){ 55 | long d=num%10; 56 | 57 | int i=fact.size(); 58 | freq[d]++; 59 | fact.push_back(fact[i-1]*i); 60 | digarr.push_front(d); 61 | 62 | num/=10; 63 | } 64 | long ans=NON(digarr,freq,fact,digarr.size(),0); 65 | 66 | return ans; 67 | 68 | 69 | } 70 | 71 | 72 | int main() { 73 | long n; 74 | cin >> n; 75 | cout << numberOfNumbersWithDuplicates(n) << endl; 76 | } -------------------------------------------------------------------------------- /Recursion -1/Last Index of Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array. 3 | Last index means - if x is present multiple times in the array, return the index at which x comes last in the array. 4 | You should start traversing your array from 0, not from (N - 1). 5 | Do this recursively. Indexing in the array starts from 0. 6 | Input Format : 7 | 8 | Line 1 : An Integer N i.e. size of array 9 | Line 2 : N integers which are elements of the array, separated by spaces 10 | Line 3 : Integer x 11 | 12 | Output Format : 13 | 14 | last index or -1 15 | 16 | Constraints : 17 | 1 <= N <= 10^3 18 | Sample Input : 19 | 20 | 4 21 | 9 8 10 8 22 | 8 23 | 24 | Sample Output : 25 | 26 | 3 27 | */ 28 | 29 | int lastIndex(int input[], int size, int x) { 30 | /* Don't write main(). 31 | Don't read input, it is passed as function argument. 32 | Return output and don't print it. 33 | Taking input and printing output is handled automatically. 34 | */ 35 | if(size==0) 36 | return -1; 37 | if(input[size-1]==x) 38 | return size-1; 39 | int lIndex=lastIndex(input,size-1,x); 40 | 41 | return lIndex; 42 | 43 | } 44 | 45 | #include 46 | #include "Solution.h" 47 | using namespace std; 48 | 49 | 50 | int main(){ 51 | int n; 52 | cin >> n; 53 | 54 | int *input = new int[n]; 55 | 56 | for(int i = 0; i < n; i++) { 57 | cin >> input[i]; 58 | } 59 | 60 | int x; 61 | 62 | cin >> x; 63 | 64 | cout << lastIndex(input, n, x) << endl; 65 | 66 | } 67 | 68 | 69 | -------------------------------------------------------------------------------- /DP (2D)/MinCostPath.cpp: -------------------------------------------------------------------------------- 1 | /*Min Cost Path problem */ 2 | 3 | #include 4 | using namespace std; 5 | 6 | int min_cost2(int** input, int m, int n) { 7 | int ** dp = new int*[m]; 8 | for (int i = 0; i < m; i++) { 9 | dp[i] = new int[n]; 10 | } 11 | dp[m - 1][n-1] = input[m-1][n-1]; 12 | for (int i = m - 2; i >= 0; i--) { 13 | dp[i][n -1] = dp[i + 1][n-1] + input[i][n-1]; 14 | } 15 | 16 | for (int j = n - 2; j >=0; j--) { 17 | dp[m -1][j] = dp[m - 1][j + 1] + input[m-1][j]; 18 | } 19 | 20 | for (int i = m - 2; i >=0; i--) { 21 | for (int j = n - 2; j >=0 ; j--) { 22 | dp[i][j] = input[i][j] + min(dp[i+1][j], min(dp[i+1][j+1], dp[i][j + 1])); 23 | } 24 | } 25 | return dp[0][0]; 26 | } 27 | 28 | int min_cost(int** input, int si, int sj, int ei, int ej) { 29 | if (si == ei && sj == ej) { 30 | return input[ei][ej]; 31 | } 32 | if (si > ei || sj > ej) { 33 | return INT_MAX; 34 | } 35 | int option1 = min_cost(input, si + 1, sj, ei, ej); 36 | int option2 = min_cost(input, si + 1, sj + 1, ei, ej); 37 | int option3 = min_cost(input, si, sj + 1, ei, ej); 38 | return input[si][sj] + min(option1, min(option2, option3)); 39 | } 40 | 41 | int main() { 42 | int ** input = new int*[3]; 43 | input[0] = new int[3]; 44 | input[1] = new int[3]; 45 | input[2] = new int[3]; 46 | input[0][0] = 4; 47 | input[0][1] = 3; 48 | input[0][2] = 2; 49 | input[1][0] = 1; 50 | input[1][1] = 8; 51 | input[1][2] = 3; 52 | input[2][0] = 1; 53 | input[2][1] = 1; 54 | input[2][2] = 8; 55 | 56 | cout << min_cost(input, 0,0,2,2) << endl; 57 | cout << min_cost2(input,3,3) << endl; 58 | delete [] input[0]; 59 | delete [] input[1]; 60 | delete [] input[2]; 61 | delete [] input; 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Priority Queues/KSmallestElements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given with an integer k and an array of integers that contain numbers in random order. Write a program to find k smallest 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 | Order of elements in the output is not important. 5 | Input Format : 6 | 7 | Line 1 : Size of array (n) 8 | Line 2 : Array elements (separated by space) 9 | Line 3 : Integer k 10 | 11 | Output Format : 12 | 13 | k smallest elements 14 | 15 | Sample Input 1 : 16 | 17 | 13 18 | 2 12 9 16 10 5 3 20 25 11 1 8 6 19 | 4 20 | 21 | Sample Output 1 : 22 | 23 | 5 24 | 3 25 | 2 26 | 1 27 | 28 | */ 29 | 30 | 31 | #include 32 | using namespace std; 33 | 34 | 35 | vector kSmallest(int *input, int n, int k) { 36 | // Write your code here 37 | priority_queue pq; 38 | vector ans; 39 | 40 | for(int i=0;i 59 | using namespace std; 60 | #include 61 | 62 | int main() { 63 | int n; 64 | cin >> n; 65 | int *input = new int[n]; 66 | for(int i = 0; i < n; i++){ 67 | cin >> input[i]; 68 | } 69 | int k; 70 | cin >> k; 71 | vector output = kSmallest(input, n, k); 72 | for(int i = 0; i < output.size(); i++){ 73 | cout << output[i] << endl; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Arrays & Strings/Pallindrome Substrings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, count and return the number of substrings of S that are palindrome. 3 | Single length substrings are also palindromes. You just need to calculate the count, not the substrings. 4 | Input Format : 5 | 6 | String S 7 | 8 | Output Format : 9 | 10 | count of palindrome substrings 11 | 12 | Constraints : 13 | 1 <= Length of S <= 1000 14 | Sample Input : 15 | 16 | aba 17 | 18 | Sample Output : 19 | 20 | 4 21 | 22 | **Note : Here 4 corresponds to ("a","b","a","aba"). 23 | 24 | */ 25 | 26 | #include 27 | using namespace std; 28 | 29 | 30 | int countPalindromeSubstrings(char s[]) { 31 | // Write your code here 32 | string st(s); 33 | int c=0; 34 | 35 | //First Considering palindroms odd case 36 | for(int i=0;i=0 && i+k=0 && i+1+k 67 | #include "solution.h" 68 | using namespace std; 69 | 70 | int main() { 71 | char input[10000]; 72 | cin >> input; 73 | cout << countPalindromeSubstrings(input) << endl; 74 | } 75 | -------------------------------------------------------------------------------- /Priority Queues/KthLargest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of random integers and an integer k, find and return the kth largest element in the array. 3 | Try to do this question in less than O(nlogn) time. 4 | Input Format : 5 | 6 | Line 1 : An integer N i.e. size of the array 7 | Line 2 : N integers which are elements of the array, separated by spaces 8 | Line 3 : An integer k 9 | 10 | Output Format : 11 | 12 | kth largest element 13 | 14 | Input Constraints : 15 | 1 <= N, Ai, k <= 10^5 16 | Sample Input 1 : 17 | 18 | 6 19 | 9 4 8 7 11 3 20 | 2 21 | 22 | Sample Output 1 : 23 | 24 | 9 25 | 26 | Sample Input 2 : 27 | 28 | 8 29 | 2 6 10 11 13 4 1 20 30 | 4 31 | 32 | Sample Output 2 : 33 | 34 | 10 35 | 36 | */ 37 | 38 | #include 39 | #include 40 | using namespace std; 41 | 42 | int kthLargest (vector arr, int n, int k){ 43 | /* Don't write main(). 44 | * Don't read input, it is passed as function argument. 45 | * Return output and don't print it. 46 | * Taking input and printing output is handled automatically. 47 | */ 48 | priority_queue,greater > pq; 49 | 50 | for(int i=0;ipq.top()){ 56 | pq.pop(); 57 | pq.push(arr[i]); 58 | } 59 | } 60 | while(pq.size()==1){ 61 | pq.pop(); 62 | } 63 | return pq.top(); 64 | 65 | } 66 | 67 | 68 | 69 | 70 | int main(){ 71 | int n, k, s; 72 | vector arr; 73 | cin>>n; 74 | for(int i = 0; i < n; i++){ 75 | cin>>s; 76 | arr.push_back(s); 77 | } 78 | cin >> k; 79 | cout << kthLargest(arr, n, k) << endl; 80 | } 81 | -------------------------------------------------------------------------------- /DP (1D)/Loot Houses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | Input Format 4 | 5 | Line 1 : An integer N 6 | Line 2 : N spaced integers denoting money in each house 7 | 8 | Output Format 9 | 10 | Line 1 : Maximum amount of money looted 11 | 12 | Input Constraints 13 | 14 | 1 <= n <= 10^4 15 | 1 <= A[i] < 10^4 16 | 17 | Sample Input : 18 | 19 | 6 20 | 5 5 10 100 10 5 21 | 22 | Sample Output 1 : 23 | 24 | 110 25 | 26 | */ 27 | 28 | #include 29 | using namespace std; 30 | int getMaxMoney(int arr[], int n){ 31 | 32 | /*Write your code here. 33 | *Don’t write main(). 34 | *Don’t take input, it is passed as function argument. 35 | *Don’t print output. 36 | *Taking input and printing output is handled automatically. 37 | */ 38 | 39 | /* 40 | The logic would be to understand that for a ith house from left, the theief has two options 41 | 1) Either steal from ith house and add its loot to his optimal looting of i-2 houses 42 | 2) Don't steal from ith house, and hence keep his optimal looting for i-1 houses 43 | */ 44 | // setting dp[0]=0 base case 45 | vector dp(n+1,0); 46 | 47 | //Bottom up dp 48 | //If there is only 1 house 49 | dp[1]=arr[0]; 50 | if (n==1) 51 | return arr[0]; 52 | for(int i=2;i<=n;i++){ 53 | 54 | dp[i]=max(arr[i-1]+dp[i-2],dp[i-1]); 55 | } 56 | return dp[n]; 57 | 58 | 59 | } 60 | 61 | int main(){ 62 | int n; 63 | cin >> n; 64 | int arr[10000]; 65 | for(int i=0; i> arr[i]; 67 | } 68 | cout << getMaxMoney(arr, n); 69 | } 70 | -------------------------------------------------------------------------------- /DP (1D)/Boredom.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Gary is bored and wants to play an interesting but tough game . So he figured out a new board game called "destroy the neighbours" . In this game there are N integers on a board. In one move, he can pick any integer x from the board and then all the integers with value x+1 or x-1 gets destroyed .This move will give him x points. 3 | He plays the game until the board becomes empty . But as he want show this game to his friend Steven, he wants to learn techniques to maximise the points to show off . Can you help Gary in finding out the maximum points he receive grab from the game ? 4 | Input Format : 5 | 6 | Line 1 : Integer N 7 | Line 2 : A list of N integers 8 | 9 | Output Format : 10 | 11 | Maximum points Gary can recieve from the Game setup 12 | 13 | Constraints : 14 | 1<=N<=10^5 15 | 1<=A[i]<=1000 16 | Sample Input : 17 | 18 | 2 19 | 1 2 20 | 21 | Sample Output : 22 | 23 | 2 24 | */ 25 | 26 | #include 27 | using namespace std; 28 | 29 | 30 | int solve(int n,vectorA){ 31 | /* Don't write main(). 32 | Don't read input, it is passed as function argument. 33 | Return output and don't print it. 34 | Taking input and printing output is handled automatically. 35 | */ 36 | if(n==1) 37 | return A[0]; 38 | vector dp(1001); 39 | 40 | unordered_map f; 41 | for(int i=0;iA; 55 | int main() 56 | { 57 | cin>>n; 58 | for(int i=0;i>x; 62 | A.push_back(x); 63 | } 64 | cout< 25 | #include 26 | using namespace std; 27 | bool checkBalanced(char *exp) { 28 | // Write your code here 29 | stack c; 30 | 31 | for(int i=0;exp[i]!='\0';i++){ 32 | 33 | if(exp[i]=='{' || exp[i]=='[' || exp[i]=='(') 34 | c.push(exp[i]); 35 | 36 | if(exp[i]=='}'){ 37 | if(!c.empty() && c.top()=='{') 38 | c.pop(); 39 | else 40 | return false; 41 | } 42 | if(exp[i]==']'){ 43 | if(!c.empty() && c.top()=='[') 44 | c.pop(); 45 | else 46 | return false; 47 | } 48 | if(exp[i]==')'){ 49 | if(!c.empty() && c.top()=='(') 50 | c.pop(); 51 | else 52 | return false; 53 | } 54 | } 55 | if(!c.empty()) 56 | return false; 57 | return true; 58 | 59 | } 60 | 61 | int main() { 62 | char input[100000]; 63 | cin.getline(input, 100000); 64 | // cin >> input; 65 | if(checkBalanced(input)) { 66 | cout << "true" << endl; 67 | } 68 | else { 69 | cout << "false" << endl; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Backtracking/PrintSubsetsOfArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array (of length n), find and print all the subsets of input array. 3 | 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. 4 | Note : The order of subsets are not important. Just print the subsets in different lines. 5 | Input format : 6 | 7 | Line 1 : Integer n, Size of array 8 | Line 2 : Array elements (separated by space) 9 | 10 | Constraints : 11 | 1 <= n <= 15 12 | Sample Input: 13 | 14 | 3 15 | 15 20 12 16 | 17 | Sample Output: 18 | 19 | [] (this just represents an empty array, don't worry about the square brackets) 20 | 12 21 | 20 22 | 20 12 23 | 15 24 | 15 12 25 | 15 20 26 | 15 20 12 27 | 28 | */ 29 | 30 | #include 31 | using namespace std; 32 | 33 | 34 | void printVector(vector &temp){ 35 | 36 | for(int i=0;i &temp){ 41 | 42 | if(n==0){ 43 | printVector(temp); 44 | return; 45 | } 46 | 47 | //First call to include the current element indicated by input[0] 48 | temp.push_back(input[0]); 49 | helper(input+1,n-1,temp); 50 | 51 | //Second call for not including the current element 52 | temp.pop_back(); 53 | helper(input+1,n-1,temp); 54 | } 55 | 56 | 57 | void printSubsetsOfArray(int input[], int size) { 58 | // Write your code here 59 | vectortemp; 60 | 61 | helper(input,size,temp); 62 | 63 | } 64 | 65 | 66 | int main() { 67 | int input[1000],length; 68 | cin >> length; 69 | for(int i=0; i < length; i++) 70 | cin >> input[i]; 71 | printSubsetsOfArray(input, length); 72 | } 73 | -------------------------------------------------------------------------------- /a4.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import pandas as pd 4 | from datetime import datetime 5 | if(len(sys.argv)==1): 6 | raise Exception("Filename should be given") 7 | for i in sys.argv[1:]: 8 | ext = os.path.splitext(i)[-1].lower() 9 | if(ext!='.csv'): 10 | raise Exception("Wrong file or file path") 11 | for i in sys.argv[1:]: 12 | try: 13 | s=open(i) 14 | except FileNotFoundError: 15 | raise Exception("File doesn't exist") 16 | for i in sys.argv[1:]: 17 | file=pd.read_csv(i) 18 | a=file.shape[-1] 19 | if(a!=2): 20 | raise Exception("File with only two column is valid") 21 | a=[] 22 | for i in sys.argv[1:]: 23 | a.append(i) 24 | result = pd.DataFrame() 25 | log=[] 26 | l=set(pd.read_csv(a[0]).iloc[:,0]) 27 | for i in a[1:]: 28 | l1=set(pd.read_csv(i).iloc[:0]) 29 | l.union(l1) 30 | l1=list(l) 31 | result['Roll No']=l1 32 | for i in a: 33 | df1 = pd.read_csv(i).fillna(0) 34 | list1 = [] 35 | num1 = list(df1.iloc[:, 1]) 36 | num2=list(df1.iloc[:,0]) 37 | for j in range(len(num1)): 38 | try: 39 | k = int(num1[j]) 40 | except: 41 | log.append([i,num2[j],num1[j]]) 42 | list1.append(j) 43 | df1.drop(index=list1, inplace=True) 44 | df1 = df1.drop_duplicates(subset=[df1.columns[0]], keep='last') 45 | s1 = pd.Series(list(df1.iloc[:, 1]), list(df1.iloc[:, 0])) 46 | b=[] 47 | for j in l1: 48 | try: 49 | c=s1[j] 50 | b.append(c) 51 | except: 52 | b.append(0) 53 | c=i.split(".") 54 | result[c[0]]=b 55 | flnm=str(datetime.now().strftime('%Y%m%d')) 56 | result.to_csv('result'+flnm+'.csv',index=False) 57 | log1=pd.DataFrame(log) 58 | log1.to_csv('log'+flnm+'.csv',index=False,header=['Filename','Roll No.','Marks']) -------------------------------------------------------------------------------- /Arrays & Strings/Leaders In Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array A of size n. Find and print all the leaders present in the input array. An array element A[i] is called Leader, if all the elements following it (i.e. present at its right) are less than or equal to A[i]. 3 | Print all the leader elements separated by space and in the same order they are present in the input array. 4 | Input Format : 5 | 6 | Line 1 : Integer n, size of array 7 | Line 2 : Array A elements (separated by space) 8 | 9 | Output Format : 10 | 11 | leaders of array (separated by space) 12 | 13 | Constraints : 14 | 1 <= n <= 10^6 15 | Sample Input 1 : 16 | 17 | 6 18 | 3 12 34 2 0 -1 19 | 20 | Sample Output 1 : 21 | 22 | 34 2 0 -1 23 | 24 | Sample Input 2 : 25 | 26 | 5 27 | 13 17 5 4 6 28 | 29 | Sample Output 2 : 30 | 31 | 17 6 32 | 33 | 34 | */ 35 | 36 | #include 37 | using namespace std; 38 | 39 | void Leaders(int* arr,int len) 40 | { 41 | /* Don't write main(). 42 | * Don't read input, it is passed as function argument. 43 | * Print your output exactly in the same format as shown. 44 | * Don't print any extra line. 45 | */ 46 | int j=len-1; 47 | vector v; 48 | for (int i=len-1;i>=0;i--){ 49 | if(i==len-1){ 50 | v.push_back(arr[i]); 51 | continue; 52 | } 53 | if(arr[i]>=arr[j]){ 54 | v.push_back(arr[i]); 55 | j=i; 56 | } 57 | } 58 | for (int i=v.size()-1;i>=0;i--){ 59 | cout< 65 | #include 66 | using namespace std; 67 | #include"solution.h" 68 | int main() 69 | { 70 | int len; 71 | cin>>len; 72 | int *arr = new int[len + 1]; 73 | 74 | for(int i=0;i>arr[i]; 77 | } 78 | Leaders(arr,len); 79 | } 80 | 81 | -------------------------------------------------------------------------------- /DP (1D)/CoinTower.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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 ? 3 | Input Format : 4 | 5 | Contains three value N,X,Y as mentioned in the problem statement 6 | 7 | Output Format : 8 | 9 | A string containing the name of the winner like “Whis” or “Beerus” (without quotes) 10 | 11 | Constraints: 12 | 13 | 1<=N<=10^6 14 | 2<=X<=Y<=50 15 | 16 | Sample Input : 17 | 18 | 4 2 3 19 | 20 | Sample Output : 21 | 22 | Whis 23 | 24 | */ 25 | 26 | 27 | #include 28 | #include 29 | #include 30 | using namespace std; 31 | 32 | int BeerusWin(vector &dp,int n,int x,int y){ 33 | if(n==1 || n==x || n==y) 34 | return 1; 35 | if(dp[n]!=-1) 36 | return dp[n]; 37 | 38 | int ans; 39 | //You'll have take care when n>x or x && n>y) 41 | ans=!BeerusWin(dp,n-1,x,y) || !BeerusWin(dp,n-x,x,y) || !BeerusWin(dp,n-y,x,y); 42 | else if(n>x && ny) 45 | ans=!BeerusWin(dp,n-1,x,y) || !BeerusWin(dp,n-y,x,y); 46 | else 47 | ans=!BeerusWin(dp,n-1,x,y); 48 | 49 | dp[n]=ans; 50 | return dp[n]; 51 | } 52 | 53 | 54 | string solve(int n, int x, int y) 55 | { 56 | // Write your code here . 57 | vector dp(n+1,-1); 58 | 59 | int ans=BeerusWin(dp,n,x,y); 60 | 61 | if(ans) 62 | return "Beerus"; 63 | else 64 | return "Whis"; 65 | } 66 | 67 | 68 | int n,x,y; 69 | int main() 70 | { 71 | cin>>n>>x>>y; 72 | cout< 2 | using namespace std; 3 | 4 | template 5 | class MapNode { 6 | public: 7 | string key; 8 | V value; 9 | MapNode* next; 10 | 11 | MapNode(string key, V value) { 12 | this->key = key; 13 | this->value = value; 14 | next = NULL; 15 | } 16 | 17 | ~MapNode() { 18 | delete next; 19 | } 20 | }; 21 | 22 | template 23 | class ourmap { 24 | MapNode** buckets; 25 | int count; 26 | int numBuckets; 27 | 28 | public: 29 | ourmap() { 30 | count = 0; 31 | numBuckets = 5; 32 | buckets = new MapNode*[numBuckets]; 33 | for (int i = 0; i < numBuckets; i++) { 34 | buckets[i] = NULL; 35 | } 36 | } 37 | 38 | ~ourmap() { 39 | for (int i = 0; i < numBuckets; i++) { 40 | delete buckets[i]; 41 | } 42 | delete [] buckets; 43 | } 44 | 45 | int size() { 46 | return count; 47 | } 48 | 49 | V getValue(string key) { 50 | 51 | } 52 | 53 | private: 54 | int getBucketIndex(string key) { 55 | int hashCode = 0; 56 | 57 | int currentCoeff = 1; 58 | for (int i = key.length() - 1; i >= 0; i--) { 59 | hashCode += key[i] * currentCoeff; 60 | hashCode = hashCode % numBuckets; 61 | currentCoeff *= 37; 62 | currentCoeff = currentCoeff % numBuckets; 63 | } 64 | 65 | return hashCode % numBuckets; 66 | } 67 | 68 | public: 69 | void insert(string key, V value) { 70 | int bucketIndex = getBucketIndex(string key); 71 | MapNode* head = buckets[bucketIndex]; 72 | while (head != NULL) { 73 | if (head->key == key) { 74 | head->value = value; 75 | return; 76 | } 77 | head = head->next; 78 | } 79 | head = buckets[bucketIndex]; 80 | MapNode* node = new MapNode(key, value); 81 | node->next = head; 82 | buckets[bucketIndex] = node; 83 | count++; 84 | } 85 | 86 | }; 87 | -------------------------------------------------------------------------------- /Stack&Queue/Sort_a_Stack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a stack, sort the elements inside that stack in ascending order using only push and pop operation. You can use one additional stack only. 3 | 4 | For eg. 5 | 6 | Input Stack : 5 (top) 7 | 4 8 | 3 9 | 2 10 | 1 11 | Output Stack : 1 (top) 12 | 2 13 | 3 14 | 4 15 | 5 16 | 17 | Input format : 18 | 19 | Line 1 : No. of elements in stack 20 | 21 | Line 2 : Stack elements (separated by space) 22 | Sample Input 23 | 24 | 5 25 | 1 2 3 4 5 26 | 27 | Sample Output 28 | 29 | 1 2 3 4 5 30 | 31 | */ 32 | 33 | #include 34 | using namespace std; 35 | void sortStack(stack &s){ 36 | // Write your code here 37 | stack temp; 38 | 39 | while(!s.empty()) 40 | { 41 | if(temp.empty()){ 42 | temp.push(s.top()); 43 | s.pop(); 44 | continue; 45 | } 46 | if(!temp.empty() && temp.top()>=s.top()){ 47 | temp.push(s.top()); 48 | s.pop(); 49 | } 50 | else{ 51 | int t=s.top(); 52 | s.pop(); 53 | 54 | while(!temp.empty() && t>temp.top()){ 55 | s.push(temp.top()); 56 | temp.pop(); 57 | } 58 | temp.push(t); 59 | } 60 | } 61 | s=temp; 62 | } 63 | #include 64 | using namespace std; 65 | 66 | int main() { 67 | stack input; 68 | int size, value; 69 | cin >> size; 70 | for(int i = 0; i < size; i++) { 71 | cin >> value; 72 | input.push(value); 73 | } 74 | sortStack(input); 75 | while(!input.empty()) { 76 | cout << input.top() << " "; 77 | input.pop(); 78 | } 79 | cout << endl; 80 | } 81 | -------------------------------------------------------------------------------- /Hashing/Zero sum Sub array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given with an array (of size N) consisting of positive and negative integers that contain numbers in random order. 3 | Write a program to return true if there exists a sub-array whose sum is zero else, return false. 4 | Input Format : 5 | 6 | Line 1 : An Integer N i.e. size of array 7 | Line 2 : N integers, elements of the array (separated by space) 8 | 9 | Output Format : 10 | 11 | true or false 12 | 13 | Constraints : 14 | 1 <= N <= 10^5 15 | Sample Input 1 : 16 | 17 | 6 18 | 7 1 3 -4 5 1 19 | 20 | Sample Output 1 : 21 | 22 | true 23 | 24 | Sample Input 2 : 25 | 26 | 5 27 | -6 7 6 2 1 28 | 29 | Sample Output 2 : 30 | 31 | false 32 | 33 | */ 34 | #include 35 | bool subArrayZeroSum(int input[], int n) { 36 | 37 | /* Don't write main(). 38 | * the input array is already passed as function argument. 39 | * Taking input and printing output is handled automatically. Return only true or false. 40 | */ 41 | vector pre; 42 | pre.push_back(input[0]); 43 | 44 | for(int i=1;i m; 49 | 50 | for(int i=0;i 61 | using namespace std; 62 | #include "solution.h" 63 | 64 | int main() 65 | { 66 | int n; 67 | int input[100000]; 68 | cin>>n; 69 | for(int i=0; i>input[i]; 72 | } 73 | bool val = subArrayZeroSum(input, n); 74 | if(val) 75 | { 76 | cout<<"true"; 77 | } 78 | else 79 | { 80 | cout<<"false"; 81 | } 82 | return 0; 83 | } 84 | 85 | -------------------------------------------------------------------------------- /Graphs/LargestPiece.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Its Gary's birthday today and he has ordered his favourite square cake consisting of '0's and '1's . 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. Given the size of cake N and the cake , can you find the size of the biggest piece of '1's for Gary ? 3 | Constraints : 4 | 1<=N<=50 5 | Input Format : 6 | 7 | Line 1 : An integer N denoting the size of cake 8 | Next N lines : N characters denoting the cake 9 | 10 | Output Format : 11 | 12 | Size of the biggest piece of '1's and no '0's 13 | 14 | Sample Input : 15 | 16 | 2 17 | 11 18 | 01 19 | 20 | Sample Output : 21 | 22 | 3 23 | 24 | */ 25 | 26 | void dfs(char cake[NMAX][NMAX],int n,int &k,int i,int j){ 27 | k++; 28 | cake[i][j]='0'; 29 | 30 | if(i+1=0 && cake[i-1][j]=='1') 33 | dfs(cake,n,k,i-1,j); 34 | if(j+1=0 && cake[i][j-1]=='1') 37 | dfs(cake,n,k,i,j-1); 38 | 39 | } 40 | 41 | int solve(int n,char cake[NMAX][NMAX]) 42 | { 43 | // Write your code here . 44 | int ans=0; 45 | for(int i=0;i 60 | #include 61 | using namespace std; 62 | #define NMAX 55 63 | char cake[NMAX][NMAX]; 64 | int main() 65 | { 66 | int n; 67 | cin>>n; 68 | for(int i=0;ia[i]){ 33 | int temp=a[pIndex]; 34 | a[pIndex]=a[i]; 35 | a[i]=temp; 36 | pIndex++; 37 | } 38 | } 39 | int temp=a[pIndex]; 40 | a[pIndex]=a[u]; 41 | a[u]=temp; 42 | return pIndex; 43 | } 44 | 45 | 46 | void qS(int a[],int l,int u){ 47 | if(l 66 | #include "Solution.h" 67 | using namespace std; 68 | 69 | 70 | int main(){ 71 | int n; 72 | cin >> n; 73 | 74 | int *input = new int[n]; 75 | 76 | for(int i = 0; i < n; i++) { 77 | cin >> input[i]; 78 | } 79 | 80 | quickSort(input, n); 81 | for(int i = 0; i < n; i++) { 82 | cout << input[i] << " "; 83 | } 84 | 85 | delete [] input; 86 | 87 | } 88 | -------------------------------------------------------------------------------- /Arrays & Strings/Reverse_Each_Word.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, reverse each word of a string individually. For eg. if a string is "abc def", reversed string should be "cba fed". 3 | Input Format : 4 | 5 | String S 6 | 7 | Output Format : 8 | 9 | Updated string 10 | 11 | Constraints : 12 | 1 <= Length of S <= 1000 13 | Sample Input : 14 | 15 | Welcome to Coding Ninjas 16 | 17 | Sample Output: 18 | 19 | emocleW ot gnidoC sajniN 20 | 21 | */ 22 | 23 | // input - given string 24 | // Update in the given input itself. No need to return or print anything 25 | 26 | #include 27 | using namespace std; 28 | 29 | void swap(string &s,int i,int j){ 30 | char temp=s[i]; 31 | s[i]=s[j]; 32 | s[j]=temp; 33 | } 34 | 35 | void reverse(string &s){ 36 | int i=0; 37 | int j=s.size()-1; 38 | while (i<=j){ 39 | swap(s,i,j); 40 | i++; 41 | j--; 42 | } 43 | } 44 | 45 | void reverseEachWord(char input[]) { 46 | // Write your code here 47 | string ans=""; 48 | string word=""; 49 | int start_flag=1; 50 | 51 | int size=strlen(input); 52 | 53 | for(int i=0;i<=size;i++){ 54 | 55 | if(input[i]!=' ' && input[i]!='\0') 56 | word+=input[i]; 57 | 58 | else{ 59 | reverse(word); 60 | if(start_flag){ 61 | start_flag=0; 62 | ans+=word; 63 | word=""; 64 | continue; 65 | } 66 | ans+=' '+word; 67 | word=""; 68 | } 69 | } 70 | strcpy(input,ans.c_str()); 71 | 72 | } 73 | 74 | #include 75 | #include "solution.h" 76 | using namespace std; 77 | 78 | int main() { 79 | char input[1000]; 80 | cin.getline(input, 1000); 81 | reverseEachWord(input); 82 | cout << input << endl; 83 | } 84 | -------------------------------------------------------------------------------- /Backtracking/PrintSubsetsSumOfArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A and an integer K, print all subsets of A which sum to K. 3 | 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. 4 | Note : The order of subsets are not important. Just print them in different lines. 5 | Input format : 6 | 7 | Line 1 : Size of input array 8 | Line 2 : Array elements separated by space 9 | Line 3 : K 10 | 11 | Sample Input: 12 | 13 | 9 14 | 5 12 3 17 1 18 15 3 17 15 | 6 16 | 17 | Sample Output: 18 | 19 | 3 3 20 | 5 1 21 | */ 22 | 23 | 24 | #include 25 | using namespace std; 26 | 27 | void printVector(vector temp){ 28 | 29 | for(int i=0;i temp,int key){ 39 | int sum=0; 40 | for(int i=0;i temp){ 47 | 48 | if(n==0){ 49 | if(checkSum(temp,k)) 50 | printVector(temp); 51 | return; 52 | } 53 | 54 | temp.push_back(input[0]); 55 | subsetCheck(input+1,n-1,k,temp); 56 | 57 | temp.pop_back(); 58 | subsetCheck(input+1,n-1,k,temp); 59 | 60 | } 61 | void printSubsetSumToK(int input[], int size, int k) { 62 | // Write your code here 63 | vector temp; 64 | subsetCheck(input,size,k,temp); 65 | 66 | } 67 | 68 | 69 | int main() { 70 | int input[1000],length,k; 71 | cin >> length; 72 | for(int i=0; i < length; i++) 73 | cin >> input[i]; 74 | cin>>k; 75 | printSubsetSumToK(input, length,k); 76 | } 77 | -------------------------------------------------------------------------------- /Arrays & Strings/Print Spiral.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an N*M 2D array, print it in spiral form. That is, first you need to print the 1st row, then last column, then last row and then first column and so on. 3 | Print every element only once. 4 | Input format : 5 | 6 | Line 1 : N and M, No. of rows & No. of columns (separated by space) followed by N*M elements in row wise fashion. 7 | 8 | Sample Input : 9 | 10 | 4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 11 | 12 | Sample Output : 13 | 14 | 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 15 | 16 | 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | 22 | void spiralPrint(int input[][1000], int row, int col){ 23 | /* Don't write main(). 24 | * Don't read input, it is passed as function argument. 25 | * Print output and don't return it. 26 | * Taking input is handled automatically. 27 | */ 28 | int k=1; 29 | int r1=0,r2=row-1; 30 | int c1=0,c2=col-1; 31 | while(k<=row*col){ 32 | for(int i=c1;i<=c2;i++){ 33 | cout<=c1;i--){ 43 | cout<=r1;i--){ 48 | cout< 58 | using namespace std; 59 | #include "solution.h" 60 | 61 | int main() { 62 | int input[1500][1000]; 63 | int row, col; 64 | cin >> row >> col; 65 | 66 | for(int i = 0; i < row; i++) { 67 | for(int j = 0; j < col; j++) { 68 | cin >> input[i][j]; 69 | } 70 | } 71 | spiralPrint(input, row, col); 72 | } -------------------------------------------------------------------------------- /Graphs/BFS.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an undirected and connected graph G(V, E), print its BFS traversal. 3 | Here you need to consider that you need to print BFS path starting from vertex 0 only. 4 | V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 5 | E is the number of edges present in graph G. 6 | Input Format : 7 | 8 | Line 1: Two Integers V and E (separated by space) 9 | Next 'E' lines, each have two space-separated integers, 'a' and 'b', denoting that there exists an edge between Vertex 'a' and Vertex 'b'. 10 | 11 | Output Format : 12 | 13 | BFS Traversal (separated by space) 14 | 15 | Constraints : 16 | 2 <= V <= 1000 17 | 1 <= E <= 1000 18 | Sample Input 1: 19 | 20 | 4 4 21 | 0 1 22 | 0 3 23 | 1 2 24 | 2 3 25 | 26 | Sample Output 1: 27 | 28 | 0 1 3 2 29 | 30 | 31 | */ 32 | #include 33 | #include 34 | using namespace std; 35 | 36 | void bfs(int **edges,int n,int start,bool *visited){ 37 | 38 | queue q; 39 | q.push(start); 40 | visited[start]=true; 41 | while(!q.empty()){ 42 | int node=q.front(); 43 | q.pop(); 44 | cout<> V >> E; 60 | 61 | int **edges=new int*[V]; 62 | //intialization 63 | for(int i=0;i>a>>b; 72 | edges[a][b]=1; 73 | edges[b][a]=1; 74 | } 75 | bool* visited=new bool[V]; 76 | for(int i=0;i 36 | 37 | int max(int arr[], int n) { 38 | /* Don't write main(). 39 | * Don't read input, it is passed as function argument. 40 | * Return output and don't print it. 41 | * Taking input and printing output is handled automatically. 42 | */ 43 | unordered_map m; 44 | vector pre; 45 | for(int i=0;i 76 | #include 77 | using namespace std; 78 | #include "solution.h" 79 | 80 | int main() { 81 | int n=0; 82 | cin>>n; 83 | int *arr = new int[n]; 84 | for(int i=0;i>arr[i]; 86 | } 87 | 88 | cout << max(arr,n); 89 | 90 | 91 | } 92 | -------------------------------------------------------------------------------- /Recursion -2/String of Lenght k.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S and an integer k, you need to find and return all the possible strings that can be made of size k using only characters present in string S. 3 | The characters can repeat as many times as needed. 4 | Note : The number of output strings can be at max 1000. 5 | Input format : 6 | 7 | String S and Integer k (separated by space) 8 | 9 | Output Format : 10 | 11 | All possible strings (in different lines) 12 | 13 | Constraints : 14 | 1 <= Length of String S <= 10 15 | 1 <= k <= 5 16 | 17 | */ 18 | 19 | /**** 20 | Save all the strings in the output 2D array that is passed as argument. Return the number of strings that you have saved in output as answer from this function. 21 | That is, return number of rows that you have added in output. 22 | ****/ 23 | 24 | #include 25 | using namespace std; 26 | 27 | void help(string s,char *inp,int k,vector &ans){ 28 | 29 | if(k==0){ 30 | ans.push_back(s); 31 | return; 32 | } 33 | 34 | for(int i=0;i ans; 48 | 49 | help("",input,k,ans); 50 | 51 | for(int i=0;i 60 | #include "solution.h" 61 | using namespace std; 62 | 63 | int main() { 64 | char a[100]; 65 | char b[1000][100]; 66 | cin >> a; 67 | int k; 68 | cin >> k; 69 | int size = allStrings(a, k, b); 70 | for(int i = 0; i < size; i++) { 71 | cout << b[i] << endl; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Graphs2/CountWays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There exists a special graph which has directed M edges and N nodes and graph contains no cycles. Count the number of ways to reach different nodes from S. A way is called different from others if the destination node or used edges differ. As the ways can be large, print the ways modulo 1000000007. 3 | Include source node as destination also. 4 | Input Format: 5 | 6 | Line 1 : Two Integers N and M 7 | Next M lines : Two integers x, y which denotes an edge from x to y 8 | (M+1)st line : S, source 9 | 10 | Output Format: 11 | 12 | Count of ways 13 | 14 | Constraints : 15 | 1 <= S, N <= 100005 16 | 1 <= M <= 200005 17 | 1 <= x , y <= N 18 | Sample Input : 19 | 20 | 4 3 21 | 1 2 22 | 2 3 23 | 3 4 24 | 2 25 | 26 | Sample Output : 27 | 28 | 3 29 | 30 | Sample Output Explanation : 31 | From node 2 we can reach - 2, 3 and 4. 32 | */ 33 | 34 | #include 35 | #include 36 | #define MOD 1000000007 37 | using namespace std; 38 | 39 | long long int dfs(long long int *dp,vector adj[],int source) 40 | { 41 | dp[source]=(dp[source]%MOD+1)%MOD; 42 | for(int i=0;i> n >> m; 56 | 57 | vector adj[n+1]; 58 | 59 | for(int i = 0;i < m; i++) { 60 | int x, y; 61 | cin >> x >> y; 62 | adj[x].push_back(y); 63 | 64 | } 65 | int S; 66 | cin>>S; 67 | 68 | long long int *dp=new long long int[n+1]; 69 | for(int i=1;i<=n;i++) 70 | dp[i]=0; 71 | 72 | dfs(dp,adj,S); 73 | cout< 36 | using namespace std; 37 | 38 | int highestFrequency(int *input, int n){ 39 | 40 | /* Don't write main(). 41 | * the input array is already passed as function argument. 42 | * Taking input and printing output is handled automatically. 43 | */ 44 | int maxf=1; 45 | int pos=0; 46 | unordered_map m; 47 | 48 | for(int i=n-1;i>=0;i--){ 49 | if(m.count(input[i])==0) 50 | m[input[i]]=1; 51 | else{ 52 | m[input[i]]+=1; 53 | if(maxf<=m[input[i]]){ 54 | pos=i; 55 | maxf=m[input[i]]; 56 | } 57 | } 58 | } 59 | return input[pos]; 60 | 61 | 62 | 63 | } 64 | 65 | #include 66 | using namespace std; 67 | #include "solution.h" 68 | 69 | int main() 70 | { 71 | int n; 72 | int input[100000]; 73 | cin>>n; 74 | for(int i=0; i>input[i]; 77 | } 78 | int maxKey= highestFrequency(input, n); 79 | cout< 42 | using namespace std; 43 | 44 | void printinter(char * first,char *second,string out){ 45 | 46 | if(first[0]=='\0'){ 47 | cout<<(out+second)< 67 | using namespace std; 68 | #include "solution.h" 69 | 70 | int main() { 71 | char *a = new char[1000]; 72 | char *b = new char[1000]; 73 | cin >> a; 74 | cin >> b; 75 | interleaving(a, b); 76 | } 77 | -------------------------------------------------------------------------------- /Recursion -1/All Indices of Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of length N and an integer x, you need to find all the indexes where x is present in the input array. Save all the indexes in an array (in increasing order). 3 | Do this recursively. Indexing in the array starts from 0. 4 | Input Format : 5 | 6 | Line 1 : An Integer N i.e. size of array 7 | Line 2 : N integers which are elements of the array, separated by spaces 8 | Line 3 : Integer x 9 | 10 | Output Format : 11 | 12 | indexes where x is present in the array (separated by space) 13 | 14 | Constraints : 15 | 1 <= N <= 10^3 16 | Sample Input : 17 | 18 | 5 19 | 9 8 10 8 8 20 | 8 21 | 22 | Sample Output : 23 | 24 | 1 3 4 25 | */ 26 | 27 | int allIndexes(int input[], int size, int x, int output[]) { 28 | /* Don't write main(). 29 | Don't read input, it is passed as function argument. 30 | Save all the indexes in the output array passed and return the size of output array. 31 | Taking input and printing output is handled automatically. 32 | */ 33 | if(size==0) 34 | return 0; 35 | int ans=allIndexes(input,size-1,x,output); 36 | 37 | if(input[size-1]!=x) 38 | return ans; 39 | else{ 40 | output[ans]=size-1; 41 | return ans+1; 42 | } 43 | } 44 | 45 | #include 46 | #include "Solution.h" 47 | using namespace std; 48 | 49 | 50 | int main(){ 51 | int n; 52 | cin >> n; 53 | 54 | int *input = new int[n]; 55 | 56 | for(int i = 0; i < n; i++) { 57 | cin >> input[i]; 58 | } 59 | 60 | int x; 61 | 62 | cin >> x; 63 | 64 | int *output = new int[n]; 65 | 66 | int size = allIndexes(input, n, x, output); 67 | for(int i = 0; i < size; i++) { 68 | cout << output[i] << " "; 69 | } 70 | 71 | delete [] input; 72 | 73 | delete [] output; 74 | 75 | 76 | } 77 | 78 | 79 | -------------------------------------------------------------------------------- /Arrays & Strings/Largest Unique Substring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, find the largest substring with no repetition i.e. largest substring which contain all unique characters. 3 | Input Format : 4 | 5 | String S 6 | 7 | Output Format : 8 | 9 | Largest unique substring 10 | 11 | Constraints : 12 | 1 <= Length os String S <= 10^3 13 | Sample Input: 14 | 15 | abcdabceb 16 | 17 | Sample Output: 18 | 19 | dabce 20 | 21 | 22 | */ 23 | 24 | // input - given string 25 | // output - output string that contains largest unique substring 26 | #include 27 | using namespace std; 28 | 29 | int isCharSeenBefore(string &s,int start,int pos){ 30 | int i=start; 31 | while(i temp; 44 | int start=0,end=1; 45 | 46 | while(endmaxlen){ 61 | maxpos=i; 62 | maxlen=temp[i].size(); 63 | } 64 | } 65 | string ans=temp[maxpos]; 66 | strcpy(output,ans.c_str()); 67 | 68 | 69 | 70 | } 71 | 72 | #include 73 | #include "solution.h" 74 | using namespace std; 75 | 76 | int main() { 77 | char input[1000], output[1000]; 78 | cin.getline(input, 1000); 79 | findLargestUniqueSubstring(input, output); 80 | cout << output << endl; 81 | } 82 | -------------------------------------------------------------------------------- /LinkedList/PallindromList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Check if a given linked list is palindrome or not. Return true or false. 3 | Indexing starts from 0. 4 | 5 | Input format : Linked list elements (separated by space and terminated by -1)` 6 | Sample Input 1 : 7 | 8 | 9 2 3 3 2 9 -1 9 | 10 | Sample Output 1 : 11 | 12 | true 13 | 14 | Sample Input 2 : 15 | 16 | 0 2 3 2 5 -1 17 | 18 | Sample Output 2 : 19 | 20 | false 21 | 22 | */ 23 | 24 | #include 25 | using namespace std; 26 | 27 | class node{ 28 | public: 29 | int data; 30 | node * next; 31 | node(int data){ 32 | this->data=data; 33 | this->next=NULL; 34 | } 35 | }; 36 | 37 | 38 | bool check_palindrome(node* head) 39 | { 40 | //write your code here 41 | vector v; 42 | while(head){ 43 | v.push_back(head->data); 44 | head=head->next; 45 | } 46 | 47 | int i=0,j=v.size()-1; 48 | while(i<=j){ 49 | if(v[i]!=v[j]) 50 | return false; 51 | i++; 52 | j--; 53 | } 54 | return true; 55 | } 56 | 57 | 58 | node* takeinput(){ 59 | int data; 60 | cin>>data; 61 | node* head=NULL,*tail=NULL; 62 | while(data!=-1){ 63 | node *newnode=new node(data); 64 | if(head==NULL) { 65 | head=newnode; 66 | tail=newnode; 67 | } 68 | else{ 69 | tail->next=newnode; 70 | tail=newnode; 71 | } 72 | cin>>data; 73 | } 74 | return head; 75 | } 76 | void print(node *head) 77 | { 78 | node*temp=head; 79 | while(temp!=NULL) 80 | { 81 | cout<data<<" "; 82 | temp=temp->next; 83 | } 84 | cout< 28 | class node{ 29 | public: 30 | int data; 31 | node * next; 32 | node(int data){ 33 | this->data=data; 34 | this->next=NULL; 35 | } 36 | }; 37 | using namespace std; 38 | 39 | 40 | node* midpoint_linkedlist(node *head) 41 | { 42 | // Write your code here 43 | if(head==NULL) 44 | return NULL; 45 | if(head->next==NULL) 46 | return head; 47 | 48 | node* slow =head; 49 | node* fast=head->next; 50 | 51 | while(fast && fast->next){ 52 | slow=slow->next; 53 | fast=fast->next->next; 54 | } 55 | return slow; 56 | 57 | } 58 | 59 | node* takeinput(){ 60 | int data; 61 | cin>>data; 62 | node* head=NULL,*tail=NULL; 63 | while(data!=-1){ 64 | node *newnode=new node(data); 65 | if(head==NULL) { 66 | head=newnode; 67 | tail=newnode; 68 | } 69 | else{ 70 | tail->next=newnode; 71 | tail=newnode; 72 | } 73 | cin>>data; 74 | } 75 | return head; 76 | } 77 | void print(node *head) 78 | { 79 | node*temp=head; 80 | while(temp!=NULL) 81 | { 82 | cout<data<<" "; 83 | temp=temp->next; 84 | } 85 | cout<data; 91 | return 0; 92 | } -------------------------------------------------------------------------------- /LinkedList2/ReverseLL(iterative).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, reverse it iteratively. 3 | You don't need to print the elements, just reverse the LL duplicates and return the head of updated LL. 4 | 5 | Input format : Linked list elements (separated by space and terminated by -1)` 6 | Sample Input 1 : 7 | 8 | 1 2 3 4 5 -1 9 | 10 | Sample Output 1 : 11 | 12 | 5 4 3 2 1 13 | 14 | 15 | */ 16 | 17 | 18 | // Reverse Linked List a. Using recursion b. Without using recursion 19 | #include 20 | class node{ 21 | public: 22 | int data; 23 | node * next; 24 | node(int data){ 25 | this->data=data; 26 | this->next=NULL; 27 | } 28 | }; 29 | using namespace std; 30 | 31 | 32 | 33 | 34 | 35 | node* rev_linkedlist_itr(node* head) 36 | { 37 | //write your iterative code here 38 | if(head==NULL) 39 | return NULL; 40 | if(head->next==NULL) 41 | return head; 42 | 43 | node* prev=head; 44 | node* cur=head->next; 45 | prev->next=NULL; 46 | while(cur!=NULL){ 47 | node* temp=cur->next; 48 | cur->next=prev; 49 | prev=cur; 50 | cur=temp; 51 | } 52 | return prev; 53 | } 54 | 55 | 56 | node* takeinput(){ 57 | int data; 58 | cin>>data; 59 | node* head=NULL,*tail=NULL; 60 | while(data!=-1){ 61 | node *newnode=new node(data); 62 | if(head==NULL) { 63 | head=newnode; 64 | tail=newnode; 65 | } 66 | else{ 67 | tail->next=newnode; 68 | tail=newnode; 69 | } 70 | cin>>data; 71 | } 72 | return head; 73 | } 74 | void print(node *head) 75 | { 76 | node*temp=head; 77 | while(temp!=NULL) 78 | { 79 | cout<data<<" "; 80 | temp=temp->next; 81 | } 82 | cout< 46 | using namespace std; 47 | 48 | void hasPath(int** edges,int n,int start,int end,bool *visited){ 49 | 50 | 51 | visited[start]=true; 52 | if(start==end) 53 | return; 54 | 55 | for(int i=0;i> V >> E; 68 | 69 | 70 | int **edges=new int*[V]; 71 | //intialization 72 | for(int i=0;i>a>>b; 81 | edges[a][b]=1; 82 | edges[b][a]=1; 83 | } 84 | 85 | int s,e; 86 | cin>>s>>e; 87 | bool* visited=new bool[V]; 88 | for(int i=0;i 31 | #include 32 | using namespace std; 33 | 34 | 35 | vector kLargest(int input[], int n, int k){ 36 | /* Don't write main(). 37 | * Don't read input, it is passed as function argument. 38 | * Return output and don't print it. 39 | * Taking input and printing output is handled automatically. 40 | */ 41 | priority_queue,greater > pq; 42 | vector ans; 43 | 44 | for(int i=0;ipq.top()){ 50 | pq.pop(); 51 | pq.push(input[i]); 52 | } 53 | } 54 | while(!pq.empty()){ 55 | ans.push_back(pq.top()); 56 | pq.pop(); 57 | } 58 | return ans; 59 | 60 | } 61 | 62 | 63 | #include 64 | using namespace std; 65 | 66 | int main() { 67 | 68 | int size; 69 | cin >> size; 70 | int *input = new int[1 + size]; 71 | 72 | for(int i = 0; i < size; i++) 73 | cin >> input[i]; 74 | 75 | int k; 76 | cin >> k; 77 | 78 | vector output = kLargest(input, size, k); 79 | for(int i = 0; i < output.size(); i++) 80 | cout << output[i] << endl; 81 | 82 | return 0; 83 | } -------------------------------------------------------------------------------- /LinkedList2/ReverseLL(recursive).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, reverse it using recursion. 3 | You don't need to print the elements, just reverse the LL duplicates and return the head of updated LL. 4 | 5 | Input format : Linked list elements (separated by space and terminated by -1)` 6 | Sample Input 1 : 7 | 8 | 1 2 3 4 5 -1 9 | 10 | Sample Output 1 : 11 | 12 | 5 4 3 2 1 13 | 14 | */ 15 | 16 | 17 | // Reverse Linked List a. Using recursion b. Without using recursion 18 | #include 19 | class node{ 20 | public: 21 | int data; 22 | node * next; 23 | node(int data){ 24 | this->data=data; 25 | this->next=NULL; 26 | } 27 | }; 28 | using namespace std; 29 | 30 | 31 | 32 | 33 | 34 | 35 | node* get_last(node* head){ 36 | node* temp=head; 37 | while(temp->next) 38 | temp=temp->next; 39 | return temp; 40 | } 41 | node *reverse_linked_list_rec(node *head) 42 | { 43 | //write your recursive code here 44 | if(head->next==NULL) 45 | return head; 46 | 47 | node *ans=reverse_linked_list_rec(head->next); 48 | 49 | node* last=get_last(ans); 50 | last->next=head; 51 | head->next=NULL; 52 | 53 | return ans; 54 | } 55 | 56 | node* takeinput(){ 57 | int data; 58 | cin>>data; 59 | node* head=NULL,*tail=NULL; 60 | while(data!=-1){ 61 | node *newnode=new node(data); 62 | if(head==NULL) { 63 | head=newnode; 64 | tail=newnode; 65 | } 66 | else{ 67 | tail->next=newnode; 68 | tail=newnode; 69 | } 70 | cin>>data; 71 | } 72 | return head; 73 | } 74 | void print(node *head) 75 | { 76 | node*temp=head; 77 | while(temp!=NULL) 78 | { 79 | cout<data<<" "; 80 | temp=temp->next; 81 | } 82 | cout< 32 | #include 33 | #include 34 | using namespace std; 35 | 36 | 37 | int depth(char str[]) { 38 | /* Don't write main(). 39 | * Don't read input, it is passed as function argument. 40 | * Return output and don't print it. 41 | * Taking input and printing output is handled automatically. 42 | */ 43 | if(str[0]=='l') 44 | return 1; 45 | 46 | int dep=0; 47 | if(str[1]=='n' && str[2]=='n') 48 | dep=1+max(depth(str+1),depth(str+2)); 49 | 50 | else if(str[1]=='n') 51 | dep=1+depth(str+1); 52 | else if(str[2]=='n') 53 | dep=1+depth(str+2); 54 | else 55 | dep=depth(str+1); 56 | 57 | return dep; 58 | } 59 | 60 | 61 | int main() 62 | { 63 | char *str = new char[100000]; 64 | cin>>str; 65 | cout<V; 19 | int E = graph->E; 20 | int dist[V]; 21 | 22 | for (int i = 0; i < V; i++) 23 | dist[i] = INT_MAX; 24 | dist[src] = 0; 25 | 26 | for (int i = 1; i <= V - 1; i++) { 27 | for (int j = 0; j < E; j++) { 28 | int u = graph->edge[j].src; 29 | int v = graph->edge[j].dest; 30 | int weight = graph->edge[j].weight; 31 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) 32 | dist[v] = dist[u] + weight; 33 | } 34 | } 35 | 36 | for (int i = 0; i < E; i++) { 37 | int u = graph->edge[i].src; 38 | int v = graph->edge[i].dest; 39 | int weight = graph->edge[i].weight; 40 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { 41 | printf("Graph contains negative weight cycle"); 42 | return; // If negative cycle is detected, simply return 43 | } 44 | } 45 | 46 | printArr(dist, V); 47 | 48 | return; 49 | } 50 | -------------------------------------------------------------------------------- /Graphs/IsConnected.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an undirected graph G(V,E), check if the graph G is connected graph or not. 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 | Input Format : 6 | 7 | Line 1: Two Integers V and E (separated by space) 8 | Next 'E' lines, each have two space-separated integers, 'a' and 'b', denoting that there exists an edge between Vertex 'a' and Vertex 'b'. 9 | 10 | Output Format : 11 | 12 | "true" or "false" 13 | 14 | Constraints : 15 | 2 <= V <= 1000 16 | 1 <= E <= 1000 17 | Sample Input 1: 18 | 19 | 4 4 20 | 0 1 21 | 0 3 22 | 1 2 23 | 2 3 24 | 25 | Sample Output 1: 26 | 27 | true 28 | 29 | Sample Input 2: 30 | 31 | 4 3 32 | 0 1 33 | 1 3 34 | 0 3 35 | 36 | Sample Output 2: 37 | 38 | false 39 | 40 | Sample Output 2 Explanation 41 | 42 | The graph is not connected, even though vertices 0,1 and 3 are connected to each other but there isn’t any path from vertices 0,1,3 to vertex 2. 43 | 44 | 45 | */ 46 | 47 | #include 48 | using namespace std; 49 | 50 | void isConnected(int** edges,int n,int node,bool* visited){ 51 | visited[node]=true; 52 | 53 | for(int i=0;i> V >> E; 63 | 64 | int **edges=new int*[V]; 65 | //intialization 66 | for(int i=0;i>a>>b; 75 | edges[a][b]=1; 76 | edges[b][a]=1; 77 | } 78 | bool* visited=new bool[V]; 79 | for(int i=0;i 31 | using namespace std; 32 | 33 | 34 | 35 | int solve(int n,int m,vectoru,vectorv) 36 | { 37 | // Write your code here . 38 | unordered_map >adj; 39 | 40 | for(int i=0;i 71 | #include 72 | using namespace std; 73 | 74 | int main() 75 | { 76 | int n,m; 77 | vectoru,v; 78 | cin>>n>>m; 79 | for(int i=0;i>x; 83 | u.push_back(x); 84 | } 85 | for(int i=0;i>x; 89 | v.push_back(x); 90 | } 91 | cout< 39 | using namespace std; 40 | int platformsNeeded(int arrival[], int departure[], int n) { 41 | /* 42 | * Don't write main(). 43 | * Don't read input, it is passed as function argument. 44 | * Don't print anything just return integer value. 45 | */ 46 | int maxc=1; 47 | int c=1; 48 | int i=0,j=0; 49 | 50 | sort(arrival,arrival+n); 51 | sort(departure,departure+n); 52 | 53 | while(i 68 | using namespace std; 69 | #include"solution.h" 70 | 71 | int main() 72 | { 73 | int n; 74 | cin>>n; 75 | int* arr=new int[n]; 76 | int* dep=new int[n]; 77 | for(int i=0;i>arr[i]; 80 | } 81 | for(int i=0;i>dep[i]; 84 | } 85 | cout<< platformsNeeded(arr, dep, n); 86 | } 87 | -------------------------------------------------------------------------------- /LinkedList2/MergeSortLL.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort a given linked list using Merge Sort. 3 | You don't need to print the elements, just sort the elements and return the head of updated LL. 4 | Input format : 5 | 6 | Linked list elements (separated by space and terminated by -1) 7 | 8 | Output format : 9 | 10 | Updated LL elements (separated by space) 11 | 12 | Constraints : 13 | 1 <= Length of LL <= 1000 14 | Sample Input 1 : 15 | 16 | 1 4 5 2 -1 17 | 18 | Sample Output 1 : 19 | 20 | 1 2 4 5 21 | 22 | 23 | */ 24 | 25 | #include "Merge2SortedList.cpp" 26 | #include "MidPointofLL.cpp" 27 | 28 | //merge sort recursive 29 | #include 30 | class node{ 31 | public: 32 | int data; 33 | node * next; 34 | node(int data){ 35 | this->data=data; 36 | this->next=NULL; 37 | } 38 | }; 39 | 40 | using namespace std; 41 | 42 | 43 | 44 | 45 | node* mergeSort(node *head) { 46 | //write your code here 47 | if(head->next!=NULL){ 48 | node* mid=midpoint(head); 49 | node* mid_1=mid->next; 50 | mid->next=NULL; 51 | 52 | node* left=mergeSort(head); 53 | node* right=mergeSort(mid_1); 54 | 55 | node* ans=merge(left,right); 56 | return ans; 57 | } 58 | return head; 59 | 60 | } 61 | 62 | node* takeinput(){ 63 | int data; 64 | cin>>data; 65 | node* head=NULL,*tail=NULL; 66 | while(data!=-1){ 67 | node *newnode=new node(data); 68 | if(head==NULL) { 69 | head=newnode; 70 | tail=newnode; 71 | } 72 | else{ 73 | tail->next=newnode; 74 | tail=newnode; 75 | } 76 | cin>>data; 77 | } 78 | return head; 79 | } 80 | void print(node *head) 81 | { 82 | node*temp=head; 83 | while(temp!=NULL) 84 | { 85 | cout<data<<" "; 86 | temp=temp->next; 87 | } 88 | cout< 30 | using namespace std; 31 | 32 | int kadane(int arr[],int n){ 33 | 34 | int all_neg=1; 35 | 36 | //Loop to check for all negatives; 37 | 38 | int neg_max=INT_MIN; 39 | for(int i=0;i0){ 41 | all_neg=0; 42 | break; 43 | } 44 | neg_max=max(neg_max,arr[i]); 45 | 46 | } 47 | if(all_neg) 48 | return neg_max; 49 | 50 | int maxsum=0; 51 | int sum=0; 52 | for(int i=0;i>n>>m; 67 | 68 | int a[n][m]; 69 | 70 | for(int i=0;i>a[i][j]; 73 | } 74 | } 75 | int ans=INT_MIN; 76 | int v[n]={0}; 77 | // The Approach is to have vertical sliding window and within that window try to find max contigos 78 | for(int i=0;i 40 | using namespace std; 41 | 42 | void intersection(int input1[], int input2[], int size1, int size2) { 43 | /* Don't write main(). 44 | * Don't read input, it is passed as function argument. 45 | * Print the output and don't return it. 46 | * Taking input is handled automatically. 47 | */ 48 | for(int i=0;i 59 | using namespace std; 60 | #include "solution.h" 61 | 62 | int main() { 63 | 64 | int size1,size2; 65 | 66 | cin>>size1; 67 | int *input1=new int[1+size1]; 68 | 69 | for(int i=0;i>input1[i]; 71 | 72 | cin>>size2; 73 | int *input2=new int[1+size2]; 74 | 75 | for(int i=0;i>input2[i]; 77 | 78 | 79 | intersection(input1,input2,size1,size2); 80 | 81 | 82 | return 0; 83 | } 84 | -------------------------------------------------------------------------------- /DP (2D)/MaxSubSquare with all zeros.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | Input format : 4 | 5 | Line 1 : n and m (space separated positive integers) 6 | Next n lines : m elements of each row (separated by space). 7 | 8 | Output Format: 9 | 10 | Line 1 : Size of maximum square sub-matrix 11 | 12 | Sample Input : 13 | 14 | 3 3 15 | 1 1 0 16 | 1 1 1 17 | 1 1 1 18 | 19 | Sample Output : 20 | 21 | 1 22 | */ 23 | 24 | #include 25 | using namespace std; 26 | int findMaxSquareWithAllZeros(int** arr, int row, int col){ 27 | 28 | /* Don't write main(). 29 | * Don't read input, it is passed as function argument. 30 | * Return output and don't print it. 31 | * Taking input and printing output is handled automatically. 32 | */ 33 | int dp[row][col]={0}; 34 | 35 | //Initialization 36 | int ans=0; 37 | for(int i=0;i>n>>m; 65 | arr=new int*[n]; 66 | for(i=0;i>arr[i][j]; 75 | } 76 | } 77 | cout << findMaxSquareWithAllZeros(arr,n,m) << endl; 78 | delete arr; 79 | return 0; 80 | } -------------------------------------------------------------------------------- /DP (1D)/MinCount.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer N, find and return the count of minimum numbers, sum of whose squares is equal to N. 3 | That is, if N is 4, then we can represent it as : {1^2 + 1^2 + 1^2 + 1^2} and {2^2}. Output will be 1, as 1 is the minimum count of numbers required. 4 | Note : x^y represents x raise to the power y. 5 | Input Format : 6 | 7 | Integer N 8 | 9 | Output Format : 10 | 11 | Required minimum count 12 | 13 | Constraints : 14 | 1 <= N <= 1000 15 | Sample Input 1 : 16 | 17 | 12 18 | 19 | Sample Output 1 : 20 | 21 | 3 22 | 23 | Sample Output 1 Explanation : 24 | 12 can be represented as : 25 | 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 26 | 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 2^2 27 | 1^1 + 1^1 + 1^1 + 1^1 + 2^2 + 2^2 28 | 2^2 + 2^2 + 2^2 29 | As we can see, the output should be 3. 30 | Sample Input 2 : 31 | 32 | 9 33 | 34 | Sample Output 2 : 35 | 36 | 1 37 | 38 | */ 39 | 40 | 41 | #include 42 | using namespace std; 43 | 44 | 45 | int minC(vector &dp,int n){ 46 | 47 | /* Don't write main(). 48 | * Don't read input, it is passed as function argument. 49 | * Return output and don't print it. 50 | * Taking input and printing output is handled automatically. 51 | */ 52 | int sq=floor(sqrt(n)); 53 | 54 | if(sq*sq == n)return 1; 55 | 56 | if(dp[n]!=0) 57 | return dp[n]; 58 | 59 | int temp=INT_MAX; 60 | for(int i=floor(sqrt(n));i>=1;i--){ 61 | temp=min(temp,minC(dp,n-(i*i))); 62 | 63 | } 64 | 65 | dp[n]=1+temp; 66 | return dp[n]; 67 | 68 | 69 | 70 | } 71 | 72 | int minCount(int n){ 73 | 74 | /* Don't write main(). 75 | * Don't read input, it is passed as function argument. 76 | * Return output and don't print it. 77 | * Taking input and printing output is handled automatically. 78 | */ 79 | 80 | vector dp(n+1); 81 | int ans=minC(dp,n); 82 | return ans; 83 | 84 | } 85 | 86 | int main(){ 87 | 88 | int num; 89 | cin >> num; 90 | cout << minCount(num); 91 | 92 | } -------------------------------------------------------------------------------- /Graphs/Island.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | An island is a small piece of land surrounded by water . A group of islands is said to be connected if we can reach from any given island to any other island in the same group . Given N islands (numbered from 1 to N) and two lists of size M (u and v) denoting island u[i] is connected to island v[i] and vice versa . Can you count the number of connected groups of islands. 3 | Constraints : 4 | 1<=N<=100 5 | 1<=M<=(N*(N-1))/2 6 | 1<=u[i],v[i]<=N 7 | Input Format : 8 | 9 | Line 1 : Two integers N and M 10 | Line 2 : List u of size of M 11 | Line 3 : List v of size of M 12 | 13 | Output Return Format : 14 | 15 | The count the number of connected groups of islands 16 | 17 | Sample Input : 18 | 19 | 2 1 20 | 1 21 | 2 22 | 23 | Sample Output : 24 | 25 | 1 26 | 27 | */ 28 | 29 | 30 | #include 31 | using namespace std; 32 | 33 | void dfs(vector > &adj,int node,bool* visited){ 34 | visited[node]=true; 35 | 36 | for(int i=0;iu,vectorv) 44 | { 45 | // Write your code here . 46 | vector > adj(n+1); 47 | 48 | for(int i=0;i 72 | #include 73 | using namespace std; 74 | 75 | int main() 76 | { 77 | int n,m; 78 | vectoru,v; 79 | cin>>n>>m; 80 | for(int i=0;i>x; 84 | u.push_back(x); 85 | } 86 | for(int i=0;i>x; 90 | v.push_back(x); 91 | } 92 | cout< 24 | using namespace std; 25 | 26 | void help(string input,string out,vector &str){ 27 | if(input.size()==0){ 28 | str.push_back(out); 29 | return; 30 | } 31 | char c1=(input[0]-48)+96; 32 | 33 | //Ignore the output coming from zero in a string 34 | if(input[0]=='0') 35 | return; 36 | 37 | help(input.substr(1),out+c1,str); 38 | 39 | if(input.size()>1){ 40 | int d=(input[0]-48)*10+(input[1]-48); 41 | if(d>26) 42 | return; 43 | char c2=96+d; 44 | help(input.substr(2),out+c2,str); 45 | } 46 | 47 | } 48 | 49 | 50 | int getCodes(string input, string output[10000]) { 51 | /* 52 | 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. 53 | Also, return the number of codes return to the output string. You do not need to print anything. 54 | */ 55 | vector str; 56 | string out=""; 57 | help(input,out,str); 58 | 59 | for(int i=0;i 70 | #include "solution.h" 71 | using namespace std; 72 | 73 | int main(){ 74 | string input; 75 | cin >> input; 76 | 77 | string output[10000]; 78 | int count = getCodes(input, output); 79 | for(int i = 0; i < count && i < 10000; i++) 80 | cout << output[i] << endl; 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /Recursion -2/Merge Sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort an array A using Merge Sort. 3 | Change in the input array itself. So no need to return or print anything. 4 | Input format : 5 | 6 | Line 1 : Integer n i.e. Array size 7 | Line 2 : Array elements (separated by space) 8 | 9 | Output format : 10 | 11 | Array elements in increasing order (separated by space) 12 | 13 | Constraints : 14 | 1 <= n <= 1000 15 | Sample Input: 16 | 17 | 6 18 | 2 6 8 5 4 3 19 | 20 | Sample Output: 21 | 22 | 2 3 4 5 6 8 23 | 24 | 25 | */ 26 | 27 | 28 | void merge(int a[],int l,int mid,int u){ 29 | 30 | int size1=mid-l+1; 31 | int size2=u-mid; 32 | 33 | int L1[size1]; 34 | int L2[size2]; 35 | 36 | int k=0; 37 | for(int i=l;i<=mid;i++,k++) 38 | L1[k]=a[i]; 39 | int j=0; 40 | for(int i=mid+1;i<=u;i++,j++) 41 | L2[j]=a[i]; 42 | k=0; 43 | j=0; 44 | int i=l; 45 | while(k 88 | #include "solution.h" 89 | using namespace std; 90 | 91 | int main() { 92 | int input[1000],length; 93 | cin >> length; 94 | for(int i=0; i < length; i++) 95 | cin >> input[i]; 96 | mergeSort(input, length); 97 | for(int i = 0; i < length; i++) { 98 | cout << input[i] << " "; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Stack&Queue/ReverseFirstKelements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a queue and an integer k, reverse first k elements. Return the updated queue. 3 | Do the problem in O(n) complexity. 4 | Input Format : 5 | 6 | Line 1 : Integer N, Size of Queue 7 | Line 2 : Queue Elements (separated by space) 8 | Line 3 : Integer k 9 | 10 | Output Format: 11 | 12 | Updated Queue elements 13 | 14 | Contraints : 15 | 1<= N <=10000 16 | Sample Input 1: 17 | 18 | 5 19 | 1 2 3 4 5 20 | 3 21 | 22 | Sample Output 1: 23 | 24 | 3 2 1 4 5 25 | 26 | Sample Input 2: 27 | 28 | 7 29 | 3 4 2 5 6 7 8 30 | 7 31 | 32 | Sample Output 2: 33 | 34 | 8 7 6 5 2 4 3 35 | 36 | */ 37 | 38 | 39 | #include 40 | #include 41 | #include 42 | using namespace std; 43 | 44 | queue reverseKElements(queue input, int k) { 45 | /* Don't write main(). 46 | * Don't read input, it is passed as function argument. 47 | * Return output and don't print it. 48 | * Taking input and printing output is handled automatically. 49 | */ 50 | stack rev; 51 | queue tem; 52 | 53 | int c=0; 54 | while(!input.empty()) 55 | { 56 | if(c out; 68 | 69 | while(!rev.empty()) 70 | { 71 | out.push(rev.top()); 72 | rev.pop(); 73 | } 74 | while(!tem.empty()) 75 | { 76 | out.push(tem.front()); 77 | tem.pop(); 78 | } 79 | return out; 80 | 81 | } 82 | 83 | 84 | int main() { 85 | int n=0; 86 | cin>>n; 87 | queue Queue; 88 | for(int i=0;i>temp; 91 | Queue.push(temp); 92 | } 93 | int k; 94 | cin>>k; 95 | 96 | queue ans = reverseKElements(Queue,k); 97 | while (!ans.empty()) { 98 | cout << ans.front() << endl; 99 | ans.pop(); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Hashing/Longest Consecutive Subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given with an array of integers that contain numbers in random order. Write a program to find the longest possible sub sequence of consecutive numbers using the numbers from given array. 3 | You need to return the output array which contains consecutive elements. Order of elements in the output is not important. 4 | Best solution takes O(n) time. 5 | If two arrays are of equal length return the array whose index of smallest element comes first. 6 | Input Format : 7 | 8 | Line 1 : Integer n, Size of array 9 | Line 2 : Array elements (separated by space) 10 | 11 | Constraints : 12 | 1 <= n <= 10^5 13 | Sample Input 1 : 14 | 15 | 13 16 | 2 12 9 16 10 5 3 20 25 11 1 8 6 17 | 18 | Sample Output 1 : 19 | 20 | 8 21 | 9 22 | 10 23 | 11 24 | 12 25 | 26 | Sample Input 2 : 27 | 28 | 7 29 | 15 13 23 21 19 11 16 30 | 31 | Sample Output 2 : 32 | 33 | 15 34 | 16 35 | 36 | */ 37 | 38 | #include 39 | using namespace std; 40 | 41 | vector longestSubsequence(int *arr, int n){ 42 | // Write your code here 43 | unordered_map m; 44 | vector ans; 45 | for(int i=0;i temp; 50 | //Find the starting point for the increasing sequence 51 | if (m.count(arr[i]-1)==0){ 52 | temp.push_back(arr[i]); 53 | int t=1; 54 | 55 | while(m.count(arr[i]+t)){ 56 | temp.push_back(arr[i]+t); 57 | t++; 58 | } 59 | 60 | if (temp.size()>ans.size()) 61 | ans=temp; 62 | } 63 | } 64 | return ans; 65 | 66 | } 67 | 68 | #include 69 | using namespace std; 70 | #include 71 | #include "solution.h" 72 | 73 | int main() { 74 | int n; 75 | cin >> n; 76 | int *input = new int[n]; 77 | for(int i = 0; i < n; i++){ 78 | cin >> input[i]; 79 | } 80 | vector output = longestSubsequence(input, n); 81 | for(int i = 0; i < output.size(); i++) { 82 | cout << output[i] << endl; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Arrays & Strings/Merge_two_Sorted_Arrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted arrays of Size M and N respectively, merge them into a third array such that the third array is also sorted. 3 | Input Format : 4 | Line 1 : Size of first array i.e. M 5 | Line 2 : M elements of first array separated by space 6 | Line 3 : Size of second array i.e. N 7 | Line 2 : N elements of second array separated by space 8 | 9 | Output Format : 10 | M + N integers i.e. elements of third sorted array separated by spaces. 11 | 12 | Constraints : 13 | 1 <= M, N <= 10^6 14 | Sample Input : 15 | 5 16 | 1 3 4 7 11 17 | 4 18 | 2 4 6 13 19 | 20 | Sample Output : 21 | 1 2 3 4 4 6 7 11 13 22 | */ 23 | 24 | #include 25 | #include "Solution.h" 26 | using namespace std; 27 | 28 | 29 | void merge(int arr1[], int size1, int arr2[], int size2, int ans[]){ 30 | 31 | /* Don't write main(). 32 | * Don't read input, it is passed as function argument. 33 | * Save the merged array in ans[] array passed as argument. 34 | * Don't return or print anything. 35 | * Taking input and printing output is handled automatically. 36 | */ 37 | int i=0,j=0; 38 | int k=0; 39 | while (i> size1; 62 | int* arr1 = new int[size1]; 63 | for(int i = 0; i < size1; i++){ 64 | cin >> arr1[i]; 65 | } 66 | int size2; 67 | cin >> size2; 68 | int* arr2 = new int[size2]; 69 | for(int i = 0; i < size2; i++){ 70 | cin >> arr2[i]; 71 | } 72 | 73 | int* ans = new int[size1 + size2]; 74 | 75 | merge(arr1, size1, arr2, size2, ans); 76 | 77 | for(int i = 0; i < size1 + size2; i++){ 78 | cout << ans[i] << " "; 79 | } 80 | delete arr1; 81 | delete arr2; 82 | delete ans; 83 | } 84 | 85 | 86 | -------------------------------------------------------------------------------- /DP (2D)/MCM.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a chain of matrices A1, A2, A3,.....An, you have to figure out the most efficient way to multiply these matrices 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 | Input Format : 5 | 6 | Line 1 : Integer n i.e. number of matrices 7 | Line 2 : n + 1 integers i.e. elements of array p[] 8 | 9 | Output Format : 10 | 11 | Line 1 : Minimum number of multiplication needed 12 | 13 | Constraints : 14 | 15 | 1 <= n <= 100 16 | 17 | Sample Input 1 : 18 | 19 | 3 20 | 10 15 20 25 21 | 22 | Sample Output : 23 | 24 | 8000 25 | 26 | Sample Output Explanation : 27 | There are two ways to multiply the chain - A1*(A2*A3) or (A1*A2)*A3. 28 | If multiply in order A1*(A2*A3) then number of multiplications required are 15000. 29 | If multiply in order (A1*A2)*A3 then number of multiplications required are 8000. 30 | Thus minimum number of multiplications required are 8000 31 | 32 | */ 33 | 34 | #include 35 | using namespace std; 36 | 37 | int f(vector > &dp,int *p,int s,int e){ 38 | if(e-s==1) 39 | return 0; 40 | 41 | if(dp[s][e]) 42 | return dp[s][e]; 43 | 44 | int ans=INT_MAX; 45 | for(int k=s+1;k > dp(n+1,vector(n+1,0)); 62 | int ans=f(dp,p,0,n); 63 | return ans; 64 | 65 | 66 | 67 | 68 | 69 | } 70 | 71 | int main(){ 72 | 73 | int n; 74 | cin >> n; 75 | int* p = new int[n]; 76 | 77 | for(int i = 0; i <= n; i++){ 78 | cin >> p[i]; 79 | } 80 | 81 | cout << mcm(p, n); 82 | 83 | } -------------------------------------------------------------------------------- /Arrays & Strings/Sort_0_1_2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer array containing only 0s, 1s and 2s. Write a solution to sort this array using one scan only. 3 | You need to change in the given array itself. So no need to return or print anything. 4 | Input format : 5 | 6 | Line 1 : Integer n (Array Size) 7 | Line 2 : Array elements (separated by space) 8 | 9 | Output Format : 10 | 11 | Updated array elements (separated by space) 12 | 13 | Constraints : 14 | 1 <= n <= 10^6 15 | Sample Input: 16 | 17 | 7 18 | 0 1 2 0 2 0 1 19 | 20 | Sample Output: 21 | 22 | 0 0 0 1 1 2 2 23 | 24 | 25 | */ 26 | 27 | // arr - input array 28 | // n - size of array 29 | 30 | void swap(int arr[],int i,int j){ 31 | int temp=arr[i]; 32 | arr[i]=arr[j]; 33 | arr[j]=temp; 34 | } 35 | 36 | void sort012(int arr[], int n) { 37 | /* Don't write main(). 38 | * Don't read input, it is passed as function argument. 39 | * No need to print or return the output. 40 | * Taking input and printing output is handled automatically. 41 | */ 42 | int i=0; 43 | int j=n-1; 44 | 45 | while ((i-1 && arr[j]==2)){ 46 | if(arr[i]==0) 47 | i++; 48 | if(arr[j]==2) 49 | j--; 50 | } 51 | if(i==n || j==-1) 52 | return; 53 | int k=i; 54 | while(k<=j && i<=j){ 55 | if(arr[k]!=1){ 56 | if(arr[k]==0){ 57 | swap(arr,i,k); 58 | i++; 59 | if(i>k) 60 | k=i; 61 | } 62 | else{ 63 | swap(arr,k,j); 64 | j--; 65 | } 66 | } 67 | else 68 | k++; 69 | } 70 | 71 | } 72 | 73 | #include 74 | #include 75 | #include "solution.h" 76 | using namespace std; 77 | 78 | 79 | int main() { 80 | 81 | int size_first; 82 | 83 | cin>>size_first; 84 | int *arr_first=new int[1+size_first]; 85 | 86 | for(int i=0;i>arr_first[i]; 88 | 89 | sort012(arr_first,size_first); 90 | 91 | for(int i=0;i 34 | #include 35 | #include 36 | using namespace std; 37 | 38 | string pad(int key){ 39 | unordered_map dial; 40 | dial[0]=""; 41 | dial[1]=""; 42 | dial[2]="abc"; 43 | dial[3]="def"; 44 | dial[4]="ghi"; 45 | dial[5]="jkl"; 46 | dial[6]="mno"; 47 | dial[7]="pqrs"; 48 | dial[8]="tuv"; 49 | dial[9]="wxyz"; 50 | 51 | return dial[key]; 52 | } 53 | 54 | 55 | int keypad(int num, string output[]){ 56 | /* Insert all the possible combinations of the integer number into the output string array. You do not need to 57 | print anything, just return the number of strings inserted into the array. 58 | */ 59 | if(num==0){ 60 | output[0]=""; 61 | return 1; 62 | } 63 | int smallOutSize=keypad(num/10,output); 64 | 65 | string pd=pad(num%10); 66 | int newsize=pd.size()*smallOutSize; 67 | //Copy 68 | string temp[10000]; 69 | for(int i=0;i<10000;i++) 70 | temp[i]=output[i]; 71 | 72 | for(int i=0;i 81 | #include 82 | #include "solution.h" 83 | using namespace std; 84 | 85 | int main(){ 86 | int num; 87 | cin >> num; 88 | 89 | string output[10000]; 90 | int count = keypad(num, output); 91 | for(int i = 0; i < count && i < 10000; i++){ 92 | cout << output[i] << endl; 93 | } 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /Hashing/Make String Anagrams.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings S1 and S2, find and return the minimum number of deletions to be made (total count of deletions in both strings) in order to make the strings anagram. 3 | Anagram of a string is a string which is its permutation. 4 | For example "bbaa" and "abab" are anagrams of each other but "bbaa" and "aaab" are not. 5 | Input Format : 6 | 7 | Line 1 : String1 8 | Line 2 : String2 9 | 10 | Output Format : 11 | 12 | Number of deletions required 13 | 14 | Contraints : 15 | 1<= Length of string <=10^4 16 | Sample Input 1 : 17 | 18 | cde 19 | abc 20 | 21 | Sample Output 1 : 22 | 23 | 4 24 | 25 | Sample Input 2 : 26 | 27 | aab 28 | aba 29 | 30 | Sample Output 2 : 31 | 32 | 0 33 | 34 | 35 | */ 36 | 37 | #include 38 | int makeAnagram(char str1[], char str2[]){ 39 | /* Don't write main(). 40 | * Don't read input, it is passed as function argument. 41 | * Return output and don't print it. 42 | * Taking input and printing output is handled automatically. 43 | */ 44 | unordered_map m; 45 | 46 | for(int i=0;str1[i]!='\0';i++){ 47 | if(!m.count(str1[i])) 48 | m[str1[i]]=1; 49 | else 50 | m[str1[i]]+=1; 51 | } 52 | int delc=0; 53 | for(int i =0;str2[i]!='\0';i++){ 54 | if(m.count(str2[i])){ 55 | if(m[str2[i]]==0){ 56 | //cout<<"Extra Same Char in STR2"<::iterator it; 68 | for(it=m.begin();it!=m.end();it++){ 69 | //cout<first<<":"<second<second; 71 | } 72 | return delc; 73 | 74 | } 75 | 76 | #include 77 | #include 78 | using namespace std; 79 | #include "solution.h" 80 | 81 | int main() { 82 | char str1[10010], str2[10010]; 83 | cin>>str1; 84 | cin>>str2; 85 | 86 | cout << makeAnagram(str1,str2) << endl; 87 | 88 | } 89 | 90 | -------------------------------------------------------------------------------- /DP (2D)/Edit_Distance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings s and t of lengths m and n respectively, find the Edit Distance between the strings. Edit Distance of two strings is minimum number of steps required to make one string equal to other. In order to do so you can perform following three operations only : 3 | 4 | 1. Delete a character 5 | 6 | 2. Replace a character with another one 7 | 8 | 3. Insert a character 9 | 10 | Note - Strings don't contain spaces 11 | Input Format : 12 | 13 | Line 1 : String s 14 | Line 2 : String t 15 | 16 | Output Format : 17 | 18 | Line 1 : Edit Distance value 19 | 20 | Constraints 21 | 22 | 1<= m,n <= 20 23 | 24 | Sample Input 1 : 25 | 26 | abc 27 | dc 28 | 29 | Sample Output 1 : 30 | 31 | 2 32 | 33 | */ 34 | 35 | 36 | #include 37 | #include 38 | #include 39 | using namespace std; 40 | 41 | int eD(vector < vector > &dp,string s1,string s2){ 42 | 43 | if(s1.size()==0) 44 | return s2.size(); 45 | if(s2.size()==0) 46 | return s1.size(); 47 | 48 | if(dp[s1.size()][s2.size()] >-1) 49 | return dp[s1.size()][s2.size()]; 50 | 51 | int ans; 52 | if(s1[0]==s2[0]) 53 | ans=eD(dp,s1.substr(1),s2.substr(1)); 54 | 55 | else{ 56 | int optiondel=1+eD(dp,s1.substr(1),s2); 57 | int optionins=1+eD(dp,s1,s2.substr(1)); 58 | int optionrep=1+eD(dp,s1.substr(1),s2.substr(1)); 59 | 60 | ans=min(optiondel,min(optionins,optionrep)); 61 | } 62 | dp[s1.size()][s2.size()]=ans; 63 | return ans; 64 | 65 | } 66 | 67 | int editDistance(string s1, string s2){ 68 | 69 | /* Don't write main(). 70 | * Don't read input, it is passed as function argument. 71 | * Return output and don't print it. 72 | * Taking input and printing output is handled automatically. 73 | */ 74 | int n=s1.size(); 75 | int m=s2.size(); 76 | vector < vector > dp(n+1,vector(m+1,-1)); 77 | 78 | int ans=eD(dp,s1,s2); 79 | return ans; 80 | 81 | } 82 | 83 | 84 | int main(){ 85 | 86 | string s1; 87 | string s2; 88 | 89 | cin >> s1; 90 | cin >> s2; 91 | 92 | cout << editDistance(s1,s2) << endl; 93 | 94 | } -------------------------------------------------------------------------------- /LinkedList/LenghtofLL(recursive).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, find and return the length of input LL recursively. 3 | Input format : 4 | 5 | Linked list elements (separated by space and terminated by -1) 6 | 7 | Output format : 8 | 9 | Length of LL 10 | 11 | Sample Input : 12 | 13 | 3 4 5 2 6 1 9 -1 14 | 15 | Sample Output : 16 | 17 | 7 18 | 19 | */ 20 | 21 | 22 | 23 | /********** 24 | * Following is the Node class that is already written. 25 | 26 | class Node{ 27 | public: 28 | int data; 29 | Node *next; 30 | Node(int data){ 31 | this -> data = data; 32 | this -> next = NULL; 33 | } 34 | }; 35 | 36 | *********/ 37 | 38 | 39 | #include 40 | using namespace std; 41 | 42 | class Node{ 43 | public: 44 | int data; 45 | Node *next; 46 | Node(int data){ 47 | this -> data = data; 48 | this -> next = NULL; 49 | } 50 | }; 51 | 52 | Node* takeinput() { 53 | int data; 54 | cin >> data; 55 | Node* head = NULL, *tail = NULL; 56 | while(data != -1){ 57 | Node *newNode = new Node(data); 58 | if(head == NULL) { 59 | head = newNode; 60 | tail = newNode; 61 | } 62 | else{ 63 | tail -> next = newNode; 64 | tail = newNode; 65 | } 66 | cin >> data; 67 | } 68 | return head; 69 | } 70 | 71 | 72 | int length(Node *head) { 73 | /* Don't write main(). 74 | * Don't read input, it is passed as function argument. 75 | * Return output and don't print it. 76 | * Taking input is handled automatically. 77 | */ 78 | if(head==NULL) 79 | return 0; 80 | int ans=length(head->next); 81 | return ans+1; 82 | 83 | } 84 | 85 | void print(Node *head) { 86 | Node *temp = head; 87 | while(temp != NULL) { 88 | cout << temp -> data << " "; 89 | temp = temp -> next; 90 | } 91 | cout<> pos; 98 | cout << length(head); 99 | return 0; 100 | } 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /DP (2D)/WaysToMakeCoinChange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an infinite supply of coins of each of denominations D = {D0, D1, D2, D3, ...... Dn-1}. 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 | 6 | Line 1 : Integer n i.e. total number of denominations 7 | Line 2 : N integers i.e. n denomination values 8 | Line 3 : Value V 9 | 10 | Output Format 11 | 12 | Line 1 : Number of ways i.e. W 13 | 14 | Constraints : 15 | 16 | 1<=n<=10 17 | 1<=V<=1000 18 | 19 | Sample Input 1 : 20 | 21 | 3 22 | 1 2 3 23 | 4 24 | 25 | Sample Output 26 | 27 | 4 28 | 29 | Sample Output Explanation : 30 | Number of ways are - 4 total i.e. (1,1,1,1), (1,1, 2), (1, 3) and (2, 2). 31 | 32 | */ 33 | 34 | 35 | 36 | 37 | #include 38 | using namespace std; 39 | 40 | int helper(vector > &dp,int c[],int n,int v){ 41 | if(v<0) 42 | return 0; 43 | if(v==0) 44 | return 1; 45 | if(n==0) 46 | return 0; 47 | 48 | if(dp[n][v]) 49 | return dp[n][v]; 50 | 51 | //Either include nth coin or don't include 52 | int ans=helper(dp,c,n,v-c[n-1])+helper(dp,c,n-1,v); 53 | dp[n][v]=ans; 54 | return ans; 55 | } 56 | int countWaysToMakeChange(int denominations[], int numDenominations, int value){ 57 | 58 | /* Don't write main(). 59 | * Don't read input, it is passed as function argument. 60 | * Return output and don't print it. 61 | * Taking input and printing output is handled automatically. 62 | */ 63 | 64 | //This problem is of 0-1 knapsack kind. 65 | 66 | 67 | vector > dp(numDenominations+1,vector(value+1,0)); 68 | int ans=helper(dp,denominations,numDenominations,value); 69 | 70 | return ans; 71 | 72 | } 73 | 74 | int main(){ 75 | 76 | int numDenominations; 77 | cin >> numDenominations; 78 | int* denominations = new int[numDenominations]; 79 | for(int i = 0; i < numDenominations; i++){ 80 | cin >> denominations[i]; 81 | } 82 | int value; 83 | cin >> value; 84 | 85 | cout << countWaysToMakeChange(denominations, numDenominations, value); 86 | 87 | } 88 | -------------------------------------------------------------------------------- /Hashing/Pair Sum to Zero.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a random integer array A of size N. Find and print the pair of elements in the array which sum to 0. 3 | Array A can contain duplicate elements. 4 | While printing a pair, print the smaller element first. 5 | 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. You can print pairs in any order, just be careful about the order of elements in a pair. 6 | Input format : 7 | 8 | Line 1 : Integer N (Array size) 9 | Line 2 : Array elements (separated by space) 10 | 11 | Output format : 12 | 13 | Line 1 : Pair 1 elements (separated by space) 14 | Line 2 : Pair 2 elements (separated by space) 15 | Line 3 : and so on 16 | 17 | Constraints : 18 | 1 <= N <= 10^6 19 | Ai contains all non-zero values 20 | Sample Input: 21 | 22 | 5 23 | 2 1 -2 2 3 24 | 25 | Sample Output : 26 | 27 | -2 2 28 | -2 2 29 | 30 | 31 | */ 32 | 33 | #include 34 | using namespace std; 35 | 36 | void PairSum(int *input, int n) { 37 | 38 | /* Don't write main(). 39 | * the input array is already passed as function argument. 40 | * Don't need to return anything. Print the desired pairs in the function itself. 41 | */ 42 | // Key=Element, Value=frequency, index 43 | unordered_map m; 44 | 45 | for(int i=0;i0){ 55 | a=-input[i]; 56 | b=input[i]; 57 | } 58 | else{ 59 | a=input[i]; 60 | b=-input[i]; 61 | } 62 | cout< 70 | using namespace std; 71 | #include "solution.h" 72 | 73 | int main() 74 | { 75 | int n; 76 | int arr[100000]; 77 | cin>>n; 78 | for(int i=0; i>arr[i]; 81 | } 82 | PairSum(arr, n); 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /DP (1D)/Number_of_APs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of n positive integers. The task is to count the number of Arithmetic Progression subsequences in the array. As the answer could be very large, output it modulo 100001. 3 | Note: Empty sequence or single element sequence is Arithmetic Progression. 4 | Input Format: 5 | 6 | First Line: N (the size of the array) 7 | Second Line: Elements of the array separated by spaces. 8 | 9 | Output: 10 | 11 | Print total number of subsequences 12 | 13 | Input Constraints: 14 | 15 | 1 <= arr[i] <= 1000 16 | 1 <= sizeof(arr) <= 1000 17 | 18 | Sample Input 1 : 19 | 20 | 3 21 | 1 2 3 22 | 23 | Sample output: 24 | 25 | 8 26 | 27 | Sample Output Explanation: 28 | 29 | Total subsequence are: {}, { 1 }, { 2 }, { 3 }, { 1, 2 }, { 2, 3 }, { 1, 3 }, { 1, 2, 3 } 30 | 31 | Sample Input 2: 32 | 33 | 7 34 | 1 2 3 4 5 9 10 35 | 36 | Sample Output: 37 | 38 | 37 39 | 40 | */ 41 | 42 | #include 43 | #define MOD 100001 44 | using namespace std; 45 | 46 | int numofAP(int *arr, int N){ 47 | /* 48 | Return all possible AP subsequences formed from the given integer array. You do not need to take input or print anything. 49 | Just return the ans. 50 | */ 51 | int mina=INT_MAX,maxa=INT_MIN; 52 | 53 | for(int i=0;i=1 && arr[i]-d<=100000) 71 | dp[i]=(dp[i]+sum[arr[i]-d])%MOD; 72 | 73 | count=(count+dp[i]-1)%MOD; 74 | 75 | sum[arr[i]]=(sum[arr[i]]+dp[i])%MOD; 76 | } 77 | } 78 | return count; 79 | 80 | 81 | } 82 | 83 | int main(){ 84 | 85 | int N; 86 | cin >> N; 87 | 88 | int *arr = new int[N+1]; 89 | for(int i = 0; i < N; i++){ 90 | cin >> arr[i]; 91 | } 92 | cout << numofAP(arr, N) << endl; 93 | 94 | return 0; 95 | } -------------------------------------------------------------------------------- /Trees/SumOfAllNodes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a generic tree, count and return the sum of all nodes present in the given tree. 3 | Input format : 4 | 5 | Elements in level order form separated by space (as per done in class). Order is - 6 | Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 7 | 8 | Output Format : 9 | 10 | Sum of all nodes 11 | 12 | Sample Input : 13 | 14 | 10 3 20 30 40 2 40 50 0 0 0 0 15 | 16 | Sample Output : 17 | 18 | 190 19 | 20 | */ 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 | int sumOfNodes(TreeNode* root) { 45 | /* Don't write main(). 46 | * Don't read input, it is passed as function argument. 47 | * Return output and don't print it. 48 | * Taking input and printing output is handled automatically. 49 | */ 50 | int ans=root->data; 51 | for(int i=0;ichildren.size();i++) 52 | ans+=sumOfNodes(root->children[i]); 53 | return ans; 54 | 55 | } 56 | 57 | #include 58 | 59 | TreeNode* takeInputLevelWise() { 60 | int rootData; 61 | cin >> rootData; 62 | TreeNode* root = new TreeNode(rootData); 63 | 64 | queue*> pendingNodes; 65 | 66 | pendingNodes.push(root); 67 | while (pendingNodes.size() != 0) { 68 | TreeNode* front = pendingNodes.front(); 69 | pendingNodes.pop(); 70 | int numChild; 71 | cin >> numChild; 72 | for (int i = 0; i < numChild; i++) { 73 | int childData; 74 | cin >> childData; 75 | TreeNode* child = new TreeNode(childData); 76 | front->children.push_back(child); 77 | pendingNodes.push(child); 78 | } 79 | } 80 | return root; 81 | } 82 | 83 | int main() { 84 | TreeNode* root = takeInputLevelWise(); 85 | cout << sumOfNodes(root) << endl; 86 | } 87 | -------------------------------------------------------------------------------- /Trees/FindHeight.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a generic tree, find and return the height of given tree. 3 | Input format : 4 | 5 | Elements in level order form separated by space (as per done in class). Order is - 6 | Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 7 | 8 | Output Format : 9 | 10 | Height 11 | 12 | Sample Input : 13 | 14 | 10 3 20 30 40 2 40 50 0 0 0 0 15 | 16 | Sample Output : 17 | 18 | 3 19 | */ 20 | 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 | int height(TreeNode* root) { 45 | /* Don't write main(). 46 | * Don't read input, it is passed as function argument. 47 | * Return output and don't print it. 48 | * Taking input and printing output is handled automatically. 49 | */ 50 | if(root==NULL) 51 | return 0; 52 | 53 | int ans=1; 54 | for(int i=0;ichildren.size();i++){ 55 | ans=max(ans,1+height(root->children[i])); 56 | } 57 | return ans; 58 | 59 | } 60 | 61 | 62 | #include 63 | TreeNode* takeInputLevelWise() { 64 | int rootData; 65 | cin >> rootData; 66 | TreeNode* root = new TreeNode(rootData); 67 | 68 | queue*> pendingNodes; 69 | 70 | pendingNodes.push(root); 71 | while (pendingNodes.size() != 0) { 72 | TreeNode* front = pendingNodes.front(); 73 | pendingNodes.pop(); 74 | int numChild; 75 | cin >> numChild; 76 | for (int i = 0; i < numChild; i++) { 77 | int childData; 78 | cin >> childData; 79 | TreeNode* child = new TreeNode(childData); 80 | front->children.push_back(child); 81 | pendingNodes.push(child); 82 | } 83 | } 84 | return root; 85 | } 86 | 87 | int main() { 88 | TreeNode* root = takeInputLevelWise(); 89 | cout << height(root) << endl; 90 | } 91 | -------------------------------------------------------------------------------- /Arrays & Strings/Push_Zeroes To End.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a random integer array, push all the zeros that are present to end of the array. The respective order of other elements should remain same. 3 | Change in the input array itself. You don't need to return or print elements. Don't use extra array. 4 | Note : You need to do this in one scan of array only. 5 | Input format : 6 | 7 | Line 1 : Integer N, Array Size 8 | Line 2 : Array elements (separated by space) 9 | 10 | Output Format : 11 | 12 | Array elements (separated by space) 13 | 14 | Constraints : 15 | 1 <= N <= 10^6 16 | Sample Input 1: 17 | 18 | 7 19 | 2 0 4 1 3 0 28 20 | 21 | Sample Output 1: 22 | 23 | 2 4 1 3 28 0 0 24 | 25 | Sample Input 2: 26 | 27 | 5 28 | 0 3 0 2 0 29 | 30 | Sample Output 2: 31 | 32 | 3 2 0 0 0 33 | 34 | 35 | */ 36 | 37 | // arr - input array 38 | // n - size of array 39 | 40 | #include 41 | using namespace std; 42 | 43 | void swap(int a[],int i,int j){ 44 | int temp=a[i]; 45 | a[i]=a[j]; 46 | a[j]=temp; 47 | } 48 | 49 | void printarr(int a[],int n){ 50 | for(int i=0;i 85 | #include "solution.h" 86 | using namespace std; 87 | 88 | int main() { 89 | 90 | int size; 91 | 92 | cin>>size; 93 | int *input=new int[1+size]; 94 | 95 | for(int i=0;i>input[i]; 97 | 98 | PushZeroesEnd(input,size); 99 | for(int i=0;i 30 | #include 31 | #include 32 | using namespace std; 33 | 34 | 35 | int smallestSuperSequence(char str1[], int len1, char str2[], int len2) { 36 | /* Don't write main(). 37 | Don't read input, it is passed as function argument. 38 | Return output and don't print it. 39 | Taking input and printing output is handled automatically. 40 | */ 41 | //We can have a dp array which at i,jth entry will store: Lenght smallest superstring 42 | 43 | int dp[len1+1][len2+1]={0}; 44 | 45 | //Inittialization 46 | 47 | for(int i=0;i<=len1;i++){ 48 | dp[i][0]=i; 49 | } 50 | for(int i=0;i<=len2;i++){ 51 | dp[0][i]=i; 52 | } 53 | 54 | for(int i=1;i<=len1;i++){ 55 | for(int j=1;j<=len2;j++){ 56 | 57 | if(str1[i-1]==str2[j-1]) 58 | dp[i][j]=1+dp[i-1][j-1]; 59 | else 60 | dp[i][j]=1+min(dp[i-1][j],dp[i][j-1]); 61 | } 62 | } 63 | 64 | //Print dp table 65 | /* 66 | for(int i=0;i<=len1;i++){ 67 | for(int j=0;j<=len2;j++){ 68 | cout<>str1; 82 | cin>>str2; 83 | int len1 = strlen(str1); 84 | int len2 = strlen(str2); 85 | int min_len = smallestSuperSequence(str1, len1, str2, len2); 86 | cout< 3 | 4 | class Trie { 5 | TrieNode *root; 6 | 7 | public : 8 | 9 | Trie() { 10 | root = new TrieNode('\0'); 11 | } 12 | 13 | bool search(TrieNode *root, string word) { 14 | if(word.size() == 0) { 15 | return root -> isTerminal; 16 | } 17 | 18 | // Small Calculation 19 | int index = word[0] - 'a'; 20 | TrieNode *child; 21 | if(root -> children[index] != NULL) { 22 | child = root -> children[index]; 23 | } 24 | else { 25 | return false; 26 | } 27 | 28 | // Recursive call 29 | return search(child, word.substr(1)); 30 | } 31 | 32 | bool search(string word) { 33 | return search(root, word); 34 | } 35 | 36 | 37 | void insertWord(TrieNode *root, string word) { 38 | // Base case 39 | if(word.size() == 0) { 40 | root -> isTerminal = true; 41 | return; 42 | } 43 | 44 | // Small Calculation 45 | int index = word[0] - 'a'; 46 | TrieNode *child; 47 | if(root -> children[index] != NULL) { 48 | child = root -> children[index]; 49 | } 50 | else { 51 | child = new TrieNode(word[0]); 52 | root -> children[index] = child; 53 | } 54 | 55 | // Recursive call 56 | insertWord(child, word.substr(1)); 57 | } 58 | 59 | // For user 60 | void insertWord(string word) { 61 | insertWord(root, word); 62 | } 63 | 64 | void removeWord(TrieNode *root, string word) { 65 | // Base case 66 | if(word.size() == 0) { 67 | root -> isTerminal = false; 68 | return; 69 | } 70 | 71 | // Small calculation 72 | TrieNode *child; 73 | int index = word[0] - 'a'; 74 | if(root -> children[index] != NULL) { 75 | child = root -> children[index]; 76 | } 77 | else { 78 | // Word not found 79 | return; 80 | } 81 | 82 | removeWord(child, word.substr(1)); 83 | 84 | // Remove child Node if it is useless 85 | if(child -> isTerminal == false) { 86 | for(int i = 0; i < 26; i++) { 87 | if(child -> children[i] != NULL) { 88 | return; 89 | } 90 | } 91 | delete child; 92 | root -> children[index] = NULL; 93 | } 94 | } 95 | 96 | 97 | 98 | 99 | void removeWord(string word) { 100 | removeWord(root, word); 101 | } 102 | 103 | 104 | 105 | }; 106 | -------------------------------------------------------------------------------- /DP (2D)/Knapsack0-1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A thief robbing a store and can carry a maximal weight of W into his knapsack. There are N items and ith item weigh wi and is of value vi. What is the maximum value V, that thief can take ? 3 | Space complexity should be O(n). 4 | Input Format : 5 | 6 | Line 1 : N i.e. number of items 7 | Line 2 : N Integers i.e. weights of items separated by space 8 | Line 3 : N Integers i.e. values of items separated by space 9 | Line 4 : Integer W i.e. maximum weight thief can carry 10 | 11 | Output Format : 12 | 13 | Line 1 : Maximum value V 14 | 15 | Constraints 16 | 1 <= N <= 10^4 17 | 1<= wi <= 100 18 | 1 <= vi <= 100 19 | Sample Input 1 : 20 | 21 | 4 22 | 1 2 4 5 23 | 5 4 8 6 24 | 5 25 | 26 | Sample Output : 27 | 28 | 13 29 | 30 | */ 31 | 32 | #include 33 | using namespace std; 34 | 35 | 36 | int knapsack(int* weights, int* values, int n, int maxWeight){ 37 | 38 | /* Don't write main(). 39 | * Don't read input, it is passed as function argument. 40 | * Return output and don't print it. 41 | * Taking input and printing output is handled automatically. 42 | */ 43 | 44 | //Let's have dp array which stores max profit at i for capacity i 45 | 46 | int dp[maxWeight+1]={0}; 47 | 48 | for(int i=0;i=weights[i];j--){ 51 | 52 | dp[j]=max(dp[j],values[i]+dp[j-weights[i]]); 53 | } 54 | } 55 | return dp[maxWeight]; 56 | 57 | /* ******Recursive Solution for basic understanding************ 58 | if(n==0 || maxWeights==0) 59 | return 0; 60 | 61 | if(weights[n-1]>maxWeights) 62 | return knapsack(weights,values, n-1,maxWeight); 63 | 64 | else 65 | return max(val[n-1]+knapsack(weights,values,n-1,maxWeight-weights[n-1]),knapsack(weights,values,n-1,maxWeight)); 66 | */ 67 | 68 | } 69 | 70 | 71 | 72 | 73 | int main(){ 74 | 75 | int n; 76 | cin >> n; 77 | int* weights = new int[n]; 78 | int* values = new int[n]; 79 | 80 | for(int i = 0; i < n; i++){ 81 | cin >> weights[i]; 82 | } 83 | 84 | for(int i = 0; i < n; i++){ 85 | cin >> values[i]; 86 | } 87 | 88 | int maxWeight; 89 | cin >> maxWeight; 90 | 91 | cout << knapsack(weights, values, n, maxWeight); 92 | 93 | } 94 | 95 | 96 | -------------------------------------------------------------------------------- /DP (1D)/ByteLand.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | In Byteland, they have a very strange monetary system. Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit). The coins can be exchanged as many times as you want. That is, if initially you have a coin of value 500, you can first exchange into 250, 166 and 125. And after that you can further exchange your 250 coin into 125, 83, 62. So we can exchange our any coin as many times as we want. 3 | You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. 4 | You have one gold coin. What is the maximum amount of American dollars you can get for it? 5 | 6 | Input format : A single integer N, denoting value of your gold coin 7 | 8 | Output Format : A single integer, denoting the maximum amount of American dollars you can make 9 | Sample Input 1 : 10 | 11 | 12 12 | 13 | Sample Output 1 : 14 | 15 | 13 16 | 17 | Sample Output 1 Explanation : 18 | You can change 12 into 6, 4 and 3, and then change these into $6+$4+$3 = $13. 19 | Sample Input 2 : 20 | 21 | 2 22 | 23 | Sample Output 1 : 24 | 25 | 2 26 | 27 | Sample Output 2 Explanation : 28 | If you try changing the coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1 out of them. It is better just to change the 2 coin directly into $2. 29 | 30 | */ 31 | 32 | // int64_t is a data type of 8 byte integer. 33 | 34 | #include 35 | #include 36 | #include 37 | using namespace std; 38 | 39 | int64_t cal(vector &dp,int64_t n) 40 | { 41 | if(n<10) 42 | return n; 43 | if(n<10000000) 44 | { 45 | if(dp[n]) 46 | return dp[n]; 47 | 48 | int64_t ans=cal(dp,n/2)+cal(dp,n/3)+cal(dp,n/4); 49 | 50 | dp[n]=max(n,ans); 51 | 52 | return dp[n]; 53 | } 54 | 55 | 56 | } 57 | 58 | int64_t bytelandian(int64_t n) { 59 | // Write your code here 60 | 61 | vector dp(10000000,0); 62 | 63 | int64_t ans=cal(dp,n); 64 | 65 | return ans; 66 | 67 | } 68 | 69 | int main() { 70 | int64_t n; 71 | cin>>n; 72 | int64_t x=bytelandian(n); 73 | cout< 2 | using namespace std; 3 | 4 | int lcs(char* s1, char* s2) { 5 | if (s1[0] == '\0' || s2[0] == '\0') { 6 | return 0; 7 | } 8 | 9 | if (s1[0] == s2[0]) { 10 | return 1 + lcs(s1 + 1, s2 + 1); 11 | } else { 12 | int option1 = lcs(s1, s2 + 1); 13 | int option2 = lcs(s1 + 1, s2); 14 | return max(option1, option2); 15 | } 16 | } 17 | 18 | int lcsI(char* s1, char* s2) { 19 | int m = strlen(s1); 20 | int n = strlen(s2); 21 | int** dp = new int*[m + 1]; 22 | for (int i = 0; i <= m; i++) { 23 | dp[i] = new int[n + 1]; 24 | } 25 | for (int i = 0; i <= m; i++) { 26 | dp[i][0] = 0; 27 | } 28 | for (int i = 0; i <=n ;i++) { 29 | dp[0][i] = 0; 30 | } 31 | 32 | for (int i = 1; i <= m; i++) { 33 | for (int j = 1; j<= n; j++) { 34 | if (s1[m - i] == s2[n - j]) { 35 | dp[i][j] = 1 + dp[i - 1][j - 1]; 36 | } else { 37 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 38 | } 39 | } 40 | } 41 | 42 | int ans = dp[m][n]; 43 | // delete 2d array 44 | for (int i =0; i <= m; i++) { 45 | delete [] dp[i]; 46 | } 47 | delete [] dp; 48 | return ans; 49 | } 50 | 51 | int lcs2Helper(char* s1, char* s2, int m, int n, int** dp) { 52 | if (m == 0 || n == 0) { 53 | return 0; 54 | } 55 | 56 | if (dp[m][n] > -1) { 57 | return dp[m][n]; 58 | } 59 | 60 | int ans; 61 | if (s1[0] == s2[0]) { 62 | ans = 1 + lcs2Helper(s1 + 1, s2 + 1, m - 1, n - 1, dp); 63 | } else { 64 | int option1 = lcs2Helper(s1, s2 + 1, m, n - 1, dp); 65 | int option2 = lcs2Helper(s1 + 1, s2, m - 1, n, dp); 66 | ans = max(option1, option2); 67 | } 68 | dp[m][n] = ans; 69 | return ans; 70 | } 71 | 72 | int lcs2(char* s1, char* s2) { 73 | int m = strlen(s1); 74 | int n = strlen(s2); 75 | int** dp = new int*[m + 1]; 76 | for (int i = 0; i <= m; i++) { 77 | dp[i] = new int[n + 1]; 78 | for (int j = 0; j <= n; j++) { 79 | dp[i][j] = -1; 80 | } 81 | } 82 | int ans = lcs2Helper(s1, s2, m, n, dp); 83 | for (int i =0; i <= m; i++) { 84 | delete [] dp[i]; 85 | } 86 | delete [] dp; 87 | return ans; 88 | } 89 | 90 | int main() { 91 | char a[100]; 92 | char b[100]; 93 | cin >> a; 94 | cin >> b; 95 | cout << lcsI(a, b) << endl; 96 | cout << lcs2(a, b) << endl; 97 | cout << lcs(a, b) << endl; 98 | } 99 | 100 | -------------------------------------------------------------------------------- /Trees/CountLeafNodes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a generic tree, count and return the number of leaf nodes present in the given tree. 3 | Input format : 4 | 5 | Elements in level order form separated by space (as per done in class). Order is - 6 | Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element 7 | 8 | Output Format : 9 | 10 | Count of leaf nodes 11 | 12 | Sample Input 1 : 13 | 14 | 10 3 20 30 40 2 40 50 0 0 0 0 15 | 16 | Sample Output 1 : 17 | 18 | 4 19 | 20 | */ 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 | int numLeafNodes(TreeNode* root) { 45 | /* Don't write main(). 46 | * Don't read input, it is passed as function argument. 47 | * Return output and don't print it. 48 | * Taking input and printing output is handled automatically. 49 | */ 50 | if(root->children.size()==0) 51 | return 1; 52 | int ans=0; 53 | for(int i=0;ichildren.size();i++){ 54 | ans+=numLeafNodes(root->children[i]); 55 | } 56 | return ans; 57 | 58 | 59 | } 60 | 61 | #include 62 | TreeNode* takeInputLevelWise() { 63 | int rootData; 64 | cin >> rootData; 65 | TreeNode* root = new TreeNode(rootData); 66 | 67 | queue*> pendingNodes; 68 | 69 | pendingNodes.push(root); 70 | while (pendingNodes.size() != 0) { 71 | TreeNode* front = pendingNodes.front(); 72 | pendingNodes.pop(); 73 | int numChild; 74 | cin >> numChild; 75 | for (int i = 0; i < numChild; i++) { 76 | int childData; 77 | cin >> childData; 78 | TreeNode* child = new TreeNode(childData); 79 | front->children.push_back(child); 80 | pendingNodes.push(child); 81 | } 82 | } 83 | return root; 84 | } 85 | 86 | int main() { 87 | TreeNode* root = takeInputLevelWise(); 88 | cout << numLeafNodes(root) << endl; 89 | } 90 | -------------------------------------------------------------------------------- /DP (1D)/Min Number of chocolates.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Noor is a teacher. She wants to give some chocolates to the students in her class. All the students sit in a line and each of them has a score according to performance. Noor wants to give at least 1 chocolate to each student. She distributes chocolates to them such that If two students sit next to each other then the one with the higher score must get more chocolates. Noor wants to save money, so she wants to minimise the total number of chocolates. 3 | Note that when two students have equal score they are allowed to have different number of chocolates. 4 | Input Format: 5 | 6 | First Line: Integer N, the number of students in Noor’s class. 7 | Second Line: Each of the student's score separated by spaces. 8 | 9 | Output Format: 10 | 11 | Output a single line containing the minimum number of chocolates Noor must give. 12 | 13 | Input Constraints 14 | 15 | 1 <= N <= 100000 16 | 1 <= score <= 100000 17 | 18 | Sample Input: 19 | 20 | 4 21 | 1 4 4 6 22 | 23 | sample Output: 24 | 25 | 6 26 | 27 | Sample Input: 28 | 29 | 3 30 | 8 7 5 31 | 32 | sample Output: 33 | 34 | 6 35 | 36 | */ 37 | 38 | #include 39 | using namespace std; 40 | int getMin(int *arr, int n){ 41 | /* Don't write main(). 42 | Don't read input, it is passed as function argument. 43 | Return output and don't print it. 44 | Taking input and printing output is handled automatically. 45 | */ 46 | int dp[n]; 47 | 48 | dp[0]=1; 49 | 50 | for(int i=1;i1)?1:dp[i-1]; 56 | } 57 | 58 | else{ 59 | int j=i; 60 | dp[j]=1; 61 | while(arr[j-1]>arr[j]){ 62 | dp[j-1]=(dp[j-1]<=dp[j])?dp[j-1]+1:dp[j-1]; 63 | j--; 64 | } 65 | } 66 | } 67 | 68 | int sum=0; 69 | for(int i=0;i> n; 83 | int *arr = new int[n]; 84 | for(int i = 0; i < n; i++){ 85 | cin >> arr[i]; 86 | } 87 | 88 | cout << getMin(arr, n); 89 | delete []arr; 90 | } -------------------------------------------------------------------------------- /Hashing/Print Intersection.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two random integer arrays, print their intersection. That is, print all the elements that are present in both the given arrays. 3 | Input arrays can contain duplicate elements. 4 | Note : Order of elements are not important 5 | Input format : 6 | 7 | Line 1 : Integer N, Array 1 Size 8 | Line 2 : Array 1 elements (separated by space) 9 | Line 3 : Integer M, Array 2 Size 10 | Line 4 : Array 2 elements (separated by space) 11 | 12 | Output format : 13 | 14 | Print intersection elements in different lines 15 | 16 | Constraints : 17 | 1 <= M, N <= 10^6 18 | Sample Input 1 : 19 | 20 | 6 21 | 2 6 8 5 4 3 22 | 4 23 | 2 3 4 7 24 | 25 | Sample Output 1 : 26 | 27 | 2 28 | 4 29 | 3 30 | 31 | Sample Input 2 : 32 | 33 | 4 34 | 2 6 1 2 35 | 5 36 | 1 2 3 4 2 37 | 38 | Sample Output 2 : 39 | 40 | 2 41 | 2 42 | 1 43 | 44 | */ 45 | 46 | // input1 - first array 47 | // input2 - second array 48 | // size1 - size of first array 49 | // size2 - size of second array 50 | 51 | #include 52 | using namespace std; 53 | 54 | void intersection(int input1[], int input2[], int size1, int size2) { 55 | /* Don't write main(). 56 | * Don't read input, it is passed as function argument. 57 | * Print the output and don't return it. 58 | * Taking input is handled automatically. 59 | */ 60 | unordered_map m; 61 | 62 | for(int i=0;i 79 | #include 80 | #include 81 | using namespace std; 82 | #include "solution.h" 83 | 84 | int main() { 85 | 86 | int size1,size2; 87 | 88 | cin>>size1; 89 | int *input1=new int[1+size1]; 90 | 91 | for(int i=0;i>input1[i]; 93 | 94 | cin>>size2; 95 | int *input2=new int[1+size2]; 96 | 97 | for(int i=0;i>input2[i]; 99 | 100 | 101 | intersection(input1,input2,size1,size2); 102 | 103 | 104 | return 0; 105 | } 106 | --------------------------------------------------------------------------------