├── .gitignore ├── Array ├── antiSpiral.cpp ├── chewbacca.cpp ├── formBiggestNumber..cpp ├── insertionSort.cpp ├── largestString.cpp ├── longestIncSub.cpp ├── magicalPark.cpp ├── maxSumArray.cpp ├── maxSumCircular.cpp ├── palindromeString.cpp ├── rainwaterHarvesting.cpp ├── readline.cpp ├── removeDuplicates.cpp ├── rotate.cpp ├── subarrays.cpp ├── sumOfSubmatrices.cpp ├── sumPair.cpp └── sumTriplets.cpp ├── Binary Search Tree ├── BSTfromPreoder.cpp ├── operations.cpp ├── topView.cpp ├── verticalSum.cpp └── verticalTraversal.cpp ├── Binary Search ├── .cph │ └── .ekoSPOJ.cpp_baeafec6458b3d28449f000e109cee55.prob ├── aggressiveCowsSPOJ.cpp ├── bookAllocation.cpp ├── ekoSPOJ.cpp ├── paintersPartition.cpp └── prataSPOJ.cpp ├── Binary Tree ├── LCA&ShortestDist2Nodes.cpp ├── allNodesDistanceKFromTarget.2.cpp ├── allNodesDistanceKFromTarget.cpp ├── buildFromPreAndInOrder.cpp ├── maxSumPath.cpp ├── rightView.cpp ├── traversals.cpp └── treeOperations.cpp ├── Bitmasking ├── .cph │ ├── .fastExponential.cpp_30bcb6d052ce7c314267a9c4487c4627.prob │ ├── .operations.cpp_cfdce468752acd6353bf575cd9fe3862.prob │ ├── .uniqueNumberII.cpp_5e956212c06c31939578e2635272c2af.prob │ └── .uniqueNumberIII.cpp_c2e3738b9cf9bde1e2cd19ea3cf3c14c.prob ├── fastExponential.cpp ├── operations.cpp ├── powerSet_GFG.cpp ├── uniqueNumberII.cpp └── uniqueNumberIII.cpp ├── Dynamic Programming ├── 0-1_knapsack.cpp ├── LCS.cpp ├── coinChange.cpp ├── editDistance.cpp ├── eggDropping.cpp ├── fibonacci.cpp ├── input.txt ├── longestIncreasingSubsequence.cpp ├── matrixChainMultiplication.cpp ├── maxSubarraySum.cpp ├── mitosis.cpp ├── mixture2.cpp ├── mixturesSPOJ.cpp ├── n-k_ladder.cpp ├── optimalGameStrategy.cpp ├── output.txt ├── palPartitioning.cpp ├── robotPathsCodechef.cpp └── winesDP.cpp ├── Graphs ├── DSU_cycleDetection_unionByRank_pathCompression.cpp ├── FINAL_cycleDetect_DIRECTED.cpp ├── LCA__binaryLifting.cpp ├── LCA__twoPointers.cpp ├── adjListHashmap.cpp ├── adjacencyList.cpp ├── articulationPointAndBridges.cpp ├── bellmanFord.cpp ├── bfs1.cpp ├── bfsGeneric.cpp ├── bfs_SSSP.cpp ├── bipartite.cpp ├── cycleDetection_directed.cpp ├── cycleDetection_undirected.cpp ├── dfs.cpp ├── dfs_cycleDetection__Directed.cpp ├── dijkstra.cpp ├── dijkstraWithPath.cpp ├── eulerTour.cpp ├── fieldOFDreams.cpp ├── floodFill.cpp ├── floodFillCharacters.cpp ├── floodFillColorCount.cpp ├── floydWarshall.cpp ├── input.txt ├── kosaraju.cpp ├── kosaraju__SrcSink__MAIN.cpp ├── kruskals.cpp ├── largestIslandME.cpp ├── largestIslandNN.cpp ├── output.txt ├── prims.cpp ├── printAncestorsTree.cpp ├── shortesPathGrid.cpp ├── snakesLadders.cpp ├── topologicalSort.cpp └── travellingSalesman.cpp ├── Greedy ├── activitySelectionSPOJ.cpp ├── baisedSPOJ.cpp ├── defkinSPOJ.cpp ├── expeditionSPOJ.cpp ├── input.txt ├── loadBalancerSPOJ.cpp ├── maxCircles.cpp └── output.txt ├── Hashing - Tries Challenges ├── NOT_COMPLETErangeXOR.cpp ├── arraysIntersection.cpp ├── countRectangles.cpp ├── countTriangles.cpp ├── digitalDIctionary.cpp ├── digitalDictionaryCB.cpp ├── existsOrNot.cpp ├── highestFreq.cpp ├── input.txt ├── maxXORSubarray.cpp ├── output.txt ├── stringWindow.cpp ├── sumSubarraysDistinct.cpp └── verticalTraversal.cpp ├── Hashing ├── hashTable.cpp ├── hashTable.h ├── longestConsecutiveSubsequenceMAP.cpp ├── longestConsecutiveSubsequenceSET.cpp ├── longestSubarrayWithGivenSum.cpp ├── rightAngledTriangles.cpp └── smallestWIndowSubstring.cpp ├── Heaps ├── buildHeapFromArray.cpp ├── heapSort.cpp ├── joinRopes.cpp ├── kLargest.cpp ├── kMostFreqWords.cpp ├── mergeKSortedArrays.cpp ├── operations.cpp ├── priorityQ_CustomClass.cpp ├── runningMedian.cpp └── topKFrequent.cpp ├── LRUCache.cpp ├── LRUCache_LEETCODE.cpp ├── Linked List ├── LLappend ├── LLappend.cpp ├── floydCycle ├── floydCycle.cpp ├── intersection ├── intersection.cpp ├── kReverse.cpp ├── mergeSortedLL.cpp ├── oddFollowedByEven.cpp ├── palindrome └── palindrome.cpp ├── My Template.txt ├── New Template.cpp ├── Number Theory ├── .cph │ ├── .prime1SPOJ.cpp_c231adfd75d997f3b2cd5c117d48f18b.prob │ └── .primeFactors.cpp_f20fa846ca04495405dd8a60d629d5db.prob ├── aFactorialProblem.cpp ├── largePrime.cpp ├── prime1SPOJ.cpp ├── primeFactors.cpp ├── primeSieve ├── primeSieve.cpp └── primeinRangeFASTER.cpp ├── Others ├── GFGSumCircular.cpp ├── GFGformBiggestSum.cpp ├── carSortingVECTOR ├── carSortingVECTOR.cpp ├── goldendeal.cpp ├── indianMoneySTL.cpp └── max.cpp ├── Queue ├── .cph │ └── .nonRepeatingCharacter.cpp_c64a5375fdc9c294067a4fe0a54fa768.prob ├── implementationArray.cpp ├── implementationLL.cpp ├── largestRectangularAreaHISTOGRAM.cpp ├── nextGreater2.cpp ├── nonRepeatingCharacter.cpp ├── prateekCoding.cpp ├── queueUsingStacks.cpp ├── queueWithStacks2.cpp └── redundantBrackets.cpp ├── README.md ├── Recursion ├── Recursion Challenges │ ├── generate_strings_mapped.cpp │ ├── indices.cpp │ ├── remove_dup.cpp │ ├── replace_dup__.cpp │ ├── replace_pi.cpp │ ├── replace_x.cpp │ ├── smart_keypad_1.cpp │ ├── string_subsequence.cpp │ └── towerofhanoi.cpp ├── friendspair.cpp ├── inversionCount.cpp ├── occurences.cpp ├── quickSort.cpp ├── rMerge.cpp ├── recursiveBubbleSort.cpp ├── sudokuSolver.cpp └── tiling.cpp ├── Sorting ├── .cph │ ├── .kthRoot.cpp_ec45fa239f6ff86695833d6fe35eb036.prob │ ├── .pivot.cpp_92c3a12f5415a5c050f9b8800b229d3a.prob │ ├── .searchRotated.cpp_51fd8b92800f52cfca2aac316ffdd064.prob │ ├── .sortgame.cpp_dd0ab307903c7282eb681d2ccd5969d2.prob │ ├── .stringSort.cpp_fdb6080d6adbb51f0b935fff51995cf9.prob │ └── .upperAndLowerBound.cpp_a936454cddab71410a18a1b0b43feacd.prob ├── kthRoot.cpp ├── pivot.cpp ├── searchRotated ├── searchRotated.cpp ├── sortgame.cpp ├── sortingLinear.cpp ├── stringSort.cpp └── upperAndLowerBound.cpp ├── Stack ├── balancedParenthesis ├── balancedParenthesis.cpp ├── implementaionLL ├── implementaionLL.cpp ├── implementationArray ├── implementationArray.cpp ├── implementationVector ├── implementationVector.cpp ├── largestAreaHistogram ├── largestAreaHistogram.cpp ├── nextGreater.cpp ├── reverseStack1 ├── reverseStack1.cpp ├── reverseStackRecursion ├── reverseStackRecursion.cpp ├── stockSpan └── stockSpan.cpp ├── Strings ├── CBNumber.cpp ├── canYouReadThis.cpp ├── isPalRecursion.cpp ├── maxCharFreq.cpp ├── sortString ├── sortString.cpp ├── stringCompression ├── stringCompression.cpp └── ultrafastmathematicians.cpp ├── Trees Challenges ├── BST_to_LL_FLATTEN.cpp ├── bottomView.cpp ├── isBalanced.cpp ├── keysInRange.cpp ├── structurallyIndenticalTree.cpp ├── sumAtK.cpp └── zigzag.cpp ├── Tries ├── (same)checkIfWordsArePresentInTheSENTENCE.cpp ├── areWordsPresentInTheSentence.cpp ├── completeString_CN.cpp ├── countDistinctSubstrings_CN.cpp ├── implement_ii_CN.cpp ├── largestXOR.cpp ├── prefixTrie.cpp ├── suffixTrie.cpp └── trie_implement1_leetcode.cpp ├── binaryTreeCreation.cpp ├── interv.png ├── jdbc steps.txt ├── longestCommonSUBSTRING.cpp └── quickSort.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | -------------------------------------------------------------------------------- /Array/antiSpiral.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void input2D(int mat[][10], int m, int n) 5 | { 6 | for (int i = 0; i < m; ++i) 7 | { 8 | for (int j = 0; j < n; ++j) 9 | { 10 | cin >> mat[i][j]; 11 | } 12 | } 13 | } 14 | 15 | void printSpiral(int mat[][10], int m, int n) 16 | { 17 | int left = 0; 18 | int right = n - 1; 19 | int top = 0; 20 | int bottom = m - 1; 21 | 22 | while (left <= right || top <= bottom) 23 | { 24 | 25 | if (left <= right) 26 | { 27 | for (int i = top; i <= bottom; i++) 28 | { 29 | cout << mat[i][left] << ", "; 30 | } 31 | left = left + 1; 32 | } 33 | 34 | if (top <= bottom) 35 | { 36 | for (int i = left; i <= right; i++) 37 | { 38 | cout << mat[bottom][i] << ", "; 39 | } 40 | bottom = bottom - 1; 41 | } 42 | 43 | if (left <= right) 44 | { 45 | for (int row = bottom; row >= top; row--) 46 | { 47 | cout << mat[row][right] << ", "; 48 | } 49 | right--; 50 | } 51 | 52 | if (top <= bottom) 53 | { 54 | for (int col = right; col >= left; col--) 55 | { 56 | cout << mat[top][col] << ", "; 57 | } 58 | ++top; 59 | } 60 | } 61 | 62 | cout << "END"; 63 | } 64 | 65 | int main() 66 | { 67 | int mat[10][10]; 68 | int m, n; 69 | cin >> m >> n; 70 | input2D(mat, m, n); 71 | 72 | printSpiral(mat, m, n); 73 | } 74 | -------------------------------------------------------------------------------- /Array/chewbacca.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char) 7 | 8 | { 9 | 10 | char a[50]; 11 | cin >> a; 12 | 13 | int i = 0; 14 | if (a[i] == '9') 15 | { 16 | i++; 17 | } 18 | 19 | for (; a[i] != '\0'; i++) 20 | { 21 | int digit = a[i] - '0'; 22 | 23 | if (digit >= 5) 24 | { 25 | digit = 9 - digit; 26 | a[i] = digit + '0'; 27 | } 28 | } 29 | cout << a << endl; 30 | } -------------------------------------------------------------------------------- /Array/formBiggestNumber..cpp: -------------------------------------------------------------------------------- 1 | // #include 2 | // #include 3 | // using namespace std; 4 | 5 | // int main() 6 | // { 7 | // string s; 8 | // getline(cin, s); 9 | 10 | // string sij, sji; 11 | 12 | // int len = s.length(); 13 | 14 | // for (int i = 0; i < len - 1; i++) 15 | // { 16 | // for (int j = i + 1; i < len; i++) 17 | // { 18 | // sij = s[i].append(s[j]); 19 | // sji = s[j].append(s[i]); 20 | 21 | // if ((sij).compare(sji) < 0) 22 | // { 23 | // swap(s[i], s[j]); 24 | // } 25 | // } 26 | // } 27 | 28 | // return 0; 29 | // } -------------------------------------------------------------------------------- /Array/insertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void insSort(int a[], int n) 5 | { 6 | 7 | for (int i = 1; i < n - 1; i++) 8 | { 9 | int e = a[i]; 10 | 11 | int j = i - 1; 12 | 13 | while (j >= 0 && a[j] > e) 14 | { 15 | a[j + 1] = a[j]; 16 | j--; 17 | } 18 | 19 | a[j + 1] = e; 20 | } 21 | } 22 | 23 | int main(int argc, char) 24 | { 25 | 26 | int n, key; 27 | cin >> n; 28 | 29 | int a[n]; 30 | 31 | for (int i = 0; i < n; i++) 32 | { 33 | cin >> a[i]; 34 | } 35 | insSort(a, n); 36 | 37 | for (int i = 0; i < n; i++) 38 | cout << a[i]; 39 | } -------------------------------------------------------------------------------- /Array/largestString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(int argc, char) 6 | { 7 | int n; 8 | cin >> n; 9 | 10 | char a[100]; 11 | char largest[100]; 12 | 13 | int len = 0; 14 | int largestlen = 0; 15 | 16 | cin.get(); // to avoid \n as an i/p 17 | 18 | for (int i = 0; i < n; i++) 19 | { 20 | cin.getline(a, 100); 21 | 22 | // cout << a << endl; 23 | 24 | len = strlen(a); 25 | if (len > largestlen) 26 | { 27 | largestlen = len; 28 | strcpy(largest, a); 29 | } 30 | } 31 | 32 | cout << largest << "and" << largestlen << endl; 33 | } -------------------------------------------------------------------------------- /Array/longestIncSub.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | 7 | { 8 | 9 | int n; 10 | cin >> n; 11 | int arr[n]; 12 | 13 | int omax = 0; 14 | int lis[n]; 15 | 16 | for (int i = 0; i < n; i++) 17 | { 18 | cin >> arr[i]; 19 | } 20 | 21 | for (int i = 0; i < n; i++) 22 | { 23 | int max = 0; 24 | 25 | for (int j = 0; j < i; j++) 26 | { 27 | 28 | if (arr[j] < arr[i]) 29 | { 30 | if (lis[j] > max) 31 | { 32 | max = lis[j]; 33 | } 34 | } 35 | } 36 | 37 | lis[i] = max + 1; 38 | 39 | if (lis[i] > omax) 40 | omax = lis[i]; 41 | } 42 | cout << omax; 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Array/magicalPark.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void magical(char a[][100], int m, int n, int k, int s) 5 | { 6 | bool success = true; 7 | 8 | for (int i = 0; i < m; i++) 9 | { 10 | for (int j = 0; j < n; j++) 11 | { 12 | char ch = a[i][j]; 13 | 14 | if (s < k) 15 | { 16 | success = false; 17 | break; 18 | } 19 | 20 | if (ch == '*') 21 | { 22 | s += 5; 23 | } 24 | 25 | else if (ch == '.') 26 | { 27 | s -= 2; 28 | } 29 | 30 | else 31 | { 32 | //# 33 | break; 34 | } 35 | 36 | // lose point when moving right except for the last column 37 | if (j != n - 1) 38 | { 39 | s--; 40 | } 41 | } 42 | } 43 | 44 | if (success) 45 | { 46 | 47 | cout << "Yes" << endl; 48 | cout << s << endl; 49 | } 50 | 51 | else 52 | { 53 | cout << "No" << endl; 54 | } 55 | } 56 | 57 | int main() 58 | { 59 | 60 | int m, n, k, s; 61 | cin >> m >> n >> k >> s; 62 | 63 | char park[100][100]; 64 | 65 | // i/p 66 | 67 | for (int i = 0; i < m; i++) 68 | { 69 | for (int j = 0; j < n; j++) 70 | { 71 | cin >> park[i][j]; 72 | } 73 | } 74 | 75 | magical(park, m, n, k, s); 76 | 77 | return 0; 78 | } -------------------------------------------------------------------------------- /Array/maxSumArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int maxSubArraySum(int a[], int size) 6 | { 7 | int max_so_far = INT_MIN, max_ending_here = 0; 8 | 9 | for (int i = 0; i < size; i++) 10 | { 11 | max_ending_here = max_ending_here + a[i]; 12 | if (max_so_far < max_ending_here) 13 | max_so_far = max_ending_here; 14 | 15 | if (max_ending_here < 0) 16 | max_ending_here = 0; 17 | } 18 | return max_so_far; 19 | } 20 | int main() 21 | { 22 | int t; 23 | cin >> t; 24 | for (int j = 0; j < t; j++) 25 | { 26 | int n; 27 | cin >> n; 28 | int a[n]; 29 | for (int i = 0; i < n; i++) 30 | { 31 | cin >> a[i]; 32 | } 33 | int max_sum = maxSubArraySum(a, n); 34 | cout << max_sum << endl; 35 | } 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Array/maxSumCircular.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(int argc, char) 6 | { 7 | int n; 8 | 9 | cin >> n; 10 | 11 | int a[n]; 12 | int b[n]; 13 | 14 | for (int i = 0; i < n; i++) 15 | { 16 | cin >> a[i]; 17 | b[i] = -a[i]; 18 | } 19 | 20 | // kadane's -> max sum 21 | int cs = 0, ms = 0; 22 | for (int i = 0; i < n; i++) 23 | { 24 | if (b[i] < 0) 25 | cs = 0; 26 | 27 | else 28 | cs += b[i]; 29 | 30 | ms = max(cs, ms); 31 | } 32 | 33 | // array sum 34 | int s = 0; 35 | for (int i = 0; i < n; i++) 36 | { 37 | s += b[i]; 38 | } 39 | 40 | int originalMAX = -(s - ms); 41 | 42 | cout << originalMAX << endl; 43 | } -------------------------------------------------------------------------------- /Array/palindromeString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool isPal(char a[]) 6 | { 7 | int i = 0; 8 | int j = strlen(a) - 1; //last character 9 | 10 | while (i < j) 11 | { 12 | if (a[i] == a[j]) 13 | { 14 | i++; 15 | j--; 16 | } 17 | 18 | else 19 | { 20 | return false; 21 | } 22 | } 23 | 24 | return true; 25 | } 26 | 27 | int main() 28 | { 29 | 30 | char a[100]; 31 | 32 | cin.getline(a, 100); 33 | 34 | if (isPal(a)) 35 | { 36 | cout << "Palindrome string" << endl; 37 | } 38 | 39 | else 40 | cout << "Not a palindrome string"; 41 | } -------------------------------------------------------------------------------- /Array/rainwaterHarvesting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int a[1000000], l[1000000], r[1000000]; 5 | int main() 6 | { 7 | int n, i, j; 8 | cin >> n; 9 | for (i = 0; i < n; i++) 10 | { 11 | cin >> a[i]; 12 | } 13 | 14 | l[0] = a[0]; 15 | r[n - 1] = a[n - 1]; 16 | 17 | int leftmax = 0, rightmax = 0; 18 | 19 | for (i = 1; i < n; i++) 20 | 21 | { 22 | l[i] = max(l[i - 1], a[i]); 23 | } 24 | 25 | for (i = n - 2; i >= 0; i--) 26 | { 27 | r[i] = max(r[i + 1], a[i]); 28 | } 29 | 30 | int water = 0; 31 | 32 | for (i = 0; i < n; i++) 33 | { 34 | water += (min(l[i], r[i]) - a[i]); 35 | } 36 | 37 | cout << water; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Array/readline.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void readline(char a[], int maxlen, char delim = '\n') 5 | { 6 | int i = 0; 7 | char ch = cin.get(); // first character 8 | 9 | while (ch != delim) 10 | { 11 | a[i] = ch; 12 | 13 | i++; 14 | 15 | if (i == (maxlen - 1)) 16 | { 17 | break; 18 | } 19 | 20 | ch = cin.get(); 21 | } 22 | 23 | a[i] = '\0'; 24 | } 25 | 26 | int main() 27 | { 28 | 29 | char a[100]; 30 | // readline(a, 100, '$'); 31 | 32 | cin.getline(a, 1000, '$'); 33 | cout << a << endl; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /Array/removeDuplicates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // remove consecutive characters from a string 6 | // cooding -> coding 7 | 8 | void remove(char a[]) 9 | { 10 | 11 | int l = strlen(a); 12 | 13 | if (l == 0 or l == 1) 14 | return; 15 | 16 | int prev = 0; 17 | 18 | for (int current = 1; current < l; current++) 19 | { 20 | if (a[current] != a[prev]) 21 | { 22 | prev++; 23 | a[prev] = a[current]; 24 | } 25 | } 26 | a[prev + 1] = '\0'; 27 | return; 28 | } 29 | 30 | int main(int argc, char) 31 | { 32 | 33 | char a[100]; 34 | cin.getline(a, 100); 35 | remove(a); 36 | cout << a << endl; 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Array/rotate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void rotate(int a[][1000], int n) 6 | { 7 | 8 | //rev each row 9 | for (int row = 0; row < n; row++) 10 | { 11 | int startcol = 0; 12 | int endcol = n - 1; 13 | 14 | while (startcol < endcol) 15 | { 16 | swap(a[row][startcol], a[row][endcol]); 17 | 18 | startcol++; 19 | endcol--; 20 | } 21 | } 22 | 23 | // transpose 24 | for (int i = 0; i < n; i++) 25 | { 26 | for (int j = 0; j < n; j++) 27 | { 28 | if (i < j) 29 | { 30 | swap(a[i][j], a[j][i]); 31 | } 32 | } 33 | } 34 | } 35 | 36 | void rotate_stl(int a[][1000], int n) 37 | { 38 | for (int i = 0; i < n; i++) 39 | { 40 | reverse(a[i], a[i + n]); 41 | } 42 | // transpose 43 | for (int i = 0; i < n; i++) 44 | { 45 | for (int j = 0; j < n; j++) 46 | { 47 | if (i < j) 48 | { 49 | swap(a[i][j], a[j][i]); 50 | } 51 | } 52 | } 53 | } 54 | 55 | int main() 56 | { 57 | 58 | int a[1000][1000]; 59 | int n; 60 | 61 | cin >> n; 62 | 63 | for (int i = 0; i < n; i++) 64 | { 65 | for (int j = 0; j < n; j++) 66 | { 67 | cin >> a[i][j]; 68 | } 69 | } 70 | rotate_stl(a, n); 71 | } -------------------------------------------------------------------------------- /Array/subarrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int n; 8 | cin >> n; 9 | 10 | int a[100]; 11 | 12 | for (int i = 0; i < n; i++) 13 | { 14 | cin >> a[i]; 15 | } 16 | 17 | // generate subarrays 18 | for (int i = 0; i < n; i++) 19 | { 20 | for (int j = i; j < n; j++) 21 | { 22 | for (int k = i; k <= j; k++) 23 | { 24 | cout << a[k] << " "; 25 | } 26 | cout << endl; 27 | } 28 | } 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Array/sumOfSubmatrices.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int m = 2; 5 | const int n = 2; 6 | 7 | int sum(int arr[n][m]) 8 | { 9 | 10 | int sum = 0; 11 | 12 | for (int i = 0; i < n; i++) 13 | { 14 | for (int j = 0; j < m; j++) 15 | { 16 | int top_left = (i + 1) * (j + 1); 17 | 18 | int bottom_right = (n - i) * (m - j); 19 | 20 | sum += (top_left * bottom_right) * (arr[i][j]); 21 | } 22 | } 23 | 24 | return sum; 25 | } 26 | 27 | int main() 28 | { 29 | 30 | // int n; 31 | // cin >> n; 32 | 33 | // int m; 34 | // cin >> m; 35 | 36 | int arr[n][m]; 37 | 38 | for (int i = 0; i < n; i++) 39 | { 40 | for (int j = 0; j < m; j++) 41 | { 42 | cin >> arr[i][j]; 43 | } 44 | } 45 | 46 | cout << sum(arr) << endl; 47 | } -------------------------------------------------------------------------------- /Array/sumPair.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void pairedElements(int arr[], int sum, int n) 6 | 7 | { 8 | int low = 0; 9 | int high = n - 1; 10 | 11 | while (low < high) 12 | { 13 | if (arr[low] + arr[high] == sum) 14 | { 15 | cout << "The pair is : (" << arr[low] << ", " << arr[high] << ")" << endl; 16 | } 17 | if (arr[low] + arr[high] > sum) 18 | { 19 | high--; 20 | } 21 | else 22 | { 23 | low++; 24 | } 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | int arr[] = {2, 3, 4, -2, 31 | 6, 8, 9, 11}; 32 | int n = sizeof(arr) / sizeof(arr[0]); 33 | sort(arr, arr + n); 34 | pairedElements(arr, 6, n); 35 | } 36 | -------------------------------------------------------------------------------- /Array/sumTriplets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | int a[1005]; 9 | for (int i = 0; i < n; i++) 10 | { 11 | cin >> a[i]; 12 | } 13 | 14 | int target; 15 | cin >> target; 16 | 17 | sort(a, a + n); 18 | 19 | for (int i = 0; i < n; i++) 20 | { 21 | int l = i + 1; 22 | int r = n - 1; 23 | while (l < r) 24 | { 25 | if (a[i] + a[l] + a[r] == target) 26 | { 27 | cout << a[i] << ", " << a[l] << " and " << a[r] << endl; 28 | l++; 29 | r--; 30 | } 31 | else if (a[i] + a[l] + a[r] < target) 32 | l++; 33 | else 34 | r--; 35 | } 36 | } 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Binary Search Tree/topView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node *left; 10 | node *right; 11 | 12 | node(int d) 13 | { 14 | data = d; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | }; 19 | 20 | // queue -> for level order 21 | // map -> if hd's not already taken 22 | void topView(node *root) 23 | { 24 | map> mp; 25 | queue> q; 26 | 27 | q.push({root, 0}); 28 | 29 | // level order 30 | while (!q.empty()) 31 | { 32 | auto f = q.front(); 33 | 34 | node *curr = f.first; 35 | int hd = f.second; 36 | 37 | if (!mp.count(hd)) 38 | mp[hd].push_back(curr->data); 39 | 40 | q.pop(); 41 | 42 | // enq the children 43 | if (curr->left) 44 | q.push({curr->left, hd - 1}); 45 | if (curr->right) 46 | q.push({curr->right, hd + 1}); 47 | } 48 | 49 | for (auto p : mp) 50 | { 51 | vector v = p.second; 52 | 53 | for (auto x : v) 54 | cout << x << " "; 55 | 56 | cout << endl; 57 | } 58 | } 59 | 60 | void inorder(node *root) 61 | { 62 | if (root == NULL) 63 | return; 64 | 65 | cout << root->data << " "; 66 | inorder(root->left); 67 | inorder(root->right); 68 | return; 69 | } 70 | 71 | int main() 72 | { 73 | 74 | node *root = new node(10); 75 | root->left = new node(20); 76 | root->right = new node(50); 77 | root->right->left = new node(60); 78 | root->left->right = new node(40); 79 | root->left->left = new node(30); 80 | cout << "Inorder:"; 81 | inorder(root); 82 | cout << endl; 83 | topView(root); 84 | } 85 | -------------------------------------------------------------------------------- /Binary Search Tree/verticalSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node *left, *right; 10 | 11 | node(int d) 12 | { 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | // HD = HORIZONTAL DISTANCE 20 | void sumRec(node *root, int hd, map &mp) 21 | { 22 | 23 | if (root == NULL) 24 | return; 25 | 26 | sumRec(root->left, hd - 1, mp); 27 | 28 | mp[hd] += root->data; 29 | 30 | sumRec(root->right, hd + 1, mp); 31 | } 32 | 33 | void sum(node *root) 34 | { 35 | map mp; 36 | sumRec(root, 0, mp); 37 | 38 | for (auto sum : mp) 39 | { 40 | cout << sum.second << " "; 41 | } 42 | } 43 | 44 | int main(){ 45 | node*root = new node(10); 46 | root->left = new node(20); 47 | root->right = new node(50); 48 | 49 | root->left->right = new node(40); 50 | root->left->left = new node(30); 51 | 52 | sum(root); 53 | } 54 | -------------------------------------------------------------------------------- /Binary Search Tree/verticalTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node *left = NULL; 10 | node *right = NULL; 11 | 12 | node(int d) 13 | { 14 | data = d; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | }; 19 | 20 | void vertTrav(node *root) 21 | { 22 | map> mp; // keys and values 23 | queue> q; // will have node and hd 24 | 25 | q.push({root, 0}); 26 | 27 | // level order 28 | while (!q.empty()) 29 | { 30 | auto p = q.front(); 31 | node *curr = p.first; 32 | int hd = p.second; 33 | 34 | mp[hd].push_back(curr->data); 35 | 36 | q.pop(); 37 | 38 | // enqueue the children 39 | if (curr->left != NULL) 40 | q.push({curr->left, hd - 1}); 41 | 42 | if (curr->right != NULL) 43 | q.push({curr->right, hd + 1}); 44 | } 45 | 46 | for (auto p : mp) 47 | { 48 | vector v = p.second; // taking out the vector contents 49 | 50 | for (int x : v) 51 | cout << x << " "; 52 | 53 | cout << endl; 54 | } 55 | } 56 | 57 | int main() 58 | { 59 | node *root = new node(10); 60 | root->left = new node(20); 61 | root->right = new node(30); 62 | root->left->right = new node(50); 63 | root->left->left = new node(40); 64 | 65 | vertTrav(root); 66 | } 67 | -------------------------------------------------------------------------------- /Binary Search/.cph/.ekoSPOJ.cpp_baeafec6458b3d28449f000e109cee55.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: ekoSPOJ","url":"/home/proghead00/Desktop/C++/Binary Search/ekoSPOJ.cpp","tests":[{"id":1613320179451,"input":"4 7\n20 15 10 17","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Binary Search/ekoSPOJ.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Binary Search/aggressiveCowsSPOJ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool canWePlaceCows(int stalls[], int n, int c, int min_sep) 5 | { 6 | int last_cow = stalls[0]; 7 | int cnt = 1; 8 | 9 | for (int i = 1; i < n; i++) 10 | { 11 | 12 | if ((stalls[i] - last_cow) >= min_sep) 13 | { 14 | 15 | last_cow = stalls[i]; 16 | cnt++; 17 | 18 | if (cnt == c) 19 | { 20 | return true; 21 | } 22 | } 23 | } 24 | 25 | return false; 26 | } 27 | int main() 28 | { 29 | int n = 5; // no of stalls 30 | int cows = 3; // no of cows 31 | 32 | int stalls[] = {1, 2, 4, 8, 9}; // taking sorted array 33 | 34 | int s = 0; 35 | int e = stalls[n - 1] - stalls[0]; 36 | 37 | int ans = 0; 38 | while (s <= e) 39 | 40 | { 41 | int mid = (s + e) / 2; 42 | 43 | bool kek = canWePlaceCows(stalls, n, cows, mid); 44 | if (kek) 45 | { 46 | 47 | ans = mid; 48 | 49 | // to search if there are larger numbers 50 | s = mid + 1; 51 | } 52 | else 53 | e = mid - 1; 54 | } 55 | cout << ans; 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Binary Search/ekoSPOJ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool check(int mid, int height[], int n, int m) 5 | { 6 | int cut_sum = 0; 7 | 8 | for (int i = 0; i < n; i++) 9 | { 10 | 11 | if (height[i] > mid) 12 | cut_sum += height[i] - mid; 13 | } 14 | 15 | if (cut_sum < m) 16 | { 17 | return false; 18 | } 19 | 20 | else 21 | 22 | return true; 23 | } 24 | int main() 25 | { 26 | int n, m; 27 | 28 | cin >> n >> m; 29 | 30 | int height[n]; 31 | 32 | for (int i = 0; i < n; i++) 33 | { 34 | cin >> height[i]; 35 | } 36 | 37 | int s = 0; 38 | 39 | int max2 = height[0]; 40 | for (int i = 0; i < n; i++) 41 | { 42 | max2 = max(max2, height[i]); 43 | } 44 | 45 | int e = max2; 46 | int ans = 0; 47 | while (s <= e) 48 | { 49 | int mid = (s + e) / 2; 50 | 51 | if (check(mid, height, n, m)) 52 | { 53 | ans = mid; 54 | 55 | s = mid + 1; 56 | } 57 | 58 | else 59 | e = mid - 1; 60 | } 61 | 62 | cout << ans << endl; 63 | } -------------------------------------------------------------------------------- /Binary Search/paintersPartition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isAValidConfig(int b[], int k, int n, int mid) 5 | { 6 | int painters = 1; 7 | int curr_board = 0; 8 | 9 | for (int i = 0; i < n; i++) 10 | { 11 | if (curr_board + b[i] > mid) 12 | { 13 | painters++; 14 | 15 | curr_board = b[i]; //assigning from the next book to the next student 16 | 17 | if (painters > k) 18 | { 19 | return false; 20 | } 21 | } 22 | 23 | else 24 | curr_board += b[i]; // adding another book 25 | } 26 | return true; 27 | } 28 | 29 | int main() 30 | { 31 | 32 | int k, n; 33 | 34 | cin >> k; 35 | 36 | cin >> n; 37 | 38 | int boards[n]; 39 | int st = 0, MAX = 0; // starting index should be the minimum element since it's the miminum time 40 | 41 | for (int i = 0; i < n; i++) 42 | { 43 | cin >> boards[i]; 44 | 45 | MAX = max(MAX, boards[i]); 46 | } 47 | st = MAX; 48 | 49 | int e; 50 | 51 | for (int i = 0; i < n; i++) 52 | { 53 | 54 | e += boards[i]; 55 | } 56 | 57 | int ans; 58 | 59 | while (st <= e) 60 | { 61 | int mid = (st + e) / 2; 62 | 63 | if (isAValidConfig(boards, k, n, mid)) 64 | { 65 | ans = mid; 66 | 67 | e = mid - 1; 68 | } 69 | 70 | else 71 | st = mid + 1; 72 | } 73 | 74 | cout << ans << endl; 75 | } -------------------------------------------------------------------------------- /Binary Search/prataSPOJ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | bool isPossible(int ranks[], int p, int cooks, int mid) 5 | { 6 | int count1 = 0, i; 7 | 8 | for (int i = 0; i < cooks; i++) 9 | { 10 | int j = 1; 11 | int sum = 0; 12 | while (sum <= mid) 13 | { 14 | sum = sum + j * ranks[i]; 15 | count1++; 16 | j++; 17 | } 18 | count1--; 19 | } 20 | if (count1 >= p) 21 | { 22 | return true; 23 | } 24 | else 25 | return false; 26 | } 27 | 28 | int findMin(int ranks[], int p, int cooks) 29 | { 30 | int s = 0, ans = 0; 31 | int e = 10000007; 32 | 33 | while (s <= e) 34 | { 35 | int mid = (s + e) / 2; 36 | 37 | if (isPossible(ranks, p, cooks, mid)) 38 | { 39 | ans = mid; 40 | e = mid - 1; 41 | } 42 | else 43 | s = mid + 1; 44 | } 45 | return ans; 46 | } 47 | 48 | int main() 49 | { 50 | int t, p, cooks; 51 | cin >> t; 52 | while (t--) 53 | { 54 | cin >> p; 55 | cin >> cooks; 56 | 57 | int ranks[cooks]; 58 | 59 | for (int i = 0; i < cooks; i++) 60 | { 61 | cin >> ranks[i]; 62 | } 63 | 64 | cout << findMin(ranks, p, cooks) << endl; 65 | } 66 | return 0; 67 | } -------------------------------------------------------------------------------- /Binary Tree/maxSumPath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node *left; 10 | node *right; 11 | 12 | node(int d) 13 | { 14 | data = d; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | }; 19 | 20 | 21 | 22 | // For each node there can be four ways that the max path goes through the node: 23 | // 1. Node only 24 | // 2. Max path through Left Child + Node 25 | // 3. Max path through Right Child + Node 26 | // 4. Max path through Left Child + Node + Max path through Right Child 27 | 28 | int utilFn(node *root, int &ans) 29 | { 30 | if (root == NULL) 31 | return 0; 32 | 33 | int left = utilFn(root->left, ans); 34 | int right = utilFn(root->right, ans); 35 | 36 | int nodeMax = max(max(root->data, root->data + left + right), 37 | max(root->data + left, root->data + right)); 38 | 39 | ans = max(ans, nodeMax); 40 | 41 | int singlePathSum = max(root->data, max(root->data + left, root->data + right)); 42 | return singlePathSum; 43 | } 44 | 45 | int maxPathSum(node *root) 46 | { 47 | int ans = INT_MIN; 48 | utilFn(root, ans); 49 | return ans; 50 | } 51 | 52 | // int max_sum = INT_MIN; 53 | // int maxPathSum(node *root) 54 | // { 55 | // // base 56 | // if (root == NULL) 57 | // return INT_MIN; 58 | 59 | // int left_sum = maxPathSum(root->left); 60 | // int right_sum = maxPathSum(root->right); 61 | 62 | // int ans = root->data; 63 | 64 | // if (left_sum > 0) 65 | // ans += left_sum; 66 | // if (right_sum > 0) 67 | // ans += right_sum; 68 | 69 | // max_sum = max(max_sum, ans); 70 | 71 | // return root->data + max(0, max(left_sum, right_sum)); 72 | // } 73 | 74 | int main() 75 | { 76 | node *root = new node(1); 77 | root->left = new node(2); 78 | root->right = new node(3); 79 | root->left->left = new node(4); 80 | root->right->right = new node(5); 81 | 82 | cout << "O/p: " << maxPathSum(root); 83 | } 84 | -------------------------------------------------------------------------------- /Binary Tree/rightView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node 5 | { 6 | public: 7 | int data; 8 | node *right; 9 | node *left; 10 | 11 | node(int d) 12 | { 13 | data = d; 14 | right = NULL; 15 | left = NULL; 16 | } 17 | }; 18 | 19 | node *buildTree() 20 | { 21 | int d; 22 | cin >> d; 23 | 24 | if (d == -1) 25 | { 26 | return NULL; 27 | } 28 | 29 | node *root = new node(d); 30 | root->left = buildTree(); 31 | root->right = buildTree(); 32 | return root; 33 | } 34 | 35 | void rightView(node *root, int level, int &maxLevel) 36 | { 37 | if (root == NULL) 38 | { 39 | return; 40 | } 41 | if (maxLevel < level) 42 | { 43 | //discovered a new level 44 | cout << root->data << " "; 45 | maxLevel = level; 46 | } 47 | 48 | rightView(root->right, level + 1, maxLevel); 49 | rightView(root->left, level + 1, maxLevel); 50 | } 51 | 52 | int main() 53 | { 54 | 55 | node *root = buildTree(); 56 | 57 | node*target = root->left->left; 58 | 59 | int maxLevel = -1; 60 | 61 | rightView(root, 0, maxLevel); 62 | } 63 | -------------------------------------------------------------------------------- /Binary Tree/traversals.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node *left, *right; 10 | 11 | node(int d) 12 | { 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | node *insert(node *root, int x) 20 | { 21 | if (root == NULL) 22 | return new node(x); 23 | 24 | else if (root->data < x) 25 | root->right = insert(root->right, x); 26 | 27 | else if (root->data >= x) 28 | root->left = insert(root->left, x); 29 | 30 | return root; 31 | } 32 | 33 | void prePrint(node *root) 34 | { 35 | if (root == NULL) 36 | return; 37 | 38 | cout << root->data << " "; 39 | prePrint(root->left); 40 | prePrint(root->right); 41 | } 42 | 43 | void printRange(node *root, int k1, int k2) 44 | { 45 | // if (root == NULL) 46 | // return; 47 | 48 | queue q; 49 | q.push(root); 50 | 51 | while (!q.empty()) 52 | { 53 | node *f = q.front(); 54 | if (f->data >= k1 and f->data <= k2) 55 | cout << f->data << " "; 56 | 57 | q.pop(); 58 | 59 | if (f->left) 60 | q.push(f->left); 61 | if (f->right) 62 | q.push(f->right); 63 | } 64 | } 65 | 66 | 67 | int main() 68 | { 69 | 70 | node *root = insert(root, 20); 71 | root->left = insert(root->left, 8); 72 | root->right = insert(root->right, 22); 73 | // node *root = buildTree(); 74 | 75 | node *newl = insert(root, 4); 76 | node *newr = insert(root, 12); 77 | 78 | prePrint(root); 79 | cout << endl; 80 | 81 | printRange(root, 10, 25); 82 | } 83 | -------------------------------------------------------------------------------- /Bitmasking/.cph/.fastExponential.cpp_30bcb6d052ce7c314267a9c4487c4627.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: fastExponential","url":"/home/proghead00/Desktop/C++/Bitmasking/fastExponential.cpp","tests":[{"id":1613980121792,"input":"14 1404","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Bitmasking/fastExponential.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Bitmasking/.cph/.operations.cpp_cfdce468752acd6353bf575cd9fe3862.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: operations","url":"/home/proghead00/Desktop/C++/Bitmasking/operations.cpp","tests":[{"id":1613889724702,"input":"15 3","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Bitmasking/operations.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Bitmasking/.cph/.uniqueNumberII.cpp_5e956212c06c31939578e2635272c2af.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: uniqueNumberII","url":"/home/proghead00/Desktop/C++/Bitmasking/uniqueNumberII.cpp","tests":[{"id":1614060107316,"input":"8\n5 1 2 1 2 3 5 7 ","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Bitmasking/uniqueNumberII.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Bitmasking/.cph/.uniqueNumberIII.cpp_c2e3738b9cf9bde1e2cd19ea3cf3c14c.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: uniqueNumberIII","url":"/home/proghead00/Desktop/C++/Bitmasking/uniqueNumberIII.cpp","tests":[{"id":1613972276926,"input":"7\n1 1 1 2 2 2 3","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Bitmasking/uniqueNumberIII.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Bitmasking/fastExponential.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int ans = 1; 8 | 9 | int a, n; 10 | cin >> a >> n; 11 | 12 | while (n > 0) 13 | { 14 | int last_bit = (n & 1); 15 | 16 | if (last_bit) 17 | { 18 | ans *= a; 19 | } 20 | 21 | a = a * a; 22 | n = n >> 1; 23 | } 24 | cout << ans << endl; 25 | } -------------------------------------------------------------------------------- /Bitmasking/operations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int ith_bit(int n, int i) 5 | { 6 | 7 | return (n & (1 << i)) > 0 ? 1 : 0; 8 | } 9 | 10 | int set_ith_bit(int n, int i) 11 | { 12 | return n | (1 << i); 13 | } 14 | 15 | int clear_ith_bit(int n, int i) 16 | { 17 | 18 | int mask = ~(1 << i); 19 | n = (n & mask); 20 | 21 | return n; 22 | } 23 | 24 | int update_ith_bit(int n, int v, int i) 25 | { 26 | int mask = ~(1 << i); 27 | 28 | int cleared_n = n & mask; 29 | 30 | n = cleared_n | (v << i); 31 | return n; 32 | } 33 | 34 | int clear_range_bits(int n, int i) 35 | { 36 | int mask = (-1 << i); 37 | n = (n & mask); 38 | 39 | return n; 40 | } 41 | 42 | int clear_i_to_j(int n, int i, int j) 43 | { 44 | int ones = ~0; 45 | 46 | int a = ones << j + 1; 47 | 48 | int b = (1 << i) - 1; 49 | 50 | int mask = a | b; 51 | 52 | int ans = n & mask; 53 | 54 | return ans; 55 | } 56 | 57 | int count_set_bits(int n) 58 | { 59 | while (n > 0) 60 | { 61 | /* code */ 62 | } 63 | } 64 | 65 | int main() 66 | { 67 | 68 | int n, i, j; 69 | 70 | cin >> n >> i >> j; 71 | 72 | int update = clear_i_to_j(n, i, j); 73 | 74 | cout << update << endl; 75 | } 76 | -------------------------------------------------------------------------------- /Bitmasking/powerSet_GFG.cpp: -------------------------------------------------------------------------------- 1 | vector AllPossibleStrings(string s){ 2 | // Code here 3 | int n = s.size(); 4 | vector ans; 5 | 6 | for(int i=0; i<(1< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int n; 8 | cin >> n; 9 | 10 | int res = 0; 11 | 12 | int a[1000005]; 13 | 14 | int num; 15 | for (size_t i = 0; i < n; i++) 16 | { 17 | cin >> num; 18 | 19 | a[i] = num; 20 | 21 | res = res ^ num; 22 | } 23 | 24 | int temp = res; 25 | int pos = 0; 26 | 27 | while ((temp & 1) != 1) 28 | { 29 | temp = temp >> 1; // rightshift till 1 is found 30 | pos++; 31 | } 32 | 33 | int mask = (1 << pos); // first set bit is at pos 34 | 35 | // numbers with set bits at pos: 36 | 37 | int x = 0, y = 0; 38 | for (size_t i = 0; i < n; i++) 39 | { 40 | if ((a[i] & mask) > 0) // take in nos. with set bits at pos 41 | { 42 | x = x ^ a[i]; 43 | } 44 | } 45 | 46 | y = res ^ x; 47 | 48 | cout << (min(x, y)) << " " << max(x, y); 49 | } -------------------------------------------------------------------------------- /Bitmasking/uniqueNumberIII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int c[64] = {0}; 7 | 8 | int n, num; 9 | 10 | cin >> n; 11 | 12 | for (size_t i = 0; i < n; i++) 13 | { 14 | cin >> num; 15 | 16 | int j = 0; 17 | 18 | while (num > 0) 19 | { 20 | int last_bit = (num & 1); 21 | 22 | c[j] += last_bit; 23 | 24 | j++; 25 | 26 | num = num >> 1; 27 | } 28 | } 29 | 30 | int p = 1, ans = 0; 31 | 32 | for (size_t i = 0; i < 64; i++) 33 | { 34 | c[i] %= 3; 35 | ans += (c[i] * p); 36 | p++; 37 | } 38 | 39 | cout << ans << endl; 40 | } 41 | -------------------------------------------------------------------------------- /Dynamic Programming/coinChange.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int change_topDown(int n, int coins[], int T, int dp[]) { 6 | 7 | if (n == 0) return 0; 8 | 9 | int ans = INT_MAX; 10 | 11 | if (dp[n] != 0) return dp[n]; 12 | 13 | for (int i = 0; i < T; i++) { 14 | if (n - coins[i] >= 0) { 15 | int subprob = change_topDown(n - coins[i], coins, T, dp); 16 | ans = min(ans, subprob + 1); 17 | } 18 | } 19 | 20 | return dp[n] = ans; 21 | } 22 | 23 | int change_bottomUp(int N, int coins[], int T) { 24 | int dp[100] = {0}; 25 | 26 | // iterate over all states 1...N 27 | for (int n = 1; n <= N; n++) { 28 | dp[n] = INT_MAX; 29 | 30 | for (int t = 0; t < T; t++) { 31 | if (n - coins[t] >= 0) { 32 | int subproblem = dp[n - coins[t]]; 33 | dp[n] = min(dp[n], subproblem + 1); 34 | } 35 | } 36 | } 37 | return dp[N]; 38 | } 39 | 40 | 41 | int main() { 42 | 43 | #ifndef ONLINE_JUDGE 44 | freopen("input.txt", "r", stdin); 45 | freopen("output.txt", "w", stdout); 46 | #endif 47 | 48 | int N = 15; 49 | int coins[] = {1, 7, 10}; 50 | int dp[100] = {0}; 51 | int T = 3; 52 | 53 | cout << change_topDown(N, coins, T, dp) << endl; 54 | cout << change_bottomUp(N, coins, T) << endl; 55 | } -------------------------------------------------------------------------------- /Dynamic Programming/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fib_topDown(int n, int dp[]) { 5 | 6 | if (dp[n] == -1) { 7 | int res; 8 | 9 | if (n == 0 or n == 1) 10 | res = n; 11 | else 12 | res = fib_topDown(n - 1, dp) + fib_topDown(n - 2, dp); 13 | 14 | dp[n] = res; 15 | } 16 | return dp[n]; 17 | } 18 | 19 | // bottom up 20 | int fib_spaceOptimized(int n) { 21 | 22 | if (n = 0 or n = 1) return n; 23 | int a = 0, b = 1, c; 24 | 25 | for (int i = 2; i < n; i++) { 26 | c = a + b; 27 | a = b; 28 | b = c; 29 | } 30 | return c; 31 | } 32 | 33 | int fib_bottomUp(int n) { 34 | int dp[100] = {0}; 35 | dp[1] = 1; 36 | for (int i = 0; i < n; i++) { 37 | for (int i = 2; i <= n; i++) { 38 | dp[i] = dp[i - 1] + dp[i - 2]; 39 | } 40 | } 41 | return dp[n]; 42 | } 43 | 44 | int main() { 45 | 46 | #ifndef ONLINE_JUDGE 47 | freopen("input.txt", "r", stdin); 48 | freopen("output.txt", "w", stdout); 49 | #endif 50 | 51 | int n; 52 | cin >> n; 53 | 54 | int dp[100]; 55 | for (int i = 0; i < 100; i++) dp[i] = -1; 56 | 57 | cout << fib_topDown(n, dp) << endl; 58 | cout << fib_bottomUp(n) << endl; 59 | 60 | 61 | } -------------------------------------------------------------------------------- /Dynamic Programming/input.txt: -------------------------------------------------------------------------------- 1 | 10 2 -------------------------------------------------------------------------------- /Dynamic Programming/longestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | //O(n^2) 6 | int LIS1(int arr[], int n) { 7 | int lis[n]; 8 | lis[0] = 1; 9 | 10 | for (int i = 1; i < n; i++) { 11 | lis[i] = 1; 12 | for (int j = 0; j < i; j++) { 13 | if (arr[j] < arr[i]) 14 | lis[i] = max(lis[i], lis[j] + 1); 15 | } 16 | } 17 | 18 | // either this: cout << *max_element(lis, lis + n); 19 | // or: 20 | int res = lis[0]; 21 | for (int i = 0; i < n; ++i) { 22 | res = max(res, lis[i]); 23 | } 24 | return res; 25 | } 26 | 27 | // ----------------------------------------------------------------------------- 28 | int ceilIdx(int tail[], int n, int x) { 29 | auto it = upper_bound(tail, tail + n, x); 30 | return (it - tail); 31 | } 32 | 33 | //O(nlogn) 34 | int LIS2(int arr[], int n) { 35 | int tail[n], len = 1; 36 | tail[0] = arr[0]; 37 | 38 | for (int i = 0; i < n; ++i) 39 | { 40 | if (arr[i] > tail[len - 1]) { 41 | tail[len] = arr[i]; 42 | len++; 43 | } 44 | else { 45 | int c = ceilIdx(tail, len - 1, arr[i]); 46 | tail[c] = arr[i]; 47 | } 48 | } 49 | return len; 50 | } 51 | 52 | int main() { 53 | #ifndef ONLINE_JUDGE 54 | freopen("input.txt", "r", stdin); 55 | freopen("output.txt", "w", stdout); 56 | #endif 57 | 58 | int arr[] = {8, 100, 150, 10, 12, 14, 110}; 59 | int n = sizeof(arr) / sizeof(int); 60 | 61 | cout << LIS2(arr, n); 62 | 63 | } -------------------------------------------------------------------------------- /Dynamic Programming/matrixChainMultiplication.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // top down 7 | int tdp[100][100]; 8 | int matrixChain_topDown(int m[], int i, int j) { 9 | 10 | if (i + 1 == j) { 11 | tdp[i][j] = 0; 12 | return 0; 13 | } 14 | 15 | if (tdp[i][j] != -1) return tdp[i][j]; 16 | 17 | int ans = INT_MAX; 18 | 19 | for (int k = i + 1; k < j; k++) { 20 | int temp = matrixChain_topDown(m, i, k) + matrixChain_topDown(m, k, j) + m[i] * m[k] * m[j]; 21 | ans = min(ans, temp); 22 | } 23 | 24 | 25 | return tdp[i][j] = ans; 26 | } 27 | 28 | // bottom up 29 | int matrixChain_bottomUp(int m[], int n) { 30 | int dp[n][n]; 31 | 32 | for (int i = 0; i < n - 1; ++i) { 33 | dp[i][i + 1] = 0; // gap of 1 is filled with 0 34 | } 35 | 36 | for (int gap = 2; gap < n; gap++) { 37 | for (int i = 0; i + gap < n; i++) { 38 | int j = i + gap; 39 | 40 | dp[i][j] = INT_MAX; 41 | 42 | for (int k = i + 1; k < j; k++) { 43 | dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + m[i] * m[k] * m[j]); 44 | 45 | } 46 | } 47 | 48 | } 49 | return dp[0][n - 1]; 50 | } 51 | 52 | int main() { 53 | #ifndef ONLINE_JUDGE 54 | freopen("input.txt", "r", stdin); 55 | freopen("output.txt", "w", stdout); 56 | #endif 57 | int matrices[] = {1, 2, 3, 4}; // dimensions 58 | 59 | int n = sizeof(matrices) / sizeof(int); 60 | memset(tdp, -1, sizeof tdp); 61 | 62 | cout << matrixChain_topDown(matrices, 0, n - 1) << endl; 63 | cout << matrixChain_bottomUp(matrices, n) << endl; 64 | } 65 | -------------------------------------------------------------------------------- /Dynamic Programming/maxSubarraySum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int maxSum(int arr[], int n) { 6 | // special case: if all the numbers are negative 7 | int c = 0; 8 | for (int i = 0; i < n; i++) { 9 | if (arr[i] < 0) c++; 10 | } 11 | if (c == n) return *max_element(arr, arr + n); 12 | 13 | else { 14 | int dp[100] = {0}; 15 | dp[0] = arr[0] > 0 ? arr[0] : 0; 16 | int max_so_far = dp[0]; 17 | 18 | for (int i = 1; i < n; ++i) 19 | { 20 | dp[i] = dp[i - 1] + arr[i]; 21 | if (dp[i] < 0) dp[i] = 0; 22 | 23 | max_so_far = max(dp[i], max_so_far); 24 | } 25 | 26 | return max_so_far; 27 | } 28 | } 29 | 30 | int main() { 31 | #ifndef ONLINE_JUDGE 32 | freopen("input.txt", "r", stdin); 33 | freopen("output.txt", "w", stdout); 34 | #endif 35 | int arr[] = { -3, 2, 5, -1, 6, 3, -2, 7, -5, 2}; 36 | // int arr[] = { -1, 4, -5, -5, -5, -6, -7, -5, -111}; 37 | int n = sizeof(arr) / sizeof(int); 38 | 39 | cout << maxSum(arr, n); 40 | } -------------------------------------------------------------------------------- /Dynamic Programming/mitosis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define ll long long 5 | #define pb push_back 6 | #define fr(a,b) for(int i = a; i < b; i++) 7 | #define rep(i,a,b) for(int i = a; i < b; i++) 8 | #define fr2(i,a,b,u) for(int i = a; i < b; i+=u) 9 | 10 | #define mod 1000000007 11 | #define all(x) (x).begin(), (x).end() 12 | #define prDouble(x) cout << fixed << setprecision(10) << x 13 | #define triplet pair> 14 | #define goog(tno) cout << "Case #" << tno <<": " 15 | #define read(x) int x; cin >> x 16 | #define endl "\n" 17 | 18 | #define ff first 19 | #define ss second 20 | #define mp make_pair 21 | #define pii pair 22 | #define vi vector 23 | #define mii map 24 | #define pqb priority_queue 25 | #define pqs priority_queue > 26 | #define setbits(x) __builtin_popcountll(x) 27 | #define zrobits(x) __builtin_ctzll(x) 28 | #define inf 1e18 29 | #define ps(x,y) fixed<>x; while(x--) 32 | mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); 33 | 34 | 35 | void solve() 36 | { 37 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 38 | #ifndef ONLINE_JUDGE 39 | freopen("input.txt", "r", stdin); 40 | freopen("output.txt", "w", stdout); 41 | #endif 42 | 43 | //code: 44 | read(n); 45 | 46 | read(x); 47 | read(y); 48 | read(z); 49 | 50 | int dp[n + 1]; 51 | dp[0] = 0; 52 | dp[1] = 0; 53 | 54 | fr(2, n + 1) { 55 | if (n & 1) { 56 | dp[i] = min(dp[i - 1] + y, dp[(i + 1) / 2] + x + z); 57 | } 58 | else { 59 | dp[i] = min(dp[i / 2] + x, dp[i - 1] + y); 60 | } 61 | } 62 | cout << dp[n]; 63 | } 64 | 65 | int32_t main() 66 | { 67 | solve(); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /Dynamic Programming/n-k_ladder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int ways_topDown(int n, int k, int *dp) { 6 | if (n == 0) return 1; 7 | 8 | if (n < 0) return 0; 9 | 10 | if (dp[n] != 0) return dp[n]; 11 | 12 | int ans = 0; 13 | for (int jump = 1; jump <= k; jump++) { 14 | ans += ways_topDown(n - jump, k, dp); 15 | } 16 | return dp[n] = ans; 17 | } 18 | 19 | int ways_bottomUp(int n, int k) { 20 | vectordp(n + 1, 0); 21 | 22 | dp[0] = 1; 23 | for (int i = 1; i <= n; ++i) { 24 | 25 | for (int jump = 1; i <= k; jump++) { 26 | 27 | if (i - jump >= 0) 28 | dp[i] += dp[i - jump]; 29 | } 30 | 31 | } 32 | return dp[n]; 33 | } 34 | int bottomUp_optimized(int n, int k) { 35 | vectordp(n + 1, 0); 36 | dp[0] = dp[1] = 1; 37 | for (int i = 2; i <= k; i++) { 38 | dp[i] = 2 * dp[i - 1]; 39 | } 40 | 41 | for (int i = k + 1; i <= n; ++i) 42 | { 43 | dp[i] = 2 * dp[i - 1] - dp[i - k - 1] 44 | } 45 | 46 | return dp[n]; 47 | } 48 | 49 | 50 | int main() { 51 | #ifndef ONLINE_JUDGE 52 | freopen("input.txt", "r", stdin); 53 | freopen("output.txt", "w", stdout); 54 | #endif 55 | int n, k; 56 | cin >> n >> k; 57 | 58 | int dp[1000] = {0}; 59 | cout << ways_topDown(n, k, dp) << endl; 60 | 61 | } 62 | -------------------------------------------------------------------------------- /Dynamic Programming/output.txt: -------------------------------------------------------------------------------- 1 | 4 -------------------------------------------------------------------------------- /Dynamic Programming/winesDP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // only 2 bottles can be sold 5 | int profit_topDown(int wines[], int i, int j, int y) { 6 | 7 | if (i > j) return 0; 8 | 9 | int op1 = wines[i] * y + profit_topDown(wines, i + 1, j, y + 1 ); 10 | int op2 = wines[j] * y + profit_topDown(wines, i, j - 1, y + 1 ); 11 | 12 | return max(op1, op2); 13 | 14 | } 15 | 16 | int profit_bottomUp(int wines[], int i, int j, int y, int dp[][100]) { 17 | if (i > j) return 0; 18 | 19 | if (dp[i][j] != 0) return dp[i][j]; 20 | 21 | int op1 = wines[i] * y + profit_bottomUp(wines, i + 1, j, y + 1, dp ); 22 | int op2 = wines[j] * y + profit_bottomUp(wines, i, j - 1, y + 1, dp ); 23 | 24 | return dp[i][j] = max(op1, op2); 25 | } 26 | 27 | 28 | 29 | int main() { 30 | 31 | #ifndef ONLINE_JUDGE 32 | freopen("input.txt", "r", stdin); 33 | freopen("output.txt", "w", stdout); 34 | #endif 35 | 36 | int wines[] = {2, 3, 5, 1, 4}; 37 | 38 | int dp[100][100] = {0}; 39 | int n = sizeof(wines) / sizeof(int); 40 | int y = 1; 41 | 42 | cout << profit_topDown(wines, 0, n - 1, y) << endl; 43 | cout << profit_bottomUp(wines, 0, n - 1, y, dp); 44 | } -------------------------------------------------------------------------------- /Graphs/DSU_cycleDetection_unionByRank_pathCompression.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Graph { 5 | int V; 6 | list > edgeList; 7 | 8 | public: 9 | Graph(int V) { 10 | this->V = V; 11 | } 12 | 13 | void addEdge(int u, int v) { 14 | edgeList.push_back({u, v}); 15 | } 16 | 17 | int findSet(int node, int parent[]) { 18 | if (parent[node] == -1) return node; // if the node is parent itself (-1) 19 | 20 | // path compression: 21 | return parent[node] = findSet(parent[node], parent); 22 | } 23 | 24 | void unionSet(int x, int y, int parent[], int rank[]) { 25 | 26 | // find leaders of set 1 and 2: 27 | int s1 = findSet(x, parent); 28 | int s2 = findSet(y, parent); 29 | 30 | // Union by Rank: 31 | 32 | if (s1 != s2) { 33 | if (rank[s1] < rank[s2]) { 34 | parent[s1] = s2; 35 | rank[s2] += rank[s1]; // thus, rank of THAT LEADER becomes the size of that set 36 | } 37 | else { 38 | parent[s2] = s1; 39 | rank[s1] += rank[s2]; 40 | } 41 | } 42 | } 43 | 44 | 45 | bool containsCycle() { 46 | int *parent = new int[V]; 47 | int *rank = new int[V]; 48 | 49 | for (int i = 0; i < V; i++) { 50 | parent[i] = -1; // since initially parent of every node is that itself 51 | rank[i] = 1; 52 | } 53 | 54 | for (auto edge : edgeList) { 55 | int i = edge.first; 56 | int j = edge.second; 57 | 58 | int s1 = findSet(i, parent); 59 | int s2 = findSet(j, parent); 60 | 61 | if (s1 != s2) unionSet(s1, s2, parent, rank); 62 | 63 | else return true; 64 | } 65 | 66 | delete[] parent; 67 | delete[] rank; 68 | return false; 69 | } 70 | }; 71 | 72 | int main() { 73 | Graph g(4); 74 | 75 | g.addEdge(0, 1); 76 | g.addEdge(1, 2); 77 | g.addEdge(2, 3); 78 | g.addEdge(3, 0); 79 | 80 | (g.containsCycle()) ? cout << "Cycle's Present" : cout << "Cycle's Not Present"; 81 | } -------------------------------------------------------------------------------- /Graphs/FINAL_cycleDetect_DIRECTED.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 1e5 + 1; 5 | 6 | vector adjList[N]; 7 | 8 | bool dfs(int node, vector &visited, vector &inStack) { 9 | 10 | visited[node] = true; 11 | inStack[node] = true; 12 | 13 | for (auto nbr : adjList[node]) { 14 | 15 | if (inStack[nbr]) return true; 16 | 17 | else if (!visited[nbr]) { 18 | bool cycle = dfs(nbr, visited, inStack); 19 | if (cycle) return true; 20 | } 21 | } 22 | 23 | inStack[node] = false; 24 | return false; 25 | } 26 | 27 | int main() { 28 | 29 | #ifndef ONLINE_JUDGE 30 | freopen("input.txt", "r", stdin); 31 | freopen("output.txt", "w", stdout); 32 | #endif 33 | 34 | int n, m; 35 | cin >> n >> m; 36 | 37 | for (int i = 0; i < m; i++) { 38 | int x, y; 39 | cin >> x >> y; 40 | 41 | adjList[x].push_back(y); 42 | // adjList[y].push_back(x); 43 | } 44 | 45 | vector visited(n, false); 46 | vector inStack(n, false); 47 | 48 | bool cycle = false; 49 | 50 | for (int i = 0; i < n; i++) { 51 | if (!visited[i]) { 52 | if (dfs(i, visited, inStack)) { 53 | cycle = true; 54 | break; 55 | } 56 | 57 | } 58 | } 59 | 60 | if (cycle) cout << "Cycle's Present"; 61 | else cout << "Not present"; 62 | 63 | 64 | } -------------------------------------------------------------------------------- /Graphs/adjListHashmap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Graph { 8 | unordered_map < string, list < pair< string, int > > > l; 9 | 10 | public: 11 | void addEdge(string x, string y, bool bidir, int wt) { 12 | l[x].push_back({y, wt}); 13 | 14 | if (bidir) l[y].push_back({x, wt}); 15 | } 16 | 17 | void print() { 18 | for (auto p : l) { 19 | string city = p.first; 20 | list> nbrs = p.second; 21 | 22 | cout << city << "--> "; 23 | for (auto nbr : nbrs) { 24 | string dest = nbr.first; 25 | int dist = nbr.second; 26 | 27 | cout << dest << " " << dist << " ; "; 28 | } 29 | cout << endl; 30 | } 31 | } 32 | }; 33 | 34 | int main() { 35 | 36 | Graph g; 37 | 38 | g.addEdge("A", "B", true, 20); 39 | g.addEdge("B", "D", true, 40); 40 | g.addEdge("A", "C", true, 10); 41 | g.addEdge("C", "D", true, 40); 42 | g.addEdge("A", "D", false, 50); 43 | 44 | g.print(); 45 | } -------------------------------------------------------------------------------- /Graphs/adjacencyList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Graph { 6 | int V; 7 | list *l; // pointer to an array of lists 8 | 9 | public: 10 | Graph(int V) { 11 | this->V = V; // no of vertices 12 | l = new list[V]; 13 | } 14 | 15 | void addEdge(int i, int j, bool undir = true) { 16 | l[i].push_back(j); 17 | 18 | if (undir) l[j].push_back(i); 19 | } 20 | 21 | void print() { 22 | // V = no. of rows 23 | for (int i = 0; i < V; i++) { 24 | 25 | cout << i << "-->"; 26 | 27 | for (int node : l[i]) cout << node << " "; 28 | 29 | cout << endl; 30 | } 31 | } 32 | }; 33 | 34 | int main() { 35 | 36 | Graph g(6); 37 | g.addEdge(0, 1); 38 | g.addEdge(0, 4); 39 | g.addEdge(2, 1); 40 | g.addEdge(3, 4); 41 | g.addEdge(4, 5); 42 | g.addEdge(2, 3); 43 | g.addEdge(3, 5); 44 | 45 | g.print(); 46 | } -------------------------------------------------------------------------------- /Graphs/bellmanFord.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector bellmanFord(int V, int src, vector> edgeList) { 5 | 6 | vector dist(V + 1, INT_MAX); // V+1 --> cuz nodes are numbered from 1 to n 7 | dist[src] = 0; 8 | 9 | // relax all edges V-1 times 10 | for (int i = 0; i < V - 1; i++) { 11 | for (auto edge : edgeList) { 12 | int u = edge[0]; 13 | int v = edge[1]; 14 | int wt = edge[2]; 15 | 16 | if (dist[u] != INT_MAX and dist[u] + wt < dist[v]) 17 | dist[v] = dist[u] + wt; 18 | } 19 | } 20 | // negative wt cycle: 21 | for (auto edge : edgeList) { 22 | int u = edge[0]; 23 | int v = edge[1]; 24 | int wt = edge[2]; 25 | 26 | if (dist[u] != INT_MAX and dist[u] + wt < dist[v]) { 27 | cout << "Negative weight cycle's found"; 28 | exit(0); 29 | } 30 | } 31 | 32 | return dist; 33 | } 34 | 35 | 36 | int main() { 37 | 38 | int n, m; // n vertices; m edges 39 | cin >> n >> m; 40 | 41 | vector > edgeList; 42 | 43 | for (int i = 0; i < m; i++) { 44 | int u, v, wt; 45 | 46 | cin >> u >> v >> wt; 47 | 48 | edgeList.push_back({u, v, wt}); 49 | } 50 | 51 | vector distances = bellmanFord(n, 1, edgeList); 52 | 53 | for (int i = 1; i <= n; i++) 54 | cout << i << " --> " << distances[i] << endl; 55 | 56 | } -------------------------------------------------------------------------------- /Graphs/bfsGeneric.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | template 8 | class Graph { 9 | map> adjList; 10 | 11 | public: 12 | void addEdge(T x, T y, bool bidirectional = true) { 13 | adjList[x].push_back(y); 14 | if (bidirectional) adjList[y].push_back(x); 15 | } 16 | 17 | void bfs(T src) { 18 | map visited; 19 | queue q; 20 | 21 | q.push(src); 22 | visited[src] = true; 23 | 24 | while (!q.empty()) { 25 | 26 | T node = q.front(); 27 | cout << node << " "; 28 | q.pop(); 29 | 30 | for (T nbr : adjList[node]) { 31 | if (!visited[nbr]) { 32 | q.push(nbr); 33 | visited[nbr] = true; 34 | } 35 | } 36 | } 37 | } 38 | 39 | void print() { 40 | // iterate over the map 41 | for (auto p : adjList) { 42 | cout << p.first << "-->"; 43 | 44 | // p.second => Linked List 45 | for (auto entry : p.second) { 46 | cout << entry << ","; 47 | } 48 | cout << endl; 49 | } 50 | } 51 | 52 | }; 53 | 54 | int main() { 55 | 56 | Graph g; 57 | 58 | g.addEdge(0, 1); 59 | g.addEdge(1, 2); 60 | g.addEdge(0, 4); 61 | g.addEdge(2, 4); 62 | g.addEdge(2, 3); 63 | g.addEdge(3, 5); 64 | g.addEdge(3, 4); 65 | 66 | g.bfs(0); 67 | cout << endl; 68 | g.print(); 69 | } 70 | -------------------------------------------------------------------------------- /Graphs/bipartite.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 100005, M = 22; 5 | 6 | vector graph[N]; 7 | int visited[N]; 8 | 9 | bool oddCycle = 0; 10 | 11 | // COLOR: 12 | // 0 -> not visited; 1-> visisted and colored 1; 2-> visited and colored 2 13 | 14 | void dfs(int node, int parent, int color) { 15 | visited[node] = color; 16 | 17 | for (auto nbr : graph[node]) { 18 | if (visited[nbr] == 0) { 19 | dfs(nbr, node, 3 - color); 20 | } 21 | 22 | // backedge and odd length cycle 23 | else if (node != parent and color == visited[nbr]) { 24 | oddCycle = 1; 25 | } 26 | } 27 | } 28 | 29 | int main() { 30 | int n, m; 31 | cin >> n >> m; 32 | 33 | int ans = 0, cnt = 0, sum = 0; 34 | 35 | while (m--) { 36 | int x, y; 37 | cin >> x >> y; 38 | graph[x].push_back(y); 39 | graph[y].push_back(x); 40 | } 41 | dfs(1, 0, 1); 42 | 43 | if (oddCycle) cout << "Not Bipartite"; 44 | else cout << "Bipartite"; 45 | 46 | } -------------------------------------------------------------------------------- /Graphs/cycleDetection_directed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | class Graph { 6 | 7 | map> adjList; 8 | 9 | public: 10 | 11 | void addEdge(T x, T y, bool bidirectional) { 12 | adjList[x].push_back(y); 13 | if (bidirectional) adjList[y].push_back(x); 14 | } 15 | 16 | bool isCycle__helper(T node, map&visited, map&inStack) { 17 | 18 | visited[node] = true; 19 | inStack[node] = true; 20 | 21 | for (T nbr : adjList[node]) { 22 | 23 | if (inStack[nbr]) return true; 24 | 25 | // if the cycle's in the deeper branch (recursively) 26 | else if (!visited[nbr]) { 27 | bool nbrFoundCycle = isCycle__helper(nbr, visited, inStack); 28 | 29 | if (nbrFoundCycle) return true; 30 | } 31 | 32 | } 33 | 34 | // while going back, stack's elements will be "popped out", i.e, false 35 | inStack[node] = false; 36 | return false; 37 | } 38 | 39 | bool isCylic() { 40 | map visited; 41 | map inStack; 42 | 43 | 44 | // WHY DO WE EVEN NEED THIS: 45 | // check for cycle in each dfs tree 46 | // for (auto p : adjList) { 47 | // T node = p.first; 48 | // if (!visited[node]) { 49 | // bool cyclePresent = isCycle__helper(node, visited, inStack); 50 | 51 | // if (cyclePresent) return true; 52 | // } 53 | // } 54 | // return false; 55 | 56 | return isCycle__helper(0, visited, inStack); 57 | } 58 | }; 59 | 60 | int main() { 61 | Graph g; 62 | g.addEdge(0, 2, false); 63 | g.addEdge(0, 1, false); 64 | g.addEdge(2, 3, false); 65 | g.addEdge(2, 4, false); 66 | g.addEdge(3, 0, false); 67 | g.addEdge(4, 5, false); 68 | g.addEdge(1, 5, false); 69 | 70 | 71 | 72 | 73 | if (g.isCylic()) cout << "Cycle's Present"; 74 | else cout << "Cycle's not present"; 75 | } -------------------------------------------------------------------------------- /Graphs/cycleDetection_undirected.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | 6 | class Graph { 7 | map> adjList; 8 | 9 | public: 10 | void addEdge(T x, T y, bool bidirectional = true) { 11 | adjList[x].push_back(y); 12 | if (bidirectional) adjList[y].push_back(x); 13 | 14 | } 15 | 16 | bool isCyclic(T src) { 17 | map visited; 18 | map parent; 19 | queue q; 20 | 21 | q.push(src); 22 | visited[src] = true; 23 | parent[src] = src; 24 | 25 | while (!q.empty()) { 26 | T node = q.front(); 27 | q.pop(); 28 | 29 | for (T nbr : adjList[node]) { 30 | if (visited[nbr] and parent[node] != nbr) 31 | return true; 32 | 33 | else if (!visited[nbr]) { 34 | q.push(nbr); 35 | visited[nbr] = true; 36 | parent[nbr] = node; 37 | } 38 | } 39 | } 40 | return false; 41 | } 42 | 43 | }; 44 | 45 | int main() { 46 | Graph g; 47 | g.addEdge(1, 2); 48 | g.addEdge(1, 4); 49 | g.addEdge(4, 3); 50 | g.addEdge(2, 3); 51 | 52 | if (g.isCyclic(1)) cout << "Cyclic Graph"; 53 | else cout << "Not cyclic"; 54 | } -------------------------------------------------------------------------------- /Graphs/dfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | 6 | class Graph { 7 | map > adjList; 8 | 9 | public: 10 | void addEdge(T x, T y, bool bidirectional = true) { 11 | adjList[x].push_back(y); 12 | if (bidirectional) adjList[y].push_back(x); 13 | } 14 | 15 | // ---------------------------------------------------------------------------------- 16 | void dfsHelper(T node, map &visited) { 17 | cout << node << " "; 18 | visited[node] = true; 19 | 20 | // go to all neighbours of that node one by one 21 | for (T nbr : adjList[node]) { 22 | if (!visited[nbr]) { 23 | dfsHelper(nbr, visited); 24 | } 25 | } 26 | } 27 | 28 | // ---------------------------------------------------------------------------------- 29 | 30 | void dfs(T src) { 31 | map visited; 32 | 33 | // no need to initialise FALSE in map, since it already is 34 | 35 | dfsHelper(src, visited); 36 | } 37 | 38 | // ---------------------------------------------------------------------------------- 39 | 40 | void dfs_connectedComponents() { 41 | map visited; 42 | 43 | // mark all nodes as not visited at the beginning 44 | for (auto p : adjList) { 45 | T node = p.first; 46 | visited[node] = false; 47 | } 48 | 49 | int c = 0; 50 | for (auto p : adjList) { 51 | T node = p.first; 52 | 53 | if (!visited[node]) { 54 | cout << "Component " << c << " --> "; 55 | dfsHelper(node, visited); 56 | c++; 57 | cout << endl; 58 | 59 | } 60 | } 61 | } 62 | 63 | 64 | }; 65 | 66 | int main() { 67 | 68 | Graph g; 69 | 70 | g.addEdge(0, 1); 71 | g.addEdge(1, 2); 72 | g.addEdge(2, 3); 73 | g.addEdge(0, 3); 74 | g.addEdge(0, 4); 75 | 76 | g.addEdge(5, 6); 77 | g.addEdge(6, 7); 78 | 79 | g.addEdge(8, 8); 80 | 81 | 82 | g.dfs(0); 83 | cout << endl; 84 | 85 | g.dfs_connectedComponents(); 86 | 87 | } 88 | -------------------------------------------------------------------------------- /Graphs/dfs_cycleDetection__Directed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 1e5 + 1; 5 | 6 | vector adjList[N]; 7 | int vis[N]; 8 | bool cycle = false; 9 | 10 | // 3 states => 0, 1, 2 11 | 12 | // 1 13 | // / \ 14 | // 3 ---- 2 15 | 16 | void dfs(int node, int parent) { 17 | 18 | // visited and in call stack ==> 1 19 | vis[node] = 1; 20 | 21 | for (auto nbr : adjList[node]) { 22 | 23 | if (!vis[nbr]) { 24 | dfs(nbr, node); 25 | } 26 | 27 | else if (nbr != parent and vis[nbr] == 1) { 28 | // backedge 29 | cycle = true; 30 | 31 | cout << node << " --> " << nbr << endl; 32 | } 33 | } 34 | 35 | // visited and not in call stack 36 | vis[node] = 2; 37 | 38 | // return; 39 | } 40 | 41 | int main() 42 | { 43 | freopen("input.txt", "r", stdin); 44 | freopen("output.txt", "w", stdout); 45 | 46 | int n, m; 47 | cin >> n >> m; 48 | 49 | for (int i = 0; i < m; i++) { 50 | int x, y; 51 | cin >> x >> y; 52 | adjList[x].push_back(y); 53 | adjList[y].push_back(x); 54 | } 55 | 56 | for (int i = 1; i <= n; i++) { 57 | if (!vis[i]) { 58 | dfs(i, 0); 59 | } 60 | } 61 | 62 | if (cycle) 63 | cout << "Cycle's found"; 64 | 65 | else 66 | cout << "Cycle's not found"; 67 | 68 | 69 | return 0; 70 | } -------------------------------------------------------------------------------- /Graphs/floodFill.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 100; 5 | int arr[N][N]; 6 | 7 | int n, m; 8 | 9 | int dx[] = {0, 0, 1, -1}; 10 | int dy[] = {1, -1, 0, 0}; 11 | 12 | void floodFill(int x, int y) { 13 | arr[x][y] = 0; 14 | 15 | for (int i = 0; i < 4; i++) { 16 | int newX = x + dx[i]; 17 | int newY = y + dy[i]; 18 | 19 | if (newX >= 0 and newX < n and newY >= 0 and newY < m and arr[newX][newY] == 1) 20 | floodFill(newX, newY); 21 | } 22 | 23 | } 24 | 25 | 26 | int main() { 27 | 28 | cin >> n >> m; 29 | 30 | for (int i = 0; i < n; i++) { 31 | for (int j = 0; j < m; j++) { 32 | cin >> arr[i][j]; 33 | } 34 | } 35 | 36 | int cnt = 0; 37 | for (int i = 0; i < n; i++) { 38 | for (int j = 0; j < m; j++) { 39 | if (arr[i][j] == 1) { 40 | cnt++; 41 | floodFill(i, j); 42 | } 43 | } 44 | } 45 | cout << cnt; 46 | } 47 | 48 | // 6 5 49 | // 0 0 0 1 1 50 | // 0 1 0 0 0 51 | // 1 1 0 1 0 52 | // 1 0 1 1 1 53 | // 0 0 1 1 0 54 | // 0 0 0 0 0 55 | -------------------------------------------------------------------------------- /Graphs/floodFillCharacters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int R, C; 5 | 6 | // coordinate = (dx,dy) 7 | int dx[] = {0, 0, 1, -1}; 8 | int dy[] = {1, -1, 0, 0}; 9 | 10 | void print(char input[][50]) { 11 | 12 | for (int i = 0; i < R; i++) { 13 | for (int j = 0; j < C; j++) { 14 | cout << input[i][j]; 15 | } 16 | cout << endl; 17 | } 18 | 19 | } 20 | 21 | 22 | void floodFill(char input[][50], int i, int j, char ch, char color) { 23 | // ch => character to be replaced 24 | // color => character to be added 25 | 26 | 27 | // base case: matrix bounds 28 | if (i<0 or j<0 or i >= R and j >= C) { 29 | return; 30 | } 31 | 32 | // figure boundary condition 33 | if (input[i][j] != ch) return; 34 | 35 | input[i][j] = color; 36 | 37 | // print(input); 38 | // cout << endl; 39 | 40 | for (int k = 0; k < 4; k++) { 41 | floodFill(input, i + dx[k], j + dy[k], ch, color); 42 | } 43 | 44 | } 45 | 46 | int main() { 47 | 48 | cin >> R >> C; 49 | 50 | char input[15][50]; 51 | 52 | for (int i = 0; i < R; i++) { 53 | for (int j = 0; j < C; j++) { 54 | cin >> input[i][j]; 55 | } 56 | } 57 | 58 | print(input); 59 | floodFill(input, 8, 13, '.', 'R'); 60 | // floodFill(input, 0, 0, '.', '!'); 61 | print(input); 62 | 63 | 64 | } -------------------------------------------------------------------------------- /Graphs/floodFillColorCount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int N = 100; 6 | 7 | int arr[N][N], vis[N][N]; 8 | int colorCnt[N]; // to map how many colors have how many islands 9 | 10 | int n, m; 11 | 12 | int dx[4] = {0, 0, 1, -1}; 13 | int dy[4] = {1, -1, 0, 0}; 14 | 15 | void floodFill(int x, int y, int color) { 16 | arr[x][y] = color; 17 | vis[x][y] = 1; 18 | colorCnt[color]++; 19 | 20 | for (int i = 0; i < 4; i++) { 21 | int newX = x + dx[i]; 22 | int newY = y + dy[i]; 23 | 24 | if (newX >= 0 and newX < n and newY >= 0 and newY < m and !vis[newX][newY] and arr[newX][newY] == 1) { 25 | floodFill(newX, newY, color); 26 | } 27 | } 28 | } 29 | 30 | int main() { 31 | 32 | cin >> n >> m; 33 | for (int i = 0; i < n; i++) { 34 | for (int j = 0; j < m; j++) { 35 | cin >> arr[i][j]; 36 | } 37 | } 38 | 39 | int totalCount = 0; 40 | 41 | for (int i = 0; i < n; i++) { 42 | for (int j = 0; j < m; j++) { 43 | if (arr[i][j] == 1 and !vis[i][j]) { 44 | totalCount++; 45 | floodFill(i, j, totalCount); 46 | } 47 | } 48 | } 49 | //-------------------- 50 | cout << endl; 51 | 52 | for (int i = 0; i < n; i++) { 53 | for (int j = 0; j < m; j++) { 54 | cout << arr[i][j] << " "; 55 | } 56 | cout << endl; 57 | } 58 | 59 | 60 | cout << endl; 61 | 62 | for (int i = 1; i <= totalCount; i++) { 63 | cout << i << " --> " << colorCnt[i] << '\n'; 64 | } 65 | 66 | return 0; 67 | } 68 | 69 | // 6 5 70 | // 0 0 0 1 1 71 | // 0 1 0 0 0 72 | // 1 1 0 1 0 73 | // 1 0 1 1 1 74 | // 0 0 1 1 0 75 | // 0 0 0 0 0 76 | -------------------------------------------------------------------------------- /Graphs/floydWarshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define inf 10000 5 | vector> floydWarshall(vector> graph) { 6 | 7 | int V = graph.size(); 8 | 9 | vector> dist(graph); 10 | 11 | // Phases --> in kth phase, include vertices --> 1,2,...k as intermediate vertices 12 | 13 | for (int k = 0; k < V; k++) { 14 | 15 | // iterate over entire 2D matrix 16 | for (int i = 0; i < V; i++) { 17 | 18 | for (int j = 0; j < V; j++) { 19 | // if vertex k is included and dist can be minimized by taking k as intermediate vertex 20 | // dist[i][j] = DIST OF I TO J 21 | 22 | if (dist[i][k] + dist[k][j] < dist[i][j]) { 23 | dist[i][j] = dist[i][k] + dist[k][j]; 24 | } 25 | } 26 | } 27 | } 28 | 29 | return dist; 30 | } 31 | 32 | int main() { 33 | 34 | // DIAGONAL ELEMENTS ARE 0 35 | // inf --> WHERE THERE'S NO DIRECTED EDGE 36 | 37 | // 4x4 ADJ MATRIX 38 | vector> graph = { 39 | {0, inf, -2, inf}, 40 | {4, 0, 3, inf}, 41 | {inf, inf, 0, 2}, 42 | {inf, -1, inf, 0} 43 | }; 44 | 45 | auto result = floydWarshall(graph); 46 | 47 | for (int i = 0; i < result.size(); i++) { 48 | for (int j = 0; j < result.size(); j++) { 49 | cout << result[i][j] << " "; 50 | } 51 | cout << endl; 52 | } 53 | 54 | } 55 | 56 | -------------------------------------------------------------------------------- /Graphs/input.txt: -------------------------------------------------------------------------------- 1 | 5 5 2 | 1 2 3 | 2 3 4 | 3 1 5 | 3 4 6 | 4 5 -------------------------------------------------------------------------------- /Graphs/kosaraju.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void dfs(vector graph[], int i, bool *visited, vector &stk) { 5 | visited[i] = true; 6 | 7 | for (auto nbr : graph[i]) { 8 | if (!visited[nbr]) 9 | dfs(graph, nbr, visited, stk); 10 | } 11 | 12 | // function call is complete 13 | 14 | stk.push_back(i); 15 | } 16 | 17 | void dfs__2(vector graph[], int i, bool *visited) { 18 | cout << i << " "; 19 | visited[i] = true; 20 | 21 | for (auto nbr : graph[i]) { 22 | if (!visited[nbr]) 23 | dfs__2(graph, nbr, visited); 24 | } 25 | } 26 | 27 | void solve(vector graph[], vector rev_graph[], int N) { 28 | 29 | bool visited[N]; 30 | memset(visited, 0, N); 31 | 32 | vector stk; 33 | 34 | // step 1: store vertices in stk, according to dfs finish time 35 | for (int i = 0; i < N; i++) { 36 | // i --> current node 37 | if (!visited[i]) { 38 | dfs(graph, i, visited, stk); 39 | } 40 | } 41 | 42 | // ordering => stk 43 | 44 | // step 2 : reverse => already done 45 | 46 | // step 3 => DFS according to the ordering in stk: 47 | memset(visited, 0, N); 48 | 49 | char componentName = 'A'; 50 | 51 | for (int x = stk.size() - 1; x >= 0; x--) { 52 | int node = stk[x]; 53 | if (!visited[node]) { 54 | // then, there's a component starting from this node 55 | cout << "Component " << componentName << " --> "; 56 | dfs__2(rev_graph, node, visited); 57 | 58 | cout << endl; 59 | componentName++; 60 | } 61 | } 62 | 63 | } 64 | 65 | 66 | int main() { 67 | // N vertices; M edges; 68 | 69 | int N; 70 | cin >> N; 71 | 72 | // vector stores adjacency list 73 | vector graph[N]; 74 | vector rev_graph[N]; 75 | 76 | int M; 77 | cin >> M; 78 | 79 | while (M--) { 80 | // edge is from x to y 81 | int x, y; 82 | cin >> x >> y; 83 | 84 | graph[x].push_back(y); 85 | rev_graph[y].push_back(x); 86 | } 87 | 88 | solve(graph, rev_graph, N); 89 | } -------------------------------------------------------------------------------- /Graphs/kruskals.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class dsu { 5 | int *parent; 6 | int *ranks; 7 | 8 | public: 9 | dsu(int n) { 10 | parent = new int[n]; 11 | ranks = new int[n]; 12 | 13 | for (int i = 0; i < n; i++) { 14 | parent[i] = -1; 15 | ranks[i] = 1; 16 | } 17 | } 18 | 19 | int findSet(int node) { 20 | if (parent[node] == -1) return node; 21 | 22 | return parent[node] = findSet(parent[node]); 23 | } 24 | 25 | void unite(int x, int y) { 26 | int s1 = findSet(x); 27 | int s2 = findSet(y); 28 | 29 | if (s1 != s2) { 30 | 31 | if (ranks[s1] < ranks[s2]) { 32 | parent[s1] = s2; 33 | ranks[s2] += ranks[s1]; 34 | } 35 | else { 36 | parent[s2] = s1; 37 | ranks[s1] += ranks[s2]; 38 | } 39 | } 40 | } 41 | 42 | }; 43 | 44 | class Graph { 45 | vector> edgeList; 46 | int V; 47 | 48 | public: 49 | Graph(int V) { 50 | this->V = V; 51 | } 52 | 53 | void addEdge(int x, int y, int w) { 54 | // edge is from x to y 55 | edgeList.push_back({w, x, y}); 56 | } 57 | 58 | int kruskal_MST() { 59 | dsu s(V); 60 | 61 | sort(edgeList.begin(), edgeList.end()); 62 | 63 | int ans = 0; 64 | for (auto edge : edgeList) { 65 | int w = edge[0]; 66 | int x = edge[1]; 67 | int y = edge[2]; 68 | 69 | // take that edge in MST if it doesn't form a cycle 70 | if (s.findSet(x) != s.findSet(y)) { 71 | s.unite(x, y); 72 | ans += w; 73 | } 74 | } 75 | return ans; 76 | } 77 | }; 78 | 79 | int main() { 80 | // Graph g(4); 81 | 82 | // g.addEdge(0, 1, 1); 83 | // g.addEdge(1, 3, 3); 84 | // g.addEdge(3, 2, 4); 85 | // g.addEdge(2, 0, 2); 86 | // g.addEdge(0, 3, 2); 87 | // g.addEdge(1, 2, 2); 88 | 89 | // For SPOJ MST: 90 | int n, m; 91 | cin >> n >> m; 92 | Graph g(n); 93 | 94 | while (m--) { 95 | int x, y, w; 96 | cin >> x >> y >> w; 97 | g.addEdge(x - 1, y - 1, w); 98 | } 99 | 100 | cout << g.kruskal_MST() << endl; 101 | } -------------------------------------------------------------------------------- /Graphs/largestIslandME.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 1000; 5 | 6 | // int arr[N][N]; 7 | 8 | const int r = 4, c = 4; 9 | 10 | // int arr[r][c] = { 11 | // {1, 0, 0, 1, 0}, 12 | // {1, 0, 1, 0, 0}, 13 | // {0, 0, 1, 0, 1}, 14 | // {1, 0, 1, 1, 1}, 15 | // {1, 0, 1, 1, 0} 16 | // }; 17 | int arr[r][c] = { 18 | {1, 1, 1, 0}, 19 | {1, 0, 0, 1}, 20 | {0, 1, 1, 1}, 21 | {1, 1, 0, 0} 22 | }; 23 | 24 | int visited[N][N]; 25 | 26 | 27 | unordered_map mp; 28 | 29 | // ----------------------------------------------- 30 | void ff(int x, int y, int &island__ID) { 31 | arr[x][y] = island__ID; 32 | visited[x][y] = true; 33 | 34 | mp[island__ID]++; 35 | 36 | int dx[4] = {0, 0, 1, -1}; 37 | int dy[4] = {1, -1, 0, 0}; 38 | 39 | for (int k = 0; k < 4; k++) { 40 | int xx = x + dx[k]; 41 | int yy = y + dy[k]; 42 | 43 | if (xx >= 0 and xx= 0 and yy < c and !visited[xx][yy] and arr[xx][yy] == 1) { 44 | ff(xx, yy, island__ID); 45 | } 46 | } 47 | } 48 | 49 | int main() { 50 | 51 | int island__ID = 0; 52 | for (int i = 0; i < r; i++) { 53 | for (int j = 0; j < c; j++) { 54 | if (arr[i][j] == 1 and !visited[i][j]) { 55 | island__ID++; 56 | ff(i, j, island__ID); 57 | } 58 | } 59 | } 60 | 61 | int largest = -1; 62 | for (auto p : mp) { 63 | largest = max(largest, p.second); 64 | } 65 | cout << largest; 66 | // for (auto x : mp) cout << x.first << "-->" << x.second << " " << endl; 67 | 68 | } -------------------------------------------------------------------------------- /Graphs/largestIslandNN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int dfs(vector > &matrix, vector > &visited, int i, int j, int m, int n) { 5 | 6 | visited[i][j] = true; 7 | 8 | int currSize = 1; 9 | 10 | int dx[] = {1, -1, 0, 0}; 11 | int dy[] = {0, 0, 1, -1}; 12 | 13 | for (int k = 0; k < 4; k++) { 14 | int xx = i + dx[k]; 15 | int yy = j + dy[k]; 16 | 17 | if (xx >= 0 and xx= 0 and yy < n and matrix[xx][yy] == 1 and !visited[xx][yy]) { 18 | int subcomponent = dfs(matrix, visited, xx, yy, m, n); 19 | currSize += subcomponent; 20 | } 21 | } 22 | return currSize; 23 | } 24 | 25 | 26 | int lasrgestIsland(vector > matrix) { 27 | 28 | int m = matrix.size(); // rows 29 | int n = matrix[0].size(); // cols 30 | 31 | vector > visited(m, vector(n, false)); 32 | 33 | int largest = 0; 34 | 35 | for (int i = 0; i < m; i++) { 36 | for (int j = 0; j < n; j++) { 37 | if (!visited[i][j] and matrix[i][j] == 1) { 38 | 39 | int size = dfs(matrix, visited, i, j, m, n); 40 | if (size > largest) { 41 | largest = size; 42 | } 43 | 44 | } 45 | 46 | } 47 | } 48 | return largest; 49 | } 50 | 51 | 52 | int main() { 53 | vector > grid = { 54 | {1, 0, 0, 1, 0}, 55 | {1, 0, 1, 0, 0}, 56 | {0, 0, 1, 0, 1}, 57 | {1, 0, 1, 1, 1}, 58 | {1, 0, 1, 1, 0} 59 | }; 60 | 61 | cout << lasrgestIsland(grid) << endl; 62 | 63 | 64 | return 0; 65 | } -------------------------------------------------------------------------------- /Graphs/output.txt: -------------------------------------------------------------------------------- 1 | 3 4 -------------------------------------------------------------------------------- /Graphs/prims.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // ADJ LIST --> (NODE, WT) 5 | // PRIORITY Q --> (WT, NODE) 6 | 7 | // ----------------------------------------- 8 | class Graph { 9 | 10 | // adjacency list: 11 | // 1 -> (a, w1) (b,w2)... 12 | // 2 -> (a, w1) (b,w2)... 13 | vector> *adjList; 14 | int V; 15 | 16 | public: 17 | Graph(int n) { 18 | V = n; 19 | adjList = new vector> [n]; 20 | 21 | } 22 | 23 | void addEdge(int x, int y, int w) { 24 | adjList[x].push_back({y, w}); 25 | adjList[y].push_back({x, w}); 26 | } 27 | 28 | int prim_MST() { 29 | 30 | // priority_queue < pair, vector< pair >, greater < pair () > > Q; ==> WRONG STATEMENT 31 | priority_queue< pair, vector > , greater> > Q; 32 | 33 | bool *visited = new bool[V] {0}; 34 | int ans = 0; 35 | 36 | Q.push({0, 0}); // first -> wt || second -> node's value 37 | 38 | while (!Q.empty()) { 39 | 40 | // pick out edge w/ min weight => bestEdge 41 | auto bestEdge = Q.top(); 42 | 43 | Q.pop(); 44 | 45 | // to ==> node to which the edge is directed to 46 | int to = bestEdge.second; 47 | 48 | int weight = bestEdge.first; 49 | 50 | if (visited[to]) { 51 | // discard the edge since it's not an active edge 52 | continue; 53 | } 54 | 55 | // else, take the current edge 56 | ans += weight; 57 | visited[to] = true; 58 | 59 | // add the new adjacent edges 60 | for (auto x : adjList[to]) { 61 | if (!visited[x.first]) { 62 | Q.push({x.second, x.first}); 63 | } 64 | } 65 | } 66 | return ans; 67 | } 68 | }; 69 | 70 | int main() { 71 | 72 | // For SPOJ MST: 73 | 74 | int n, m; 75 | cin >> n >> m; 76 | 77 | Graph g(n); 78 | 79 | while (m--) { 80 | int x, y, w; 81 | cin >> x >> y >> w; 82 | 83 | g.addEdge(x - 1, y - 1, w); 84 | } 85 | 86 | cout << g.prim_MST() << endl; 87 | } -------------------------------------------------------------------------------- /Graphs/shortesPathGrid.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int shortestPath(vector> grid) { 5 | 6 | int m = grid.size(); //rows 7 | int n = grid[0].size(); //cols 8 | 9 | vector> dist(m + 1, vector(n + 1, INT_MAX)); // M+1 ROWS; N+1 COLS 10 | 11 | dist[0][0] = grid[0][0]; 12 | 13 | set > ss; 14 | s.insert({dist[0][0], 0, 0}); 15 | 16 | int dx[] = {0, 0, 1, -1}; 17 | int dy[] = {1, -1, 0, 0}; 18 | 19 | int i = 0, j = 0; 20 | 21 | while (!s.empty()) { 22 | auto p = *(s.begin()); 23 | 24 | int curr_d = p.frst[0]; 25 | int curr_x = p.first[1]; 26 | int curr_y = p.first[2]; 27 | 28 | s.erase(s.begin()); 29 | 30 | // update nbrs 31 | for (int k = 0; k < 4; k++) { 32 | 33 | int newX = curr_x + dx[k]; 34 | int newY = curr_y + dy[k]; 35 | 36 | if (newX >= 0 and newX= 0 and newY < n and curr_d + grid[newX][newY] < dist[newX][newY]) { 37 | 38 | auto f = s.find({dist[nx][ny], newX, newY}); 39 | 40 | if (f != s.end()) { 41 | s.erase(f); 42 | } 43 | 44 | int newDist = grid[newX][newX] + curr_d; 45 | dist[newX][newY] = newDist; 46 | s.insert({newDist, newX, newY}); 47 | } 48 | } 49 | } 50 | return dist[m - 1][n - 1]; 51 | 52 | } 53 | 54 | int main() { 55 | 56 | } -------------------------------------------------------------------------------- /Graphs/snakesLadders.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | template 9 | 10 | class Graph { 11 | map> adjList; 12 | 13 | public: 14 | void addEdge(T x, T y, bool bidirectional = true) { 15 | adjList[x].push_back(y); 16 | if (bidirectional) adjList[y].push_back(x); 17 | } 18 | 19 | int bfs_SSSP(T src, T dest) { 20 | map dist; 21 | map parent; 22 | 23 | queue q; 24 | 25 | // initialise every other node with inf 26 | for (auto p : adjList) dist[p.first] = INT_MAX; 27 | 28 | // push src as first 29 | q.push(src); 30 | dist[src] = 0; 31 | parent[src] = src; 32 | 33 | while (!q.empty()) { 34 | 35 | T node = q.front(); 36 | // cout << node << " "; 37 | q.pop(); 38 | 39 | for (T nbr : adjList[node]) { 40 | if (dist[nbr] == INT_MAX) { 41 | q.push(nbr); 42 | 43 | dist[nbr] = dist[node] + 1; 44 | parent[nbr] = node; 45 | } 46 | } 47 | } 48 | 49 | T temp = dest; 50 | while (temp != src) { 51 | cout << temp << " <-- "; 52 | temp = parent[temp]; 53 | } 54 | cout << src << endl; 55 | return dist[dest]; 56 | } 57 | 58 | 59 | }; 60 | 61 | int main() { 62 | 63 | Graph g; 64 | int board[50] = {0}; 65 | board[2] = 13; 66 | board[5] = 2; 67 | board[9] = 18; 68 | board[18] = 11; 69 | board[17] = -13; 70 | board[20] = -14; 71 | board[24] = -8; 72 | board[25] = -10; 73 | board[32] = -2; 74 | board[34] = -22; 75 | 76 | for (int u = 0; u <= 36 ; u++) { 77 | // at every node we can throw a die 78 | for (int dice = 1; dice <= 6; dice++) { 79 | int v = u + dice + board[u + dice]; 80 | 81 | g.addEdge(u, v, false); 82 | } 83 | } 84 | 85 | cout << "Distance: " << g.bfs_SSSP(1, 36); 86 | } 87 | 88 | -------------------------------------------------------------------------------- /Graphs/travellingSalesman.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define inf 999999 5 | // #cities = N = 4 -> 1111 --> (2^4)-1 ==> thus, 2^N states 6 | 7 | const int n = 4; // here, n=4 8 | int dp[1 << n][n]; 9 | 10 | 11 | // adj matrix: 12 | int adjMatrix[1 << n][n] = { 13 | {0, 20, 42, 25}, 14 | {20, 0, 30, 34}, 15 | {42, 30, 0, 10}, 16 | {25, 34, 10, 0} 17 | }; 18 | 19 | int visitedALL = (1 << n) - 1; 20 | 21 | //----------------------------------------------- 22 | 23 | int tsp(int mask, int currCity) { 24 | 25 | // if all cities have been visited: 26 | if (mask == visitedALL) { 27 | // return cost from curr city to the src one (0th) 28 | return adjMatrix[currCity][0]; 29 | } 30 | 31 | if (dp[mask][currCity] != -1) 32 | return dp[mask][currCity]; 33 | 34 | // else, try all possible options ==> Go to unvisited cities 35 | int ans = inf; 36 | for (int choice = 0; choice < n; choice++) { 37 | 38 | // check if currCity is visited or not 39 | if ((mask & (1 << choice)) == 0) { 40 | int subprob = adjMatrix[currCity][choice] + tsp(mask | (1 << choice), choice); 41 | ans = min(ans, subprob); 42 | } 43 | } 44 | 45 | return dp[mask][currCity] = ans; 46 | } 47 | 48 | //----------------------------------------------- 49 | int main() { 50 | 51 | memset(dp, -1, sizeof dp); 52 | 53 | // for (int i = 0; i < 16; i++) { 54 | // for (int j = 0; j < 4; j++) 55 | // dp[i][j] = -1; 56 | // } 57 | 58 | cout << tsp(1, 0); // INITIALLY, mask = 0001 || currCity = 0 (src) 59 | 60 | } 61 | 62 | -------------------------------------------------------------------------------- /Greedy/activitySelectionSPOJ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // can select activity if the starting time of the new activity >= finishing time of the previous 7 | 8 | bool compare(pairp1, pairp2) { 9 | return p1.second < p2.second; 10 | } 11 | 12 | int main() { 13 | #ifndef ONLINE_JUDGE 14 | freopen("input.txt", "r", stdin); 15 | freopen("output.txt", "w", stdout); 16 | #endif 17 | 18 | int t, n, s, e; 19 | cin >> t; 20 | vector> v; // first-> start; second-> ending time 21 | while (t--) { 22 | cin >> n; 23 | for (int i = 0; i < n; i++) { 24 | cin >> s >> e; 25 | v.push_back({s, e}); 26 | } 27 | 28 | // activity selection 29 | sort(v.begin(), v.end(), compare); 30 | 31 | // start picking activities 32 | int res = 1; // first activity is picked already at first 33 | int finish = v[0].second; 34 | 35 | for (int i = 1; i < n; i++) { 36 | if (v[i].first >= finish) { //if the starting time (first) of the new activity >= finish 37 | finish = v[i].second; 38 | res++; 39 | } 40 | } 41 | 42 | cout << res << endl; 43 | v.clear(); 44 | } 45 | } -------------------------------------------------------------------------------- /Greedy/baisedSPOJ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | #ifndef ONLINE_JUDGE 7 | freopen("input.txt", "r", stdin); 8 | freopen("output.txt", "w", stdout); 9 | #endif 10 | int arr[100000] = {0}; // freq array 11 | int t; 12 | cin >> t; 13 | 14 | while (t--) { 15 | memset(arr, 0, sizeof (arr)); 16 | string name; 17 | int n, rank; 18 | 19 | cin >> n; 20 | for (int i = 0; i < n; i++) { 21 | cin >> name >> rank; 22 | arr[rank]++; // preferred rank 23 | } 24 | 25 | // greedy: assign the team to the nearest rank available 26 | 27 | int actualRank = 1; 28 | int sum = 0; 29 | for (int i = 1; i <= n; i++) { 30 | while (arr[i]) // not empty 31 | { 32 | sum += abs(actualRank - i); 33 | arr[i]--; 34 | actualRank++; 35 | } 36 | 37 | } 38 | cout << sum << endl; 39 | } 40 | } -------------------------------------------------------------------------------- /Greedy/defkinSPOJ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | #ifndef ONLINE_JUDGE 8 | freopen("input.txt", "r", stdin); 9 | freopen("output.txt", "w", stdout); 10 | #endif 11 | 12 | int t; 13 | cin >> t; 14 | 15 | while (t--) { 16 | int w, h, n; 17 | cin >> w >> h >> n; 18 | vector a; 19 | vector b; 20 | 21 | a.push_back(0); 22 | b.push_back(0); 23 | 24 | for (int i = 0; i < n; i++) { 25 | int x, y; 26 | cin >> x >> y; 27 | a.push_back(x); 28 | b.push_back(y); 29 | } 30 | 31 | // pushing the last point 32 | a.push_back(w + 1); 33 | b.push_back(h + 1); 34 | 35 | 36 | // we need to sort since the towers are inputted in random 37 | sort(a.begin(), a.end()); 38 | sort(b.begin(), b.end()); 39 | 40 | int mx = 0, my = 0; 41 | 42 | for (int i = 0; i < a.size() - 1; i++) { 43 | mx = max(mx, a[i + 1] - a[i] - 1); 44 | my = max(my, b[i + 1] - b[i] - 1); 45 | } 46 | 47 | cout << mx*my << endl; 48 | 49 | } 50 | } -------------------------------------------------------------------------------- /Greedy/input.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 1 1 3 | 2 1 4 | 3 1 5 | 4 1 -------------------------------------------------------------------------------- /Greedy/loadBalancerSPOJ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int main() { 6 | 7 | #ifndef ONLINE_JUDGE 8 | freopen("input.txt", "r", stdin); 9 | freopen("output.txt", "w", stdout); 10 | #endif 11 | 12 | 13 | int arr[90000]; 14 | int n, i, val, diff = 0; 15 | 16 | while (true) { 17 | 18 | int maxLoad = 0, load = 0; 19 | cin >> n; 20 | 21 | // stop taking input when n=-1 22 | if (n == -1) { 23 | break; 24 | } 25 | 26 | for (int i = 0; i < n; i++) { 27 | cin >> arr[i]; 28 | load += arr[i]; 29 | 30 | } 31 | 32 | if (load % n != 0) { 33 | cout << -1 << endl; 34 | continue; 35 | } 36 | 37 | // else divide the load equally 38 | load /= n; 39 | 40 | for (int i = 0; i < n; i++) { 41 | // find diff b/w final load to be assigned and curr node 42 | diff += (arr[i] - load); 43 | int ans = abs(diff); 44 | maxLoad = max(maxLoad, ans); 45 | } 46 | 47 | cout << maxLoad << endl; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Greedy/maxCircles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool cmp(pair p1, pair p2) { 6 | 7 | if (p1.second == p2.second) { 8 | return p1.first < p2.first; 9 | } 10 | 11 | return p1.second < p2.second; 12 | } 13 | 14 | int main() { 15 | 16 | #ifndef ONLINE_JUDGE 17 | freopen("input.txt", "r", stdin); 18 | freopen("output.txt", "w", stdout); 19 | #endif 20 | 21 | int n; 22 | cin >> n; 23 | vector> v; 24 | 25 | int c, r; 26 | for (int i = 0; i < n; i++) { 27 | cin >> c >> r; 28 | v.push_back({c - r, c + r}); 29 | } 30 | sort(v.begin(), v.end(), cmp); 31 | 32 | int cnt = 0; 33 | int curr = v[0].second; 34 | for (int i = 1; i < n; i++) { 35 | if (curr <= v[i].first) curr = v[i].second; 36 | else cnt++; 37 | } 38 | 39 | cout << cnt << endl; 40 | v.clear(); 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Greedy/output.txt: -------------------------------------------------------------------------------- 1 | 2 2 | -------------------------------------------------------------------------------- /Hashing - Tries Challenges/arraysIntersection.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | unordered_map freq; 10 | int n; 11 | cin >> n; 12 | int temp; 13 | for (int i = 0; i < n; i++) 14 | { 15 | cin >> temp; 16 | freq[temp]++; 17 | } 18 | 19 | vector ans; 20 | for (int i = 0; i < n; i++) 21 | { 22 | cin >> temp; 23 | if (freq.find(temp) != freq.end() && freq[temp] > 0) 24 | { 25 | freq[temp]--; //Decrement frequency to ensure it is not repeated 26 | ans.push_back(temp); 27 | } 28 | } 29 | 30 | sort(ans.begin(), ans.end()); 31 | 32 | cout << "["; 33 | for (int i = 0; i < ans.size(); i++) 34 | { 35 | cout << ans[i]; 36 | if (i < ans.size() - 1) 37 | cout << ", "; 38 | } 39 | cout << "]"; 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Hashing - Tries Challenges/countRectangles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Point { 7 | public: 8 | int x, y; 9 | 10 | Point() { 11 | 12 | } 13 | 14 | Point(int x, int y) { 15 | this->x = x; 16 | this->y = y; 17 | } 18 | }; 19 | 20 | class Compare { 21 | public: 22 | bool operator()(const Point p1, const Point p2) { 23 | if (p1.x == p2.x) 24 | return p1.y < p2.y; 25 | return p1.x < p2.x; 26 | } 27 | }; 28 | 29 | int count_rectangles(vectorpoints) { 30 | 31 | int ans = 0; 32 | 33 | 34 | // insert all points in the set 35 | set s; 36 | 37 | for (Point p : points) { 38 | s.insert(p); 39 | } 40 | 41 | // Brute force for two points; look up for the other two 42 | for (auto it = s.begin(); it != prev(s.end()); it++) { 43 | for (auto jt = next(it); jt != s.end(); jt++) { 44 | 45 | Point p1 = *it; 46 | Point p2 = *jt; 47 | 48 | if (p2.x == p1.x or p2.y == p1.y) { 49 | continue; 50 | } 51 | 52 | Point p3(p1.x, p2.y); 53 | Point p4(p2.x, p1.y); 54 | 55 | // lookup 56 | if (s.find(p3) != s.end() and s.find(p4) != s.end()) { 57 | ans++; 58 | } 59 | } 60 | } 61 | 62 | return ans / 2; 63 | 64 | } 65 | 66 | int main() { 67 | 68 | #ifndef ONLINE_JUDGE 69 | freopen("input.txt", "r", stdin); 70 | freopen("output.txt", "w", stdout); 71 | #endif 72 | 73 | 74 | int n; 75 | cin >> n; 76 | 77 | int x, y; 78 | 79 | vector points; 80 | 81 | for (int i = 0; i < n; i++) { 82 | cin >> x >> y; 83 | Point p(x, y); 84 | points.push_back(p); 85 | 86 | } 87 | cout << count_rectangles(points) << endl; 88 | 89 | } -------------------------------------------------------------------------------- /Hashing - Tries Challenges/countTriangles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int count_triangles(vector> &points) { 7 | unordered_mapfreqX; 8 | unordered_mapfreqY; 9 | 10 | // frequencies 11 | for (auto p : points) { 12 | int x = p.first; 13 | int y = p.second; 14 | 15 | freqX[x]++; 16 | freqY[y]++; 17 | } 18 | 19 | int cnt = 0; 20 | for (auto p : points) { 21 | int x = p.first; 22 | int y = p.second; 23 | 24 | int fx = freqX[x]; 25 | int fy = freqY[y]; 26 | 27 | cnt += (fx - 1) * (fy - 1); // excluding the pivot 28 | } 29 | return cnt; 30 | } 31 | 32 | int main() { 33 | #ifndef ONLINE_JUDGE 34 | freopen("input.txt", "r", stdin); 35 | freopen("output.txt", "w", stdout); 36 | #endif 37 | int n; // no of points 38 | cin >> n; 39 | 40 | vector> points; 41 | 42 | for (int i = 0; i < n; i++) { 43 | int x, y; 44 | cin >> x >> y; 45 | 46 | points.push_back({x, y}); 47 | } 48 | cout << count_triangles(points); 49 | } -------------------------------------------------------------------------------- /Hashing - Tries Challenges/existsOrNot.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | #ifndef ONLINE_JUDGE 7 | freopen("input.txt", "r", stdin); 8 | freopen("output.txt", "w", stdout); 9 | #endif 10 | int t; 11 | cin >> t; 12 | for (int i = 0; i < t; i++) { 13 | int l; 14 | cin >> l; 15 | 16 | map hm; 17 | int num; 18 | 19 | for (int j = 0; j < l; j++) { 20 | cin >> num; 21 | hm[num] = 1; 22 | } 23 | 24 | int q; 25 | cin >> q; 26 | int query; 27 | 28 | for (int k = 0; k < q; k++) { 29 | cin >> query; 30 | if (hm.count(query) > 0) { 31 | cout << "Yes" << endl; 32 | } else { 33 | cout << "No" << endl; 34 | } 35 | } 36 | } 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Hashing - Tries Challenges/highestFreq.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | #ifndef ONLINE_JUDGE 9 | freopen("input.txt", "r", stdin); 10 | freopen("output.txt", "w", stdout); 11 | #endif 12 | map m; //ELement value-Freq pair 13 | int n; 14 | cin >> n; 15 | while (n--) 16 | { 17 | int x; 18 | cin >> x; 19 | m[x]++; 20 | } 21 | 22 | int maxFreq = 0; 23 | int ans = 0; 24 | for (auto it : m) 25 | { 26 | if (it.second > maxFreq) 27 | { 28 | maxFreq = it.second; 29 | ans = it.first; 30 | } 31 | } 32 | for (auto it : m) 33 | { 34 | cout << it.first << " -> " << it.second << endl; 35 | } 36 | cout << ans; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Hashing - Tries Challenges/input.txt: -------------------------------------------------------------------------------- 1 | 4 2 | pet 3 | peter 4 | rat 5 | rack 6 | 5 7 | pe 8 | pet 9 | r 10 | rac 11 | rat -------------------------------------------------------------------------------- /Hashing - Tries Challenges/maxXORSubarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node { 5 | public: 6 | // left stores 0, right stores 1 7 | node*left; 8 | node*right; 9 | }; 10 | 11 | class trie { 12 | node*root; 13 | public: 14 | trie() { 15 | root = new node(); 16 | } 17 | 18 | void insert(int n) { 19 | node*temp = root; 20 | for (int i = 31; i >= 0; i--) { 21 | 22 | // extracting i-th bit and checking whether it's set or unset 23 | int bit = (n >> i) & 1; 24 | 25 | if (bit == 0) { 26 | if (temp->left == NULL) 27 | temp->left = new node(); 28 | 29 | temp = temp->left; 30 | } 31 | 32 | else { 33 | if (temp->right == NULL) 34 | temp->right = new node(); 35 | 36 | temp = temp->right; 37 | } 38 | } 39 | } 40 | 41 | int helper(int value) { 42 | node*temp = root; 43 | int curr_ans = 0; 44 | for (int j = 31; j >= 0; j--) { 45 | 46 | int bit = (value >> j) & 1; 47 | 48 | if (bit == 0) { 49 | if (temp->right) { 50 | temp = temp->right; 51 | curr_ans += (1 << j); //2 to the power j 52 | } 53 | else temp = temp->left; 54 | } 55 | 56 | else { 57 | if (temp->left) 58 | { temp = temp->left; 59 | curr_ans += (1 << j); 60 | } 61 | 62 | else temp = temp->right; 63 | 64 | } 65 | } 66 | return curr_ans; 67 | } 68 | 69 | int max_xor(int *arr, int n) { 70 | int max_xor = 0; 71 | 72 | for (int i = 0; i < n; i++) { 73 | int val = arr[i]; 74 | // insert the value in the trie: 75 | insert(val); 76 | int curr_xor = helper(val); 77 | 78 | max_xor = max(max_xor, curr_xor); 79 | } 80 | 81 | return max_xor; 82 | } 83 | 84 | }; 85 | 86 | int main() { 87 | #ifndef ONLINE_JUDGE 88 | freopen("input.txt", "r", stdin); 89 | freopen("output.txt", "w", stdout); 90 | #endif 91 | int n; 92 | cin >> n; 93 | 94 | int arr[n]; 95 | for (int i = 0; i < n; i++) cin >> arr[i]; 96 | 97 | trie t; 98 | cout << t.max_xor(arr, n) << endl; 99 | 100 | } 101 | -------------------------------------------------------------------------------- /Hashing - Tries Challenges/output.txt: -------------------------------------------------------------------------------- 1 | pet 2 | peter 3 | pe found 4 | pet 5 | peter 6 | pet found 7 | rack 8 | rat 9 | r found 10 | rack 11 | rac found 12 | rat 13 | rat found 14 | -------------------------------------------------------------------------------- /Hashing - Tries Challenges/stringWindow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | string window(string s1, string s2) { 7 | 8 | // corner case 9 | if (s2.length() > s1.length()) 10 | return "No String"; 11 | 12 | // freq arrays 13 | int fs1[256] = {0}; 14 | int fs2[256] = {0}; 15 | 16 | for (int i = 0; i < s2.length(); i++) 17 | { 18 | char ch = s2[i]; 19 | fs2[ch]++; 20 | } 21 | 22 | int start = 0, cnt = 0, start_idx = -1, min_len = INT_MAX; 23 | 24 | for (int i = 0; i < s1.length(); i++) 25 | { 26 | char ch = s1[i]; 27 | fs1[ch]++; 28 | 29 | // no. of characters matched 30 | if (fs2[ch] != 0 and fs1[ch] <= fs2[ch]) 31 | cnt++; 32 | 33 | 34 | // if all characters match 35 | if (cnt == s2.length()) { 36 | char temp = s1[start]; 37 | 38 | // remove unwanted characters 39 | while (fs2[temp] == 0 or fs1[temp] > fs2[temp]) { 40 | fs1[temp]--; 41 | start++; 42 | temp = s1[start]; 43 | } 44 | 45 | int window_len = i - start + 1; 46 | if (window_len < min_len) 47 | { 48 | min_len = window_len; 49 | start_idx = start; 50 | } 51 | } 52 | } 53 | 54 | if (start_idx == -1) 55 | return "No String"; 56 | 57 | string ans = s1.substr(start_idx, min_len); 58 | return ans; 59 | 60 | } 61 | 62 | 63 | 64 | int main() { 65 | #ifndef ONLINE_JUDGE 66 | freopen("input.txt", "r", stdin); 67 | freopen("output.txt", "w", stdout); 68 | #endif 69 | 70 | string s1, s2; 71 | getline(cin, s1); 72 | getline(cin, s2); 73 | 74 | cout << window(s1, s2); 75 | 76 | 77 | } 78 | -------------------------------------------------------------------------------- /Hashing - Tries Challenges/sumSubarraysDistinct.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | #ifndef ONLINE_JUDGE 8 | freopen("input.txt", "r", stdin); 9 | freopen("output.txt", "w", stdout); 10 | #endif 11 | 12 | int n; cin >> n; 13 | 14 | int a[n]; 15 | for (int i = 0; i < n; i++) cin >> a[i]; 16 | 17 | unordered_set s; 18 | 19 | int ans = 0; 20 | int j = 0; 21 | 22 | // fix starting point 23 | for (int i = 0; i < n; i++) { 24 | 25 | // find ending point of curr subarray w/ distinct elements 26 | while (j < n and s.find(a[j]) == s.end()) { 27 | 28 | s.insert(a[j]); 29 | j++; 30 | } 31 | 32 | ans += ((j - i) * (j - i + 1)) / 2; 33 | 34 | // remove a[i] since we need to move forward 35 | s.erase(a[i]); 36 | } 37 | 38 | cout << ans << endl; 39 | } -------------------------------------------------------------------------------- /Hashing - Tries Challenges/verticalTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class node { 6 | public: 7 | int data; 8 | node*left; 9 | node*right; 10 | 11 | node(int d) { 12 | data = d; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | void verticalTrav(node*root, map>&m, int hd) { 19 | if (root == NULL) return; 20 | 21 | m[hd].push_back(root->data); 22 | 23 | verticalTrav(root->left, m, hd - 1); 24 | verticalTrav(root->right, m, hd + 1); 25 | return; 26 | 27 | } 28 | 29 | int main() { 30 | 31 | 32 | node*root = new node(1); 33 | root->left = new node(2); 34 | root->right = new node(3); 35 | root->left->left = new node(4); 36 | root->left->right = new node(5); 37 | 38 | root->right->left = new node(6); 39 | root->right->right = new node(7); 40 | 41 | root->right->right->right = new node(9); 42 | 43 | root->left->right->right = new node(8); 44 | 45 | map >m; 46 | int hd = 0; 47 | verticalTrav(root, m, hd); 48 | 49 | for (auto p : m) 50 | { 51 | for (int x : p.second) { 52 | cout << x << " "; 53 | 54 | } 55 | cout << endl; 56 | } 57 | 58 | 59 | } -------------------------------------------------------------------------------- /Hashing/hashTable.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "hashTable.h" 4 | using namespace std; 5 | 6 | int main() { 7 | Hashtable price_menu; 8 | 9 | price_menu.insert("Burger", 120); 10 | price_menu.insert("Pepsi", 20); 11 | price_menu.insert("Pizza", 150); 12 | price_menu.insert("Noodles", 25); 13 | price_menu.insert("Coke", 40); 14 | 15 | price_menu.print(); 16 | 17 | int *price = price_menu.search("Noodles"); 18 | (price == NULL) ? cout << "Nope" : cout << "Price is " << *price << endl; 19 | 20 | } -------------------------------------------------------------------------------- /Hashing/longestConsecutiveSubsequenceMAP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | int largestSequence(int arr[], int n) { 7 | unordered_map m; // value mapping to streak length 8 | 9 | for (int i = 0; i < n; i++) { 10 | int num = arr[i]; 11 | 12 | // new streak formation 13 | if (m.count(num - 1) == 0 and m.count(num + 1) == 0) { 14 | m[num] = 1; 15 | } 16 | 17 | else if (m.count(num - 1) and m.count(num + 1)) { 18 | int leftLen = m[num - 1]; 19 | int rightLen = m[num + 1]; 20 | 21 | int streak = leftLen + 1 + rightLen; 22 | m[num - leftLen] = streak; 23 | m[num - rightLen] = streak; 24 | } 25 | 26 | else if (m.count(num - 1) and !m.count(num + 1)) { 27 | int len = m[num - 1]; 28 | m[num - len] = len + 1; 29 | m[num] = len + 1; 30 | } 31 | else if (!m.count(num - 1) and m.count(num + 1)) { 32 | int len = m[num + 1]; 33 | m[num + len] = len + 1; 34 | m[num] = len + 1; 35 | } 36 | } 37 | 38 | int largest = 0; 39 | for (auto p : m) { 40 | largest = max(largest, p.second); 41 | } 42 | 43 | return largest; 44 | } 45 | 46 | int main() { 47 | int arr[] = {10, 4, 20, 1, 2, 8, 9, 3, 19}; 48 | int n = sizeof(arr) / sizeof(int); 49 | 50 | cout << largestSequence(arr, n); 51 | } -------------------------------------------------------------------------------- /Hashing/longestConsecutiveSubsequenceSET.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | // O(N) 5 | int longestConsecutive(int a[], int n) { 6 | unordered_set s; 7 | 8 | for (int i = 0; i < n; i++) { 9 | s.insert(a[i]); //O(1) 10 | } 11 | int maxStreak = 1; 12 | for (int i = 0; i < n; i++) { 13 | if (s.find(a[i - 1]) == s.end()) { 14 | 15 | // a[i] is the starting head of the streak 16 | // traverse the entire range of the streak 17 | int nextNum = a[i] + 1; 18 | int streakLen = 1; 19 | while (s.find(nextNum) != s.end()) { 20 | nextNum++; 21 | streakLen++; 22 | } 23 | 24 | maxStreak max(streakLen, maxStreak); 25 | } 26 | } 27 | 28 | return max; 29 | } 30 | 31 | int main() { 32 | int arr[] = {10, 4, 20, 1, 2, 8, 9, 3, 19}; 33 | int n = sizeof(arr) / sizeof(int); 34 | 35 | cout << longestConsecutive(arr, n); 36 | } -------------------------------------------------------------------------------- /Hashing/longestSubarrayWithGivenSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int longestSubarrayWithGivenSum(int arr[], int n, int k) { 6 | <<<<<<< HEAD 7 | ======= 8 | 9 | 10 | unordered_map m; 11 | int pre = 0, len = 0; 12 | 13 | for (int i = 0; i < n; i++) { 14 | pre += arr[i]; 15 | 16 | if (pre == k) 17 | { 18 | len = max(len, i + 1); 19 | } 20 | >>>>>>> 29afa652e0ff15855fc19c2d6c9752b41279f05c 21 | 22 | int longestSubarrayWithZeroSum(int arr[], int n) { 23 | unordered_map m; 24 | int pre = 0, len = 0; 25 | 26 | for (int i = 0; i < n; i++) { 27 | pre += arr[i]; 28 | 29 | if (pre == k) 30 | { 31 | len = max(len, i + 1); 32 | } 33 | 34 | 35 | if (m.find(pre - k) != m.end()) // if that element is already present 36 | { 37 | len = max(len, i - m[pre - k]); 38 | } 39 | 40 | else // first occurence of the element 41 | { 42 | m[pre] = i; 43 | } 44 | } 45 | 46 | return len; 47 | 48 | } 49 | 50 | int main() { 51 | int n; 52 | cin >> n; 53 | int k; 54 | cin >> k; 55 | int arr[n]; 56 | 57 | for (int i = 0; i < n; i++) 58 | cin >> arr[i]; 59 | 60 | cout << longestSubarrayWithGivenSum(arr, n, k) << " "; 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /Hashing/rightAngledTriangles.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Hashing/rightAngledTriangles.cpp -------------------------------------------------------------------------------- /Hashing/smallestWIndowSubstring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | string window(string s, string pat) { 7 | int stringLen = s.length(); 8 | int patternLen = pat.length(); 9 | 10 | if (patternLen > stringLen) return "None"; 11 | 12 | int stringFreq[256] = {0}; 13 | int patFreq[256] = {0}; 14 | 15 | // count freq of pattern 16 | for (int i = 0; i < patternLen; i++) { 17 | char ch = pat[i]; 18 | patFreq[ch]++; 19 | } 20 | 21 | // sliding window -> expansion, contraction, update min length of window 22 | // i -> to expand; start-> to shrink 23 | 24 | int start = 0, cnt = 0, minLength = INT_MAX; 25 | 26 | int startIdx = -1; 27 | 28 | for (int i = 0; i < stringLen; i++) { 29 | char ch = s[i]; 30 | stringFreq[ch]++; 31 | 32 | // maintain the count of characters matched 33 | if (patFreq[ch] != 0 and stringFreq[ch] <= patFreq[ch]) { 34 | cnt++; 35 | } 36 | 37 | // if all char match 38 | if (cnt == patternLen) { 39 | char temp = s[start]; 40 | 41 | // if the char is not needed 42 | while (patFreq[temp] == 0 or stringFreq[temp] > patFreq[temp]) { 43 | stringFreq[temp]--; 44 | start++; 45 | temp = s[start]; 46 | } 47 | 48 | // ending point is i; starting point is start 49 | int windowLength = i - start + 1; 50 | 51 | if (windowLength < minLength) { 52 | minLength = windowLength; 53 | startIdx = start; 54 | } 55 | 56 | } 57 | } 58 | 59 | if (startIdx == -1) return "None"; 60 | 61 | string ans = s.substr(startIdx, minLength); 62 | return ans; 63 | } 64 | 65 | 66 | int main() { 67 | string s = "qwerty asdfgh qazxsw"; 68 | string p = "qas"; 69 | 70 | cout << window(s, p); 71 | 72 | } 73 | -------------------------------------------------------------------------------- /Heaps/buildHeapFromArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool minHeap = false; 6 | bool compare(int a, int b) 7 | { 8 | if (minHeap) 9 | return a < b; 10 | else 11 | return a > b; 12 | } 13 | 14 | void heapify(vector &v, int idx) 15 | { 16 | 17 | int left = 2 * idx; 18 | int right = 2 * idx + 1; 19 | 20 | int minIdx = idx; 21 | int last = v.size() - 1; 22 | 23 | if (left <= last and compare(v[left], v[idx])) // then that node exists and is smaller than the current node 24 | minIdx = left; 25 | 26 | if (right <= last and compare(v[right], v[minIdx])) // then that node exists and is smaller than the current node 27 | minIdx = right; 28 | 29 | if (minIdx != idx) 30 | { 31 | swap(v[idx], v[minIdx]); 32 | heapify(v, minIdx); 33 | } 34 | } 35 | 36 | void buildHeapOptimised(vector &v) 37 | { 38 | // first non leaf node: (v.size()-1)/2 39 | for (size_t i = (v.size() - 1) / 2; i >= 1; i--) 40 | { 41 | heapify(v, i); 42 | } 43 | } 44 | 45 | void print(vector &v) 46 | { 47 | for (int x : v) 48 | cout << x << " "; 49 | 50 | cout << endl; 51 | } 52 | 53 | int main() 54 | { 55 | vector v{-1, 10, 20, 5, 6, 1, 8, 9, 4}; 56 | print(v); 57 | 58 | buildHeapOptimised(v); //O(n) 59 | print(v); 60 | } 61 | -------------------------------------------------------------------------------- /Heaps/heapSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool minHeap = false; 6 | bool compare(int a, int b) 7 | { 8 | if (minHeap) 9 | return a < b; 10 | 11 | else 12 | return a > b; 13 | } 14 | 15 | void heapify(vector &v, int idx, int size) 16 | { 17 | int minIdx = idx; 18 | int left = 2 * idx; 19 | int right = left + 1; 20 | int last = size - 1; 21 | 22 | if (left <= last and compare(v[left], v[idx])) 23 | minIdx = left; 24 | 25 | if (right <= last and compare(v[right], v[minIdx])) 26 | minIdx = right; 27 | 28 | if (minIdx != idx) 29 | { 30 | swap(v[idx], v[minIdx]); 31 | heapify(v, minIdx, size); 32 | } 33 | } 34 | 35 | void buildHeapOptimised(vector &v) 36 | { 37 | for (size_t i = (v.size() - 1) / 2; i >= 1; i--) 38 | { 39 | heapify(v, i, v.size()); 40 | } 41 | } 42 | 43 | void heapsort(vector &v) 44 | { 45 | buildHeapOptimised(v); 46 | int n = v.size(); 47 | 48 | // remove n-1 elements from the heap 49 | while (n > 1) 50 | { 51 | swap(v[1], v[n - 1]); 52 | n--; // shrinking the size of the heap 53 | 54 | heapify(v, 1, n); 55 | } 56 | } 57 | 58 | int main() 59 | { 60 | vector v{-1, 4, 6, 5, 4, 3, 8}; 61 | buildHeapOptimised(v); 62 | heapsort(v); 63 | 64 | for (int x : v) 65 | cout << x << " "; 66 | } 67 | -------------------------------------------------------------------------------- /Heaps/joinRopes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int joinRopes(int ropes[], int n) 6 | { 7 | // min heap -> greater 8 | 9 | // declare like this to directly make a min heap outta the array 10 | priority_queue, greater> pq(ropes, ropes + n); 11 | 12 | int cost = 0; 13 | while (pq.size() > 1) 14 | { 15 | int a = pq.top(); 16 | pq.pop(); 17 | 18 | int b = pq.top(); 19 | pq.pop(); 20 | 21 | int newRope = a + b; 22 | cost += newRope; 23 | 24 | pq.push(newRope); 25 | } 26 | 27 | return cost; 28 | } 29 | 30 | int main() 31 | { 32 | int ropes[] = {4, 3, 2, 6}; 33 | int n = 4; 34 | 35 | cout << joinRopes(ropes, n) << endl; 36 | } 37 | -------------------------------------------------------------------------------- /Heaps/kLargest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int kLargest(vector &v, int k) 6 | { 7 | priority_queue, greater> pq; 8 | int c = 0; 9 | 10 | for (size_t i = 0; i < v.size(); i++) 11 | { 12 | if (c < k) // we're gonna keep only 3 elements in the heap and pop/push when necessary; thus we need a count variable 13 | { 14 | pq.push(v[i]); 15 | c++; 16 | } 17 | else 18 | { 19 | if (v[i] > pq.top()) 20 | { 21 | pq.pop(); 22 | pq.push(v[i]); 23 | } 24 | } 25 | } 26 | 27 | return pq.top(); 28 | } 29 | 30 | int main() 31 | { 32 | 33 | vector v{2, 4, 1, 7, 5, 3}; 34 | 35 | int k; 36 | cin >> k; 37 | 38 | cout << kLargest(v, k) << " "; 39 | } 40 | -------------------------------------------------------------------------------- /Heaps/kMostFreqWords.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | vector kFrequent(vector &v, int k) 6 | { 7 | int c = 0; 8 | } 9 | -------------------------------------------------------------------------------- /Heaps/mergeKSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | typedef pair> node; 7 | 8 | vector mergeKSortedArrays(vector> arr) 9 | { 10 | vector result; 11 | 12 | priority_queue, greater> pq; // min heap 13 | 14 | 15 | for (size_t i = 0; i < arr.size(); i++) 16 | { 17 | pq.push({arr[i][0], {i, 0}}); // i-> array idx; 0->column 18 | } 19 | 20 | // remove elements from min heap and add to result vector 21 | while (!pq.empty()) 22 | { 23 | node curr = pq.top(); 24 | pq.pop(); 25 | 26 | int element = curr.first; 27 | int x = curr.second.first; // row in which element is present 28 | int y = curr.second.second; // col in which element is present 29 | 30 | result.push_back(element); // smallest element 31 | 32 | // push to the priority queue the next element(of the curr element) 33 | if (y + 1 < arr[x].size()) 34 | { 35 | pq.push({arr[x][y + 1], {x, y + 1}}); // row->x ; col ->y+1 36 | } 37 | } 38 | 39 | return result; 40 | } 41 | 42 | int main() 43 | { 44 | 45 | vector> arr{ 46 | {2, 6, 12, 15}, 47 | {1, 3, 14, 20}, 48 | {3, 5, 8, 10}}; 49 | 50 | vector output = mergeKSortedArrays(arr); 51 | 52 | for (auto x : output) 53 | { 54 | cout << x << " "; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Heaps/priorityQ_CustomClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Person 6 | { 7 | public: 8 | string name; 9 | int age; 10 | 11 | Person(string n, int a) 12 | { 13 | name = n; 14 | age = a; 15 | } 16 | }; 17 | 18 | class PersonCompare 19 | { 20 | public: 21 | bool operator()(Person p1, Person p2) 22 | { 23 | return p1.age < p2.age; 24 | } 25 | }; 26 | 27 | int main() 28 | { 29 | int n; 30 | cin >> n; 31 | 32 | priority_queue> pq; 33 | 34 | for (size_t i = 0; i < n; i++) 35 | { 36 | string name; 37 | int age; 38 | 39 | cin >> name >> age; 40 | 41 | Person p(name, age); 42 | pq.push(p); 43 | } 44 | int k = 3; 45 | for (size_t i = 0; i < k; i++) 46 | { 47 | Person P = pq.top(); 48 | cout << P.name << " " << P.age << endl; 49 | pq.pop(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Heaps/runningMedian.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | 8 | priority_queue leftHeap; // max heap 9 | priority_queue, greater> rightHeap; // min heap 10 | 11 | int d; 12 | cin >> d; 13 | leftHeap.push(d); 14 | 15 | float median = d; 16 | cout << median << " "; 17 | 18 | cin >> d; 19 | 20 | while (d != -1) 21 | { 22 | // either left heap or right will be bigger or they'll be equal 23 | 24 | if (leftHeap.size() > rightHeap.size()) 25 | { 26 | if (d < median) 27 | { 28 | rightHeap.push(leftHeap.top()); 29 | leftHeap.pop(); 30 | leftHeap.push(d); 31 | } 32 | 33 | else 34 | rightHeap.push(d); 35 | 36 | median = (leftHeap.top() + rightHeap.top()) / 2.0; 37 | } 38 | 39 | else if (leftHeap.size() == rightHeap.size()) 40 | { 41 | if (d < median) 42 | { 43 | leftHeap.push(d); 44 | median = leftHeap.top(); 45 | } 46 | 47 | else 48 | { 49 | rightHeap.push(d); 50 | median = rightHeap.top(); 51 | } 52 | } 53 | 54 | else // if leftHeap.size() < rightHeap.size() 55 | { 56 | if (d < median) 57 | leftHeap.push(d); 58 | 59 | else // if d > median, push it to right heap 60 | { 61 | leftHeap.push(rightHeap.top()); 62 | rightHeap.pop(); 63 | rightHeap.push(d); 64 | } 65 | 66 | median = (leftHeap.top() + rightHeap.top()) / 2.0; 67 | } 68 | 69 | cout << median << " "; 70 | cin >> d; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Heaps/topKFrequent.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | struct compare{ 6 | bool operator()(pairp1, pairp2){ 7 | 8 | // second => freq 9 | if(p1.second==p2.second) 10 | return p1.first > p2.first; 11 | return p1.second < p2.second; 12 | } 13 | }; 14 | 15 | void kFreq(int arr[], int n) 16 | { 17 | unordered_mapm; 18 | 19 | for (int i = 0; i < n; ++i) 20 | m[arr[i]]++; 21 | 22 | // create pq using unordered_map contents 23 | priority_queue, vector>, compare> pq(m. begin(), m.end()); 24 | 25 | int k = 1; 26 | for (int i = 0; i < k; ++i) 27 | { 28 | cout << pq.top().first << " "; 29 | pq.pop(); 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | int arr[] = {2,34,5,3,3,43,3}; 36 | 37 | kFreq(arr, 7); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /LRUCache.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | string key; 7 | int value; 8 | 9 | Node(string key, int value) { 10 | this->key = key; 11 | this->value = value; 12 | } 13 | }; 14 | 15 | class LRU { 16 | public: 17 | int maxSize; 18 | list l; 19 | unordered_map::iterator> mp; // it is an iterator to the node that's in the list 20 | 21 | LRU(int maxSize) { 22 | this->maxSize = maxSize > 1 ? maxSize : 1; // if maxSize == 0, set it to 1 (minimum of 1 is needed) 23 | } 24 | 25 | void insert(string key, int value) { 26 | if (mp.count(key)) { 27 | // update the key 28 | auto it = mp[key]; 29 | it->value = value; 30 | } 31 | else { 32 | // check if cache is full 33 | // if yes, remove LRU item from the cache 34 | 35 | if (l.size() == maxSize) { 36 | Node last = l.back(); 37 | mp.erase(last.key); 38 | l.pop_back(); 39 | } 40 | 41 | Node n(key, value); 42 | l.push_front(n); 43 | mp[key] = l.begin(); 44 | } 45 | } 46 | 47 | int* getValue(string key) { 48 | if (mp.count(key)) { 49 | auto it = mp[key]; 50 | int value = it->value; 51 | l.push_front(*it); 52 | l.erase(it); 53 | mp[key] = l.begin(); 54 | 55 | return &l.begin()->value; 56 | } 57 | 58 | return NULL; 59 | } 60 | 61 | string mostRecentKey() { 62 | return l.front().key; 63 | } 64 | }; 65 | 66 | int main() { 67 | int mx; cin >> mx; 68 | LRU lru(3); 69 | lru.insert("Pen Drive", 10); 70 | lru.insert("TWS", 20); 71 | lru.insert("Smartwatch", 30); 72 | cout << lru.mostRecentKey() << endl; 73 | 74 | lru.insert("Pen Drive", 40); 75 | cout << lru.mostRecentKey() << endl; 76 | 77 | lru.insert("SSD", 20); 78 | cout << lru.mostRecentKey() << endl; 79 | 80 | if (!lru.getValue("TWS")) cout << "TWS is not present"; 81 | if (!lru.getValue("Smartwatch")) cout << "Smartwatch is not present"; 82 | if (!lru.getValue("Pen Drive")) cout << "Pen Drive is not present"; 83 | 84 | } 85 | -------------------------------------------------------------------------------- /LRUCache_LEETCODE.cpp: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | public: 3 | list> lru; 4 | 5 | // iterator will store the respective address 6 | unordered_map>::iterator> mp; // {key, address} pair 7 | 8 | void updatePosition(int key, int value) { 9 | lru.erase(mp[key]); 10 | lru.push_front({key, value}); 11 | mp[key] = lru.begin(); // address of new position stored in the map 12 | } 13 | 14 | int capacity; 15 | LRUCache(int capacity) { 16 | this->capacity = capacity; 17 | } 18 | 19 | int get(int key) { 20 | if (mp.find(key) != mp.end()) { 21 | updatePosition(key, (*mp[key]).second); 22 | return (*mp[key]).second; 23 | } 24 | return -1; 25 | } 26 | 27 | void put(int key, int value) { 28 | if (mp.find(key) != mp.end()) updatePosition(key, value); 29 | else { 30 | // add to cache 31 | lru.push_front({key, value }); 32 | mp[key] = lru.begin(); 33 | 34 | if (mp.size() > capacity) { 35 | mp.erase(lru.back().first); 36 | lru.pop_back(); 37 | } 38 | } 39 | } 40 | }; 41 | 42 | 43 | -------------------------------------------------------------------------------- /Linked List/LLappend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Linked List/LLappend -------------------------------------------------------------------------------- /Linked List/LLappend.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | 7 | public: 8 | int data; 9 | Node *next; 10 | 11 | Node(int d) 12 | { 13 | data = d; 14 | next = NULL; 15 | } 16 | }; 17 | 18 | void create(Node *&head, int d) 19 | { 20 | if (head == NULL) 21 | { 22 | head = new Node(d); 23 | return; 24 | } 25 | 26 | Node *tail = head; 27 | 28 | while (tail->next != NULL) 29 | { 30 | tail = tail->next; 31 | } 32 | 33 | Node *t = new Node(d); 34 | 35 | tail->next = t; 36 | t->next = NULL; 37 | return; 38 | } 39 | 40 | int length(Node *head) 41 | { 42 | int c = 1; 43 | while (head != NULL) 44 | { 45 | c++; 46 | head = head->next; 47 | } 48 | 49 | return c; 50 | } 51 | 52 | Node *kAppend(Node *&head, int k) 53 | { 54 | k += 1; 55 | Node *newHead; 56 | Node *newTail; 57 | Node *tail = head; 58 | 59 | int l = length(head); 60 | k = k % l; // in case k>l 61 | int cnt = 1; 62 | 63 | while (tail->next != NULL) 64 | { 65 | if (cnt == l - k) 66 | { 67 | newTail = tail; 68 | } 69 | 70 | if (cnt == l - k + 1) 71 | { 72 | newHead = tail; 73 | } 74 | 75 | tail = tail->next; 76 | cnt++; 77 | } 78 | 79 | newTail->next = NULL; 80 | tail->next = head; 81 | 82 | return newHead; 83 | } 84 | 85 | void print(Node *head) 86 | { 87 | while (head != NULL) 88 | { 89 | cout << head->data << " "; 90 | head = head->next; 91 | } 92 | cout << endl; 93 | } 94 | 95 | int main() 96 | { 97 | 98 | Node *head = NULL; 99 | create(head, 1); 100 | create(head, 2); 101 | create(head, 3); 102 | create(head, 4); 103 | create(head, 5); 104 | create(head, 6); 105 | create(head, 7); 106 | 107 | print(head); 108 | 109 | Node *newHead = kAppend(head, 3); 110 | 111 | print(newHead); 112 | } 113 | -------------------------------------------------------------------------------- /Linked List/floydCycle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Linked List/floydCycle -------------------------------------------------------------------------------- /Linked List/intersection: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Linked List/intersection -------------------------------------------------------------------------------- /Linked List/kReverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | 6 | public: 7 | int data; 8 | Node*next; 9 | 10 | Node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | 15 | 16 | }; 17 | 18 | void create(Node*&head, int d){ 19 | 20 | if(head==NULL) 21 | { 22 | head = new Node(d); 23 | return; 24 | } 25 | 26 | Node*tail = head; 27 | while(tail->next!=NULL) 28 | { 29 | tail = tail->next; 30 | } 31 | 32 | Node *n = new Node(d); 33 | tail->next = n; 34 | return; 35 | 36 | } 37 | 38 | Node* krev(Node *&head, int k){ 39 | // base case 40 | if (!head) 41 | return NULL; 42 | 43 | Node*p = head; 44 | Node*q = NULL; 45 | 46 | Node*next = NULL; 47 | 48 | int cnt = 0; 49 | while (p != NULL and cnt < k) 50 | { 51 | next = p->next; 52 | 53 | p -> next = q; 54 | q = p; 55 | p = next; 56 | 57 | cnt++; 58 | } 59 | 60 | // next points to (k+1)th node 61 | 62 | if (next != NULL) 63 | head->next = krev(next, k); 64 | 65 | return q; 66 | } 67 | 68 | void print(Node*head){ 69 | 70 | while(head!=NULL) 71 | { 72 | cout << head->data<<" "; 73 | head = head->next; 74 | } 75 | cout << endl; 76 | } 77 | 78 | int main(){ 79 | Node*head = NULL; 80 | int K=3; 81 | 82 | // cin >> N; 83 | 84 | // for(int i=0;i> ele; 88 | // create(head, ele); 89 | 90 | // } 91 | 92 | create(head, 1); 93 | create(head, 2); 94 | create(head, 3); 95 | create(head, 4); 96 | create(head, 5); 97 | create(head, 6); 98 | create(head, 7); 99 | create(head, 8); 100 | create(head, 9); 101 | create(head, 10); 102 | 103 | print(head); 104 | 105 | head = krev(head,3); 106 | print(head); 107 | } -------------------------------------------------------------------------------- /Linked List/mergeSortedLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *next; 9 | 10 | Node(int d) 11 | { 12 | data = d; 13 | next = NULL; 14 | } 15 | }; 16 | 17 | void create(Node *&head, int d) 18 | { 19 | if (head == NULL) 20 | { 21 | head = new Node(d); 22 | return; 23 | } 24 | 25 | Node *tail = head; 26 | 27 | while (tail->next != NULL) 28 | { 29 | tail = tail->next; 30 | } 31 | 32 | Node *n = new Node(d); 33 | 34 | tail->next = n; 35 | 36 | return; 37 | } 38 | 39 | Node *merge(Node *a, Node *b) 40 | { 41 | 42 | if (a == NULL) 43 | return b; 44 | 45 | if (b == NULL) 46 | return a; 47 | 48 | Node *c; 49 | 50 | if (a->data < b->data) 51 | { 52 | c = a; 53 | c->next = merge(a->next, b); 54 | } 55 | else 56 | { 57 | c = b; 58 | c->next = merge(a, b->next); 59 | } 60 | 61 | return c; 62 | } 63 | 64 | void print(Node *head) 65 | { 66 | 67 | while (head != NULL) 68 | { 69 | cout << head->data << " "; 70 | head = head->next; 71 | } 72 | cout << endl; 73 | } 74 | 75 | int main() 76 | { 77 | 78 | Node *h1 = NULL; 79 | create(h1, 1); 80 | create(h1, 3); 81 | create(h1, 5); 82 | create(h1, 7); 83 | create(h1, 9); 84 | 85 | Node *h2 = NULL; 86 | create(h2, 2); 87 | create(h2, 4); 88 | create(h2, 6); 89 | create(h2, 8); 90 | create(h2, 10); 91 | 92 | print(h1); 93 | print(h2); 94 | 95 | // cout << merge(h1, h2) << endl; 96 | Node *m = merge(h1, h2); 97 | print(m); 98 | // cout << m << endl; 99 | } -------------------------------------------------------------------------------- /Linked List/palindrome: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Linked List/palindrome -------------------------------------------------------------------------------- /New Template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define pb push_back 5 | #define fr(a,b) for(int i = a; i < b; i++) 6 | #define fr2(a,b) for(int j = a; j < b; j++) 7 | #define fr3(a,b) for(int k = a; k < b; k++) 8 | #define fr4(i,a,b,u) for(int i = a; i < b; i+=u) 9 | #define endl "\n" 10 | #define vp vector> 11 | 12 | #define inf (1LL<<60) 13 | #define triplet pair> 14 | #define read(x) long long x; cin >> x 15 | 16 | #define ff first 17 | #define ss second 18 | #define int long long 19 | #define pii pair 20 | #define vi vector 21 | #define mii map 22 | #define pqb priority_queue 23 | #define pqs priority_queue > 24 | #define w(x) int x; cin>>x; while(x--) 25 | 26 | 27 | // ------------------------------------------------------------------------------------------------------- 28 | 29 | void solve() { 30 | 31 | ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 32 | 33 | // code: 34 | cout << 5; 35 | } 36 | 37 | int32_t main() { 38 | solve(); 39 | cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << "\n"; 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Number Theory/.cph/.prime1SPOJ.cpp_c231adfd75d997f3b2cd5c117d48f18b.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: prime1SPOJ","url":"/home/proghead00/Desktop/C++/Number Theory/prime1SPOJ.cpp","tests":[{"id":1614345369015,"input":"2\n1 10\n3 5","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Number Theory/prime1SPOJ.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Number Theory/.cph/.primeFactors.cpp_f20fa846ca04495405dd8a60d629d5db.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: primeFactors","url":"/home/proghead00/Desktop/C++/Number Theory/primeFactors.cpp","tests":[{"id":1614353416734,"input":"2\n10\n24","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Number Theory/primeFactors.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Number Theory/aFactorialProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // n! / k^x = 0 ...find max value of x 5 | -------------------------------------------------------------------------------- /Number Theory/largePrime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | const int n = 1000000; 7 | bitset<1000005> b; 8 | vector primes; 9 | 10 | void sieve() 11 | { 12 | 13 | // set all bits 14 | b.set(); //1,1,1,1,1,... 15 | 16 | b[0] = b[1] = 0; // since they're not primes 17 | 18 | for (long long int i = 2; i <= n; i++) 19 | { 20 | if (b[i]) 21 | { 22 | primes.push_back(i); 23 | 24 | // make multiples of the current prime 0 25 | for (long long int j = i * i; j <= n; j = j + i) 26 | { 27 | b[j] = 0; 28 | } 29 | } 30 | } 31 | } 32 | 33 | bool isPrime(long long num) 34 | { 35 | if (num <= n) 36 | { 37 | return b[num] == 1 ? true : false; //O(1) 38 | } 39 | 40 | for (long long int i = 0; primes[i] * (long long)primes[i] <= num; i++) 41 | { 42 | if (num % primes[i] == 0) 43 | return false; 44 | } 45 | 46 | return true; 47 | } 48 | 49 | int main() 50 | { 51 | 52 | sieve(); 53 | 54 | if (isPrime(3267000013)) 55 | { 56 | cout << "PRIME" << endl; 57 | } 58 | 59 | else 60 | 61 | cout << "NOT PRIME" << endl; 62 | } -------------------------------------------------------------------------------- /Number Theory/prime1SPOJ.cpp: -------------------------------------------------------------------------------- 1 | // SEGMENTED SIEVE 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | #define N 100000 // N = sqrt(n) 8 | 9 | vector primes; //will store prime nos. -> 2,3,5,7,... 10 | 11 | int p[N] = {0}; 12 | 13 | // 0 -> not prime 14 | // 1 -> prime 15 | 16 | void sieve() 17 | { 18 | 19 | for (size_t i = 2; i <= N; i++) 20 | { 21 | if (p[i] == 0) 22 | { 23 | primes.push_back(i); 24 | 25 | // mark on multiples as NON PRIME 26 | for (size_t j = i * i; j <= N; j++) 27 | { 28 | p[j] = 1; // not prime 29 | } 30 | } 31 | } 32 | } 33 | 34 | int main() 35 | { 36 | 37 | sieve(); // building sieve only once for all queries 38 | 39 | int t; 40 | cin >> t; 41 | 42 | while (t--) 43 | { 44 | 45 | int n, m; 46 | 47 | cin >> m >> n; 48 | 49 | bool segment[n - m + 1]; 50 | 51 | for (size_t i = 0; i < n - m + 1; i++) 52 | { 53 | segment[i] = 0; 54 | } 55 | 56 | for (auto x : primes) 57 | { 58 | if (x * x > n) 59 | { 60 | break; // stop loop if rermaining prime nos aren't needed 61 | } 62 | 63 | int start = (m / x) * x; 64 | 65 | if (x >= m and x <= n) 66 | { 67 | start = 2 * x; 68 | } 69 | 70 | // mark multiples of x as non prime 71 | for (size_t i = start; i <= n; i += x) 72 | { 73 | segment[i - m] = 1; 74 | } 75 | } 76 | 77 | for (size_t i = m; i <= n; i++) 78 | { 79 | if (segment[i - m] == 0 and i != 1) 80 | { 81 | cout << i << endl; 82 | } 83 | } 84 | 85 | cout << endl; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Number Theory/primeSieve: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Number Theory/primeSieve -------------------------------------------------------------------------------- /Number Theory/primeSieve.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // 1 -> PRIME 5 | 6 | void prime_sieve(int *p) 7 | { 8 | 9 | // first make all odd numbers prime 10 | 11 | for (size_t i = 3; i <= 1000000; i += 2) 12 | { 13 | p[i] = 1; 14 | } 15 | 16 | // sieve 17 | for (size_t i = 3; i <= 1000000; i++) 18 | { 19 | // if curr number is not marked, it is prime 20 | 21 | if (p[i] == 1) 22 | { 23 | // make all the multiples of i as NOT prime 24 | 25 | for (size_t j = i * i; j <= 1000000; j += i) 26 | { 27 | p[j] = 0; 28 | } 29 | } 30 | } 31 | 32 | // special case 33 | p[2] = 1; // since 2 is prime 34 | p[0] = p[1] = 0; // not prime 35 | } 36 | 37 | int main() 38 | { 39 | int n; 40 | cin >> n; 41 | 42 | int p[1000000] = {0}; 43 | prime_sieve(p); 44 | 45 | // primes upto range n 46 | for (size_t i = 0; i <= n; i++) 47 | { 48 | if (p[i] == 1) 49 | { 50 | cout << i << " "; 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /Number Theory/primeinRangeFASTER.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void prime_sieve(int *p) 5 | { 6 | 7 | // first make all odd numbers prime 8 | 9 | for (size_t i = 3; i <= 1000000; i += 2) 10 | { 11 | p[i] = 1; 12 | } 13 | 14 | // sieve 15 | for (size_t i = 3; i <= 1000000; i++) 16 | { 17 | // if curr number is not marked, it is prime 18 | 19 | if (p[i] == 1) 20 | { 21 | // make all the multiples of i as NOT prime 22 | 23 | for (size_t j = i * i; j <= 1000000; j += i) 24 | { 25 | p[j] = 0; 26 | } 27 | } 28 | } 29 | 30 | // special case 31 | p[2] = 1; // since 2 is prime 32 | p[0] = p[1] = 0; // not prime 33 | } 34 | 35 | int main() 36 | { 37 | int p[1000000] = {0}; 38 | prime_sieve(p); 39 | 40 | int csum[1000000] = {0}; 41 | 42 | // precompute primes upto i 43 | for (size_t i = 1; i <= 1000000; i++) 44 | { 45 | csum[i] = csum[i - 1] + p[i]; 46 | } 47 | 48 | int q; 49 | cin >> q; 50 | 51 | while (q--) 52 | { 53 | int a, b; 54 | 55 | cin >> a >> b; 56 | 57 | cout << csum[b] - csum[a - 1] << endl; 58 | } 59 | } -------------------------------------------------------------------------------- /Others/GFGSumCircular.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int maxCircularSum(int a[], int n) 5 | { 6 | if (n == 1) 7 | return a[0]; 8 | 9 | //sum 10 | int sum = 0; 11 | for (int i = 0; i < n; i++) 12 | { 13 | sum += a[i]; 14 | } 15 | 16 | int curr_max = a[0], max_so_far = a[0], curr_min = a[0], min_so_far = a[0]; 17 | 18 | // Kadane's Algorithm 19 | for (int i = 1; i < n; i++) 20 | { 21 | // Kadane's Algorithm to find Maximum subarray sum. 22 | curr_max = max(curr_max + a[i], a[i]); 23 | max_so_far = max(max_so_far, curr_max); 24 | 25 | // Kadane's Algorithm to find Minimum subarray sum. 26 | curr_min = min(curr_min + a[i], a[i]); 27 | min_so_far = min(min_so_far, curr_min); 28 | } 29 | 30 | if (min_so_far == sum) 31 | return max_so_far; 32 | 33 | // returning the maximum value 34 | return max(max_so_far, sum - min_so_far); 35 | } 36 | 37 | int main() 38 | { 39 | int a[] = {11, 10, -20, 5, -3, -5, 8, -13, 10}; 40 | int n = sizeof(a) / sizeof(a[0]); 41 | cout << "Maximum circular sum is " << maxCircularSum(a, n) << endl; 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Others/GFGformBiggestSum.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // A comparison function which 9 | // is used by sort() in 10 | // printLargest() 11 | int myCompare(string X, string Y) 12 | { 13 | // first append Y at the end of X 14 | string XY = X.append(Y); 15 | 16 | // then append X at the end of Y 17 | string YX = Y.append(X); 18 | 19 | // Now see which of the two 20 | // formed numbers is greater 21 | return XY.compare(YX) > 0 ? 1 : 0; 22 | } 23 | 24 | // The main function that prints 25 | // the arrangement with the 26 | // largest value. The function 27 | // accepts a vector of strings 28 | void printLargest(vector arr) 29 | { 30 | 31 | // Sort the numbers using 32 | // library sort function. The 33 | // function uses our comparison 34 | // function myCompare() to 35 | // compare two strings. See 36 | // http://www.cplusplus.com/reference/ 37 | // algorithm/sort/ 38 | // for details 39 | sort(arr.begin(), arr.end(), myCompare); 40 | 41 | for (int i = 0; i < arr.size(); i++) 42 | cout << arr[i]; 43 | } 44 | 45 | // Driver code 46 | int main() 47 | { 48 | vector arr; 49 | 50 | // output should be 6054854654 51 | arr.push_back("54"); 52 | arr.push_back("546"); 53 | arr.push_back("548"); 54 | arr.push_back("60"); 55 | printLargest(arr); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Others/carSortingVECTOR: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Others/carSortingVECTOR -------------------------------------------------------------------------------- /Others/carSortingVECTOR.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Car 7 | { 8 | 9 | public: 10 | string car_name; 11 | int x, y; 12 | 13 | Car(string n, int x, int y) 14 | { 15 | car_name = n; 16 | this->x = x; 17 | this->y = y; 18 | } 19 | 20 | int distance() 21 | { 22 | 23 | return x * x + y * y; 24 | } 25 | }; 26 | 27 | bool compare(Car A, Car B) 28 | { 29 | 30 | int d_a = A.distance(); 31 | 32 | int d_b = B.distance(); 33 | 34 | if (d_a == d_b) 35 | { 36 | return A.car_name < B.car_name; 37 | } 38 | 39 | return d_a < d_b; 40 | } 41 | 42 | int main(int argc, const char **argv) 43 | { 44 | 45 | int n; 46 | 47 | cin >> n; 48 | 49 | vector v; 50 | 51 | for (size_t i = 0; i < n; i++) 52 | { 53 | int x, y; 54 | 55 | string name; 56 | 57 | cin >> name >> x >> y; 58 | 59 | Car temp(name, x, y); 60 | 61 | v.push_back(temp); 62 | } 63 | 64 | sort(v.begin(), v.end(), compare); 65 | 66 | for (auto c : v) 67 | { 68 | cout << "Car: " << c.car_name << " Distance: " << c.distance() << " Location: " << c.x << "," << c.y << endl; 69 | } 70 | 71 | return 0; 72 | } -------------------------------------------------------------------------------- /Others/goldendeal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int t; 8 | cin >> t; 9 | while (t--) 10 | { 11 | long long n; 12 | cin >> n; 13 | 14 | long long x[n]; 15 | 16 | for (int i = 0; i < n; i++) 17 | { 18 | cin >> x[i]; 19 | } 20 | 21 | unordered_map hash; 22 | 23 | for (size_t i = 0; i < n; i++) 24 | hash[x[i]]++; 25 | 26 | int maxc = 0, ans = -1; 27 | for (auto i : hash) 28 | { 29 | if (maxc < i.second) 30 | { 31 | ans = i.first; 32 | maxc = i.second; 33 | } 34 | } 35 | 36 | if (ans > (n / 2)) 37 | cout << ans << endl; 38 | 39 | else 40 | cout << "-1" << endl; 41 | } 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Others/indianMoneySTL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool compare(int a, int b) 6 | { 7 | return a <= b; 8 | } 9 | 10 | int main() 11 | 12 | { 13 | int money; 14 | cin >> money; 15 | 16 | int coins[] = {1, 2, 5, 10, 20, 50, 100, 200, 1000, 2000}; 17 | int n = sizeof(coins) / sizeof(int); 18 | 19 | while (money > 0) 20 | { 21 | int lb = lower_bound(coins, coins + n, money, compare) - coins - 1; 22 | 23 | int m = coins[lb]; 24 | 25 | cout << m << ","; 26 | 27 | money = money - m; 28 | } 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Others/max.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | // your code goes here 7 | 8 | int N; 9 | cin >> N; 10 | 11 | // int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 12 | 13 | int max2; 14 | 15 | // for (int i = 0; i < 10; i++) 16 | // { 17 | // if (N % arr[i] == 0) 18 | // { 19 | // max2 = max(max2, arr[i]); 20 | // } 21 | // } 22 | // cout << max2; 23 | 24 | for (int i = 1; i <= 10; i++) 25 | { 26 | if (N % i == 0) 27 | max2 = max(max2, i); 28 | } 29 | cout << max2; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Queue/.cph/.nonRepeatingCharacter.cpp_c64a5375fdc9c294067a4fe0a54fa768.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: nonRepeatingCharacter","url":"c:\\Users\\proghead00\\Desktop\\C++\\Queue\\nonRepeatingCharacter.cpp","tests":[{"id":1619792835270,"input":"2\n4 1 3\nABBBCDDE\nEARTH\nINDIA\nUUUFFFDDD\n2 5 7\nSDHHD\nXOXOXOXO","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"c:\\Users\\proghead00\\Desktop\\C++\\Queue\\nonRepeatingCharacter.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Queue/implementationArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Queue 5 | { 6 | int *arr; 7 | int front, rear, curr_size, max_size; 8 | 9 | public: 10 | Queue(int default_size = 5) 11 | { 12 | 13 | arr = new int[default_size]; 14 | curr_size = 0; 15 | max_size = default_size; 16 | front = 0; 17 | rear = max_size - 1; 18 | } 19 | 20 | bool full() 21 | { 22 | return curr_size == max_size; 23 | } 24 | 25 | void push(int data) 26 | { 27 | if (!full()) 28 | { 29 | rear = (rear + 1) % max_size; 30 | arr[rear] = data; 31 | curr_size++; 32 | } 33 | } 34 | 35 | bool empty() 36 | { 37 | return curr_size == 0; 38 | } 39 | 40 | void pop() 41 | { 42 | if (!empty()) 43 | { 44 | front = (front + 1) % max_size; 45 | curr_size--; 46 | } 47 | } 48 | 49 | int front2() 50 | { 51 | if (!empty()) 52 | { 53 | return arr[front]; 54 | } 55 | } 56 | 57 | ~Queue() 58 | { 59 | if (arr != NULL) 60 | { 61 | delete[] arr; 62 | arr = NULL; 63 | } 64 | } 65 | }; 66 | 67 | int main() 68 | { 69 | 70 | Queue q(100); 71 | 72 | for (size_t i = 0; i <= 6; i++) 73 | { 74 | q.push(i); 75 | } 76 | 77 | q.pop(); 78 | q.pop(); 79 | 80 | q.push(7); 81 | 82 | while (!q.empty()) 83 | { 84 | cout << q.front2() << " "; 85 | q.pop(); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Queue/implementationLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | Node *next; 8 | Node(int d) 9 | { 10 | data = d; 11 | next = NULL; 12 | } 13 | }; 14 | 15 | class Queue 16 | { 17 | public: 18 | Node *front, *rear; 19 | Queue() 20 | { 21 | front = rear = NULL; 22 | } 23 | 24 | void enQueue(int x) 25 | { 26 | 27 | Node *temp = new Node(x); 28 | 29 | // If queue is empty, then new node is front and rear both 30 | if (rear == NULL) 31 | { 32 | front = rear = temp; 33 | return; 34 | } 35 | 36 | // Add the new node at the end of queue and change rear 37 | rear->next = temp; 38 | rear = temp; 39 | } 40 | 41 | void deQueue() 42 | { 43 | // If queue is empty, return NULL. 44 | if (front == NULL) 45 | return; 46 | 47 | // Store previous front and move front one node ahead 48 | Node *temp = front; 49 | front = front->next; 50 | 51 | // If front becomes NULL, then change rear also as NULL 52 | if (front == NULL) 53 | rear = NULL; 54 | 55 | delete (temp); 56 | } 57 | }; 58 | 59 | int main() 60 | { 61 | 62 | Queue q; 63 | q.enQueue(10); 64 | q.enQueue(20); 65 | q.deQueue(); 66 | q.deQueue(); 67 | q.enQueue(30); 68 | q.enQueue(40); 69 | q.enQueue(50); 70 | q.deQueue(); 71 | cout << "Queue Front : " << (q.front)->data << endl; 72 | cout << "Queue Rear : " << (q.rear)->data; 73 | } 74 | -------------------------------------------------------------------------------- /Queue/largestRectangularAreaHISTOGRAM.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int arr[] = {1, 2, 3, 4, 5}; 8 | stack s; 9 | int res = 0; 10 | int n = 5; 11 | int curr = -1; 12 | int tp = -1; 13 | for (size_t i = 0; i < n; i++) 14 | { 15 | while (!s.empty() and arr[s.top()] >= arr[i]) 16 | { 17 | tp = s.top(); 18 | s.pop(); 19 | 20 | curr = arr[tp] * (s.empty() ? i : (i - s.top() - 1)); 21 | 22 | res = max(res, curr); 23 | } 24 | 25 | s.push(i); 26 | } 27 | 28 | while (!s.empty()) 29 | { 30 | tp = s.top(); 31 | s.pop(); 32 | 33 | curr = arr[tp] * (s.empty() ? n : (n - s.top() - 1)); 34 | 35 | res = max(res, curr); 36 | } 37 | 38 | cout << res; 39 | } 40 | -------------------------------------------------------------------------------- /Queue/nextGreater2.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void printNGE(int arr[], int n) 6 | { 7 | stack s; 8 | 9 | int arr1[n]; 10 | 11 | for (int i = n - 1; i >= 0; i--) 12 | { 13 | 14 | while (!s.empty() && s.top() <= arr[i]) 15 | s.pop(); 16 | 17 | if (s.empty()) 18 | arr1[i] = -1; 19 | else 20 | arr1[i] = s.top(); 21 | 22 | s.push(arr[i]); 23 | } 24 | 25 | for (int i = 0; i < n; i++) 26 | cout << arr[i] << " ---> " << arr1[i] << endl; 27 | } 28 | 29 | int main() 30 | { 31 | int arr[] = {11, 13, 21, 3}; 32 | int n = sizeof(arr) / sizeof(arr[0]); 33 | printNGE(arr, n); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Queue/nonRepeatingCharacter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | queue q; 8 | int freq[27] = {0}; 9 | 10 | char ch; 11 | 12 | cin >> ch; 13 | 14 | while (ch != '.') 15 | { 16 | q.push(ch); 17 | 18 | freq[ch - 'a']++; 19 | 20 | while (!q.empty()) 21 | { 22 | // a is mapped with 0, b with 1, and so on... 23 | int idx = q.front() - 'a'; 24 | 25 | if (freq[idx] > 1) 26 | { 27 | q.pop(); 28 | } 29 | else 30 | { 31 | cout << q.front() << endl; 32 | break; 33 | } 34 | } 35 | 36 | if (q.empty()) 37 | { 38 | cout << "-1" << endl; 39 | } 40 | 41 | cin >> ch; 42 | } 43 | } -------------------------------------------------------------------------------- /Queue/prateekCoding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int main() 12 | { 13 | 14 | int q, i; 15 | cin >> q; // no. of queries 16 | long int a, b; 17 | stack s; 18 | 19 | for (i = 0; i < q; i++) 20 | { 21 | cin >> a; 22 | if (a == 1) 23 | { 24 | if (s.empty()) 25 | cout << "No Code\n"; 26 | else 27 | { 28 | cout << "Ans: " << s.top() << "\n"; 29 | s.pop(); 30 | } 31 | } 32 | else 33 | { 34 | cin >> b; 35 | s.push(b); 36 | } 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Queue/queueUsingStacks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // stack s1; 6 | // stack s2; 7 | 8 | void enq(stack s1, int x) 9 | { 10 | s1.push(x); 11 | } 12 | 13 | void deq(stack s1, stack s2) 14 | { 15 | if (s1.empty()) 16 | return; 17 | 18 | while (s1.size() > 1) 19 | { 20 | int ts1 = s1.top(); 21 | s2.push(ts1); 22 | 23 | s1.pop(); 24 | } 25 | 26 | cout << s1.top() << " "; 27 | s1.pop(); 28 | 29 | while (!s2.empty()) 30 | { 31 | cout << s2.top() << " "; 32 | s2.pop(); 33 | } 34 | } 35 | 36 | int main() 37 | { 38 | stack s1; 39 | stack s2; 40 | 41 | enq(s1, 10); 42 | enq(s1, 20); 43 | enq(s1, 30); 44 | enq(s1, 40); 45 | 46 | 47 | deq(s1, s2); 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Queue/queueWithStacks2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Queue { 5 | stack s1, s2; 6 | 7 | void enQueue(int x) 8 | { 9 | // Move all elements from s1 to s2 10 | while (!s1.empty()) { 11 | s2.push(s1.top()); 12 | s1.pop(); 13 | } 14 | 15 | // Push item into s1 16 | s1.push(x); 17 | 18 | // Push everything back to s1 19 | while (!s2.empty()) { 20 | s1.push(s2.top()); 21 | s2.pop(); 22 | } 23 | } 24 | 25 | // Dequeue an item from the queue 26 | int deQueue() 27 | { 28 | // if first stack is empty 29 | if (s1.empty()) { 30 | cout << "Q is Empty"; 31 | exit(0); 32 | } 33 | 34 | // Return top of s1 35 | int x = s1.top(); 36 | s1.pop(); 37 | return x; 38 | } 39 | }; 40 | 41 | 42 | int main() 43 | { 44 | Queue q; 45 | q.enQueue(1); 46 | q.enQueue(2); 47 | q.enQueue(3); 48 | 49 | cout << q.deQueue() << '\n'; 50 | cout << q.deQueue() << '\n'; 51 | cout << q.deQueue() << '\n'; 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Queue/redundantBrackets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include > 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | string s; 8 | stack st; 9 | 10 | cin >> s; 11 | 12 | int c = 0; 13 | for (size_t i = 0; i < s.size(); i++) 14 | { 15 | if (s[i] == ')') 16 | { 17 | if (st.top() == '(') 18 | c++; 19 | 20 | else 21 | { 22 | while (st.top() != '(') 23 | { 24 | st.pop(); 25 | } 26 | 27 | st.pop(); // popping out the opening bracket 28 | } 29 | } 30 | else 31 | { 32 | st.push(s[i]); 33 | } 34 | } 35 | 36 | if (c == 0) 37 | cout << "No duplicate"; 38 | 39 | else 40 | cout << "Duplicate"; 41 | } 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Interview/ Competitive Programming problems in C++ (ง'̀-'́)ง 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Recursion/Recursion Challenges/generate_strings_mapped.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void gen_string(char *in, char *out, int i, int j) 5 | { 6 | if(in[i]=='\0'){ 7 | out[j]='\0'; 8 | cout << out<< endl; 9 | return; 10 | } 11 | 12 | // single char 13 | int digit = in[i]-'0'; 14 | char ch = digit + 'A' - 1; 15 | out[j]=ch; 16 | gen_string(in, out, i+1, j+1); 17 | 18 | // double 19 | if(in[i+1]!='\0') 20 | { 21 | int second_digit = in[i+1]-'0'; 22 | int no = digit*10 + second_digit; 23 | 24 | if(no<=26) 25 | { 26 | ch = no + 'A' - 1; 27 | out[j]=ch; 28 | 29 | gen_string(in,out,i+2,j+1); 30 | 31 | } 32 | } 33 | return; 34 | } 35 | 36 | 37 | int main() { 38 | char in[100]; 39 | cin >> in; 40 | 41 | char out[100]; 42 | gen_string(in,out, 0,0); 43 | 44 | 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Recursion/Recursion Challenges/indices.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void idx(int *a, int n, int i, int x) 5 | { 6 | if(n==0) 7 | return; 8 | 9 | if(a[i]==x) 10 | { 11 | cout< 2 | using namespace std; 3 | 4 | void remove_dup(string s, int i) 5 | { 6 | if(i==s.size()) 7 | return; 8 | 9 | if(s[i]==s[i+1]) 10 | { 11 | remove_dup(s, i+1); 12 | } 13 | 14 | else{ 15 | cout << s[i]; 16 | remove_dup(s, i+1); } 17 | 18 | } 19 | 20 | 21 | 22 | int main() { 23 | string s = "maaaaam"; 24 | int n = s.size(); 25 | 26 | string s2; 27 | remove_dup(s, 0); 28 | // cout << s << "\n"; 29 | } 30 | -------------------------------------------------------------------------------- /Recursion/Recursion Challenges/replace_dup__.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void replace_dup(string &s, string &s2, int i) { 5 | if (i == s.size()) 6 | return; 7 | 8 | if (s[i] == s[i+1]) { 9 | s2.push_back(s[i]); 10 | s2.push_back('*'); 11 | } else { 12 | s2.push_back(s[i]); 13 | } 14 | replace_dup(s, s2, i+1); 15 | } 16 | 17 | 18 | int main() { 19 | string s = "hello"; 20 | int n = s.size(); 21 | 22 | string s2; 23 | replace_dup(s, s2, 0); 24 | cout << s2 << "\n"; 25 | } -------------------------------------------------------------------------------- /Recursion/Recursion Challenges/replace_pi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void pi(string s, int i, string &s2) 5 | { 6 | if(i==s.size()) 7 | return; 8 | 9 | if(s[i]=='p' and s[i+1]=='i') 10 | { 11 | s2.push_back('3'); 12 | s2.push_back('.'); 13 | s2.push_back('1'); 14 | s2.push_back('4'); 15 | 16 | pi(s, i+2, s2); 17 | 18 | } 19 | else 20 | { 21 | s2.push_back(s[i]); 22 | pi(s, i+1, s2); 23 | } 24 | 25 | 26 | } 27 | 28 | int main() { 29 | 30 | string s2; 31 | 32 | pi("xabpixx3.15x", 0, s2); 33 | 34 | cout << s2; 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Recursion/Recursion Challenges/replace_x.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void replacex(string s, int i) 5 | { 6 | int c = 0; 7 | if (i == s.size()) 8 | { 9 | return; 10 | } 11 | 12 | if (s[i] != 'x') 13 | { 14 | cout << s[i]; 15 | replacex(s, i + 1); 16 | } 17 | else 18 | { 19 | c++; 20 | replacex(s, i + 1); 21 | } 22 | 23 | for (int j = 0; j < c; j++) 24 | cout << 'x'; 25 | } 26 | 27 | int main() 28 | { 29 | replacex("axxxxxxbxc", 0); 30 | } 31 | -------------------------------------------------------------------------------- /Recursion/Recursion Challenges/smart_keypad_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | char table[][10] = { 5 | " ", ".+@$", "abc", "def", "ghi", 6 | "jkl" , "mno", "pqrs" , "tuv", "wxyz" 7 | }; 8 | 9 | void keymap(char *in, char *out, int i, int j) 10 | { 11 | 12 | if(in[i]=='\0') 13 | { 14 | out[j]='\0'; 15 | cout<> in; 43 | 44 | char out[1000]; 45 | keymap(in, out, 0, 0); 46 | } 47 | -------------------------------------------------------------------------------- /Recursion/Recursion Challenges/string_subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void str_subsequence(char *in, char *out, int i, int j) 5 | { 6 | if(in[i] =='\0') 7 | { 8 | out[j]='\0'; 9 | cout << out <<","; 10 | return; 11 | } 12 | 13 | // include curr character 14 | out[j]=in[i]; 15 | str_subsequence(in, out, i+1, j+1); 16 | 17 | // exclude curr char 18 | str_subsequence(in,out, i+1, j); 19 | } 20 | 21 | int main() { 22 | 23 | char in[]="abc"; 24 | char out[10]; 25 | 26 | str_subsequence(in,out,0,0); 27 | 28 | 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Recursion/Recursion Challenges/towerofhanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void toh(int n, char src, char helper, char dest) 5 | { 6 | if(n==0) // if 0 rings, do nothing 7 | return; 8 | 9 | 10 | toh(n-1, src, dest, helper); 11 | 12 | cout<< "Moving ring "<< n << " from "< 2 | using namespace std; 3 | 4 | int fact(int n) 5 | { 6 | if (n == 1) 7 | return 1; 8 | 9 | return n * fact(n - 1); 10 | } 11 | int ways(int n) 12 | { 13 | if (n == 1) 14 | return 1; 15 | 16 | if (n == 2) 17 | { 18 | return 2; 19 | } 20 | 21 | return (ways(n - 1) + ways(fact(n - 1) / fact(n - 2))); 22 | } 23 | 24 | int main() 25 | { 26 | int n; 27 | 28 | cin >> n; 29 | 30 | cout << ways(n) << endl; 31 | } -------------------------------------------------------------------------------- /Recursion/inversionCount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int merge(int *a, int s, int e) 5 | { 6 | int mid = (s + e) / 2; 7 | int i = s; 8 | int j = mid + 1; 9 | 10 | int k = s; 11 | 12 | int temp[100000000]; 13 | int c = 0; 14 | 15 | while (i <= mid && j <= e) 16 | { 17 | if (a[i] <= a[j]) 18 | { 19 | temp[k++] = a[i++]; 20 | } 21 | else 22 | { 23 | temp[k++] = a[j++]; 24 | 25 | // if the numbers aren't in sorted order 26 | c += mid - i + 1; 27 | } 28 | } 29 | 30 | while (i <= mid) 31 | { 32 | temp[k++] = a[i++]; 33 | } 34 | while (j <= e) 35 | { 36 | temp[k++] = a[j++]; 37 | } 38 | 39 | for (size_t i = s; i <= e; i++) 40 | { 41 | a[i] = temp[i]; 42 | } 43 | 44 | return c; 45 | } 46 | 47 | int inv(int *a, int s, int e) 48 | { 49 | if (s >= e) 50 | return 0; 51 | 52 | int mid = (s + e) / 2; 53 | 54 | int x = inv(a, s, mid); // no of inv in first half 55 | int y = inv(a, mid + 1, e); // second half 56 | 57 | int z = merge(a, s, e); // cross inv 58 | 59 | return x + y + z; 60 | } 61 | 62 | int main() 63 | { 64 | int n; 65 | cin >> n; 66 | 67 | int a[n]; 68 | for (size_t i = 0; i < n; i++) 69 | { 70 | cin >> a[i]; 71 | } 72 | 73 | cout << inv(a, 0, n - 1) << endl; 74 | } 75 | -------------------------------------------------------------------------------- /Recursion/occurences.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int first_occ(int *a, int n, int key) 5 | { 6 | 7 | if (n == 0) 8 | { 9 | return -1; 10 | } 11 | 12 | if (a[0] == key) 13 | return 0; 14 | 15 | int i = first_occ(a + 1, n - 1, key); 16 | 17 | if (i == -1) 18 | { 19 | return -1; 20 | } 21 | 22 | return i + 1; 23 | } 24 | 25 | int last_occ(int *a, int n, int key) 26 | 27 | { 28 | 29 | if (n == 0) 30 | { 31 | return -1; 32 | } 33 | 34 | int i = last_occ(a + 1, n - 1, key); 35 | if (i == -1) 36 | { 37 | if (a[0] == key) 38 | { 39 | return 0; 40 | } 41 | 42 | else 43 | return -1; 44 | } 45 | 46 | return i + 1; 47 | } 48 | 49 | void all_occurences(int *a, int i, int n, int key) 50 | { 51 | if (i == n) 52 | return; 53 | 54 | if (a[i] == key) 55 | { 56 | cout << i << " "; 57 | } 58 | 59 | all_occurences(a, i + 1, n, key); 60 | } 61 | 62 | int store_occurences(int *a, int i, int n, int key, int *out, int j) 63 | { 64 | if (i == n) 65 | { 66 | return j; 67 | } 68 | 69 | if (a[i] == key) 70 | { 71 | out[j] = i; 72 | return store_occurences(a, i + 1, n, key, out, j); 73 | } 74 | return store_occurences(a, i + 1, n, key, out, j); 75 | } 76 | 77 | int main() 78 | { 79 | int n; 80 | 81 | cin >> n; 82 | 83 | int a[n]; 84 | 85 | for (size_t i = 0; i < n; i++) 86 | { 87 | cin >> a[i]; 88 | } 89 | 90 | int k; 91 | cin >> k; 92 | 93 | int i = last_occ(a, n, k); 94 | 95 | cout << i << endl; 96 | } -------------------------------------------------------------------------------- /Recursion/quickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int partition(int *a, int s, int e) 5 | { 6 | int pivot = a[e]; 7 | 8 | int pIndex = s; // initially at start 9 | 10 | for (size_t i = s; i < e; i++) 11 | { 12 | if (a[i] <= pivot) 13 | { 14 | swap(a[i], a[pIndex]); 15 | 16 | pIndex++; 17 | } 18 | } 19 | 20 | swap(a[pIndex], a[e]); 21 | 22 | return pIndex; 23 | } 24 | 25 | void quicksort(int a[], int start, int end) 26 | { 27 | 28 | if (start >= end) 29 | { 30 | return; 31 | } 32 | 33 | int pindex = partition(a, start, end); 34 | quicksort(a, start, pindex - 1); 35 | quicksort(a, pindex + 1, end); 36 | } 37 | 38 | int main() 39 | { 40 | int n; 41 | cin >> n; 42 | 43 | int a[n]; 44 | 45 | for (size_t i = 0; i < n; i++) 46 | { 47 | cin >> a[i]; 48 | } 49 | 50 | quicksort(a, 0, n - 1); 51 | 52 | for (size_t i = 0; i < n; i++) 53 | { 54 | cout << a[i] << " "; 55 | } 56 | } -------------------------------------------------------------------------------- /Recursion/rMerge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(int *a, int s, int e) 5 | { 6 | int mid = s + (e - s) / 2; 7 | 8 | int i = s; 9 | int j = mid + 1; 10 | 11 | int k = s; 12 | 13 | int temp[100000]; 14 | 15 | while (i <= mid && j <= e) 16 | { 17 | if (a[i] < a[j]) 18 | { 19 | temp[k++] = a[i++]; 20 | } 21 | 22 | else 23 | temp[k++] = a[j++]; 24 | } 25 | 26 | while (i <= mid) 27 | { 28 | temp[k++] = a[i++]; 29 | } 30 | 31 | while (j <= e) 32 | { 33 | temp[k++] = a[j++]; 34 | } 35 | 36 | // copying to og array 37 | for (size_t i = s; i <= e; i++) 38 | { 39 | a[i] = temp[i]; 40 | } 41 | } 42 | 43 | void ms(int *a, int s, int e) 44 | { 45 | //1. base case 46 | if (s >= e) 47 | { 48 | return; 49 | } 50 | 51 | //2. divide 52 | int mid = s + (e - s) / 2; 53 | 54 | // recursively sort 55 | ms(a, s, mid); 56 | ms(a, mid + 1, e); 57 | 58 | // merge 2 arrays 59 | merge(a, s, e); 60 | } 61 | 62 | int main() 63 | { 64 | int n; 65 | cin >> n; 66 | 67 | int a[n]; 68 | for (size_t i = 0; i < n; i++) 69 | { 70 | cin >> a[i]; 71 | } 72 | int s = 0; 73 | int e = n - 1; 74 | 75 | ms(a, s, e); 76 | 77 | for (size_t i = 0; i < n; i++) 78 | { 79 | cout << a[i] << " "; 80 | } 81 | } -------------------------------------------------------------------------------- /Recursion/recursiveBubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void rbubble(int *a, int n, int j) 5 | 6 | { 7 | if (n == 1) 8 | { 9 | return; 10 | } 11 | 12 | if (j == n - 1) 13 | { 14 | rbubble(a, n - 1, 0); 15 | return; 16 | } 17 | 18 | if (a[j] > a[j + 1]) 19 | { 20 | swap(a[j], a[j + 1]); 21 | } 22 | 23 | rbubble(a, n, j + 1); 24 | 25 | return; 26 | } 27 | 28 | int main() 29 | { 30 | int n; 31 | cin >> n; 32 | 33 | int a[n]; 34 | 35 | for (size_t i = 0; i < n; i++) 36 | { 37 | cin >> a[i]; 38 | } 39 | 40 | rbubble(a, n, 0); 41 | 42 | for (size_t i = 0; i < n; i++) 43 | { 44 | cout << a[i] << " "; 45 | } 46 | } -------------------------------------------------------------------------------- /Recursion/tiling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int ways(int n) 5 | { 6 | if (n == 0) 7 | return 0; 8 | 9 | if (n < 4) 10 | { 11 | return 1; //1 way 12 | } 13 | 14 | if (n >= 4) 15 | { 16 | return (ways(n - 1)) + (ways(n - 4)); 17 | } 18 | } 19 | int main() 20 | 21 | { 22 | // wall size: 4 x N 23 | // tile size: 1,4 or 4,1 24 | 25 | int n; 26 | 27 | cin >> n; 28 | 29 | int w = ways(n); 30 | 31 | cout << w << endl; 32 | } -------------------------------------------------------------------------------- /Sorting/.cph/.kthRoot.cpp_ec45fa239f6ff86695833d6fe35eb036.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: kthRoot","url":"/home/proghead00/Desktop/C++/Sorting/kthRoot.cpp","tests":[{"id":1613405224337,"input":"2\n10 1\n1000000000000000 10","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Sorting/kthRoot.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Sorting/.cph/.pivot.cpp_92c3a12f5415a5c050f9b8800b229d3a.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: pivot","url":"/home/proghead00/Desktop/C++/Sorting/pivot.cpp","tests":[{"id":1613497064750,"input":"5\n4\n5\n1\n2\n3","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Sorting/pivot.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Sorting/.cph/.searchRotated.cpp_51fd8b92800f52cfca2aac316ffdd064.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: searchRotated","url":"/home/proghead00/Desktop/C++/Sorting/searchRotated.cpp","tests":[{"id":1613488040005,"input":"5\n4\n5\n1\n2\n3\n2","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Sorting/searchRotated.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Sorting/.cph/.sortgame.cpp_dd0ab307903c7282eb681d2ccd5969d2.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: sortgame","url":"/home/proghead00/Desktop/C++/Sorting/sortgame.cpp","tests":[{"id":1613400080474,"input":"79\n4\nEve 78\nBob 99\nSuzy 86\nAlice 86","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Sorting/sortgame.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Sorting/.cph/.stringSort.cpp_fdb6080d6adbb51f0b935fff51995cf9.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: stringSort","url":"/home/proghead00/Desktop/C++/Sorting/stringSort.cpp","tests":[{"id":1613473391869,"input":"4\nBatman\nBatmans\nBat\nBatter","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Sorting/stringSort.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Sorting/.cph/.upperAndLowerBound.cpp_a936454cddab71410a18a1b0b43feacd.prob: -------------------------------------------------------------------------------- 1 | {"name":"Local: upperAndLowerBound","url":"/home/proghead00/Desktop/C++/Sorting/upperAndLowerBound.cpp","tests":[{"id":1613486837822,"input":"5\n1 2 3 3 4\n3\n2\n3\n10","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"/home/proghead00/Desktop/C++/Sorting/upperAndLowerBound.cpp","group":"local","local":true} -------------------------------------------------------------------------------- /Sorting/kthRoot.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isAns(long long n, long long k, long long ans) 5 | { 6 | if (pow(ans, k) <= n) 7 | { 8 | return true; 9 | } 10 | 11 | return false; 12 | } 13 | int main() 14 | { 15 | long long t, n, k; 16 | 17 | cin >> t; 18 | 19 | while (t--) 20 | { 21 | cin >> n >> k; 22 | 23 | long long s = 1; 24 | long long e = n; 25 | long long ans; 26 | while (s <= e) 27 | { 28 | long long mid = (s + e) / 2; 29 | 30 | if (isAns(n, k, mid)) 31 | { 32 | ans = mid; 33 | s = mid + 1; 34 | } 35 | 36 | else 37 | e = mid - 1; 38 | } 39 | 40 | cout << ans << endl; 41 | } 42 | } -------------------------------------------------------------------------------- /Sorting/pivot.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int arr[10000]; 8 | int n; 9 | cin >> n; 10 | 11 | for (int i = 0; i < n; i++) 12 | { 13 | cin >> arr[i]; 14 | } 15 | 16 | int s = 0, e = n - 1; 17 | 18 | int mid; 19 | 20 | // at least 2 elements are reqd 21 | while (s < e) 22 | { 23 | mid = (s + e) / 2; 24 | 25 | if (arr[mid] < arr[e]) 26 | { 27 | e = mid; 28 | } 29 | 30 | else if (arr[mid] > arr[e]) 31 | s = mid + 1; 32 | } 33 | 34 | // e-1 (or s-1) if we want the HIGHEST ELEMENT before the drop 35 | // e (or s) if we want the MINIMUM ELEMENT making the drop 36 | cout << e - 1 << endl; 37 | } -------------------------------------------------------------------------------- /Sorting/searchRotated: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Sorting/searchRotated -------------------------------------------------------------------------------- /Sorting/searchRotated.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | 8 | cin >> n; 9 | 10 | int arr[n]; 11 | 12 | for (size_t i = 0; i < n; i++) 13 | { 14 | cin >> arr[i]; 15 | } 16 | 17 | int x; 18 | 19 | cin >> x; 20 | 21 | int s = 0, e = n - 1; 22 | 23 | int ans = -1; 24 | while (s <= e) 25 | 26 | { 27 | int mid = (s + e) / 2; 28 | 29 | if (arr[mid] == x) 30 | { 31 | cout << mid; 32 | return 0; 33 | } 34 | 35 | // first part 36 | else if (arr[s] < arr[mid]) 37 | { 38 | // 2 cases -> element on the left or right 39 | 40 | if (x >= arr[s] and x <= arr[mid]) 41 | { 42 | e = mid - 1; 43 | } 44 | else 45 | s = mid + 1; 46 | } 47 | 48 | else if (arr[s] > arr[mid]) 49 | { 50 | if (x >= arr[mid] and x <= arr[e]) 51 | s = mid + 1; 52 | 53 | else 54 | e = mid - 1; 55 | } 56 | } 57 | 58 | return -1; 59 | } -------------------------------------------------------------------------------- /Sorting/sortgame.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | bool myCompare(pair a, pair b) 7 | { 8 | if (a.second == b.second) 9 | return a.first < b.first; // names in lexicographic order when salaries are equal 10 | 11 | return a.second > b.second; // descending 12 | } 13 | 14 | int main() 15 | { 16 | int x, n, i; 17 | cin >> x; 18 | pair a[100000]; 19 | cin >> n; 20 | for (i = 0; i < n; i++) 21 | { 22 | cin >> a[i].first; // employee name i/p 23 | cin >> a[i].second; // salary i/p 24 | } 25 | sort(a, a + n, myCompare); 26 | 27 | for (i = 0; i < n and a[i].second >= x; i++) 28 | { 29 | cout << a[i].first << " " << a[i].second << endl; 30 | } 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Sorting/sortingLinear.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swap(int *a, int *b) 4 | { 5 | int temp = *a; 6 | *a = *b; 7 | *b = temp; 8 | } 9 | void sort012(int a[], int arr_size) 10 | { 11 | int lo = 0; 12 | int hi = arr_size - 1; 13 | int mid = 0; 14 | 15 | while (mid <= hi) 16 | { 17 | switch (a[mid]) 18 | { 19 | case 0: 20 | swap(&a[lo++], &a[mid++]); 21 | break; 22 | case 1: 23 | mid++; 24 | break; 25 | case 2: 26 | swap(&a[mid], &a[hi--]); 27 | break; 28 | } 29 | } 30 | } 31 | int main(int argc, char const *argv[]) 32 | { 33 | int n; 34 | cin >> n; 35 | int arr[n]; 36 | for (int i = 0; i < n; i++) 37 | { 38 | cin >> arr[i]; 39 | } 40 | sort012(arr, n); 41 | for (int i = 0; i < n; i++) 42 | { 43 | cout << " " << arr[i]; 44 | } 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Sorting/stringSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void sort(string a[], int n) 6 | { 7 | for (int i = 0; i < n - 1; i++) 8 | { 9 | for (int j = 0; j < n - 1 - i; j++) 10 | { 11 | 12 | if (a[j] > a[j + 1]) 13 | { 14 | string t = a[j]; 15 | a[j] = a[j + 1]; 16 | a[j + 1] = t; 17 | } 18 | } 19 | } 20 | } 21 | 22 | void substring(string s[], int n) 23 | { 24 | 25 | for (int i = 0; i < n; i++) 26 | { 27 | if (s[i + 1].find(s[i]) != string::npos) 28 | { 29 | if (s[i + 2].find(s[i + 1]) != string::npos) 30 | { 31 | string t = s[i + 1]; 32 | s[i + 1] = s[i + 2]; 33 | s[i + 2] = t; 34 | } 35 | 36 | string t = s[i]; 37 | s[i] = s[i + 1]; 38 | s[i + 1] = t; 39 | } 40 | } 41 | } 42 | int main() 43 | { 44 | int n; 45 | 46 | cin >> n; 47 | 48 | string s[n]; 49 | 50 | for (int i = 0; i < n; i++) 51 | { 52 | cin >> s[i]; 53 | } 54 | 55 | sort(s, n); 56 | 57 | substring(s, n); 58 | 59 | for (int i = 0; i < n; i++) 60 | { 61 | cout << s[i] << endl; 62 | } 63 | } -------------------------------------------------------------------------------- /Sorting/upperAndLowerBound.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // first and last occurences depending on queries 6 | int firstOcc(int a[], int n, int q) 7 | { 8 | int s = 0; 9 | int e = n - 1; 10 | 11 | int ans = -1; 12 | while (s <= e) 13 | { 14 | int mid = (s + e) / 2; 15 | 16 | if (a[mid] == q) 17 | { 18 | ans = mid; 19 | e = mid - 1; 20 | } 21 | 22 | else if (a[mid] > q) 23 | 24 | e = mid - 1; 25 | 26 | else 27 | s = mid + 1; 28 | } 29 | 30 | return ans; 31 | } 32 | 33 | int lastOcc(int a[], int n, int q) 34 | { 35 | int s = 0; 36 | int e = n - 1; 37 | 38 | int ans = -1; 39 | while (s <= e) 40 | { 41 | int mid = (s + e) / 2; 42 | 43 | if (a[mid] == q) 44 | { 45 | ans = mid; 46 | s = mid + 1; 47 | } 48 | 49 | else if (a[mid] > q) 50 | 51 | e = mid - 1; 52 | 53 | else 54 | s = mid + 1; 55 | } 56 | 57 | return ans; 58 | } 59 | 60 | int main() 61 | { 62 | int n; 63 | 64 | cin >> n; 65 | 66 | int arr[n]; 67 | 68 | for (size_t i = 0; i < n; i++) 69 | { 70 | cin >> arr[i]; 71 | } 72 | 73 | int q; 74 | 75 | cin >> q; 76 | 77 | int query[q]; 78 | 79 | for (size_t i = 0; i < q; i++) 80 | { 81 | cin >> query[i]; 82 | } 83 | 84 | for (size_t i = 0; i < q; i++) 85 | { 86 | int first = firstOcc(arr, n, query[i]); 87 | 88 | int last = lastOcc(arr, n, query[i]); 89 | 90 | cout << first << " " << last << endl; 91 | } 92 | } -------------------------------------------------------------------------------- /Stack/balancedParenthesis: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Stack/balancedParenthesis -------------------------------------------------------------------------------- /Stack/balancedParenthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool isvalid(char *s) 6 | { 7 | stack st; 8 | 9 | for (int i = 0; s[i] != '\0'; i++) 10 | { 11 | char ch = s[i]; 12 | 13 | if (ch == '(') 14 | { 15 | st.push(ch); 16 | } 17 | 18 | else if (s[i] == ')') 19 | 20 | { 21 | if (st.empty() == true or st.top() == ')') 22 | return false; 23 | 24 | st.pop(); 25 | } 26 | } 27 | return st.empty(); 28 | } 29 | 30 | int main() 31 | { 32 | 33 | char s[100000] = "a+b+ ()(b)"; 34 | 35 | if (isvalid(s)) 36 | { 37 | cout << "Yes"; 38 | } 39 | else 40 | cout << "No"; 41 | 42 | cout << endl; 43 | // cout << isvalid(s) << endl; 44 | } -------------------------------------------------------------------------------- /Stack/implementaionLL: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Stack/implementaionLL -------------------------------------------------------------------------------- /Stack/implementaionLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *next; 9 | 10 | Node(int d) 11 | { 12 | data = d; 13 | next = NULL; 14 | } 15 | }; 16 | 17 | class Stack 18 | { 19 | 20 | Node *head; 21 | 22 | int sz; 23 | 24 | public: 25 | Stack() 26 | { 27 | head = NULL; 28 | sz = 0; 29 | } 30 | 31 | void push(int x) 32 | { 33 | Node *temp = new Node(x); 34 | temp->next = head; 35 | head = temp; 36 | sz++; 37 | } 38 | 39 | int pop() 40 | { 41 | if (head == NULL) 42 | { 43 | cout << "There are no nodes in the Linked List!" << endl; 44 | return 9999; 45 | } 46 | 47 | int res = head->data; 48 | 49 | Node *temp = head; 50 | head = head->next; 51 | delete (temp); 52 | 53 | sz--; 54 | return res; 55 | } 56 | 57 | int size() 58 | { 59 | return sz; 60 | } 61 | 62 | bool isEmpty() 63 | { 64 | return (head == NULL); 65 | } 66 | 67 | int peek() 68 | { 69 | 70 | if (head == NULL) 71 | { 72 | cout << "There are no nodes in the Linked List!" << endl; 73 | return 9999; 74 | } 75 | return head->data; 76 | } 77 | }; 78 | 79 | int main() 80 | { 81 | 82 | Stack s; 83 | 84 | Node *head; 85 | 86 | s.push(1); 87 | s.push(2); 88 | s.push(3); 89 | s.push(4); 90 | s.push(5); 91 | 92 | cout << s.pop() << endl; 93 | 94 | cout << s.size() << endl; 95 | 96 | cout << s.isEmpty() << endl; 97 | cout << s.peek() << endl; 98 | } -------------------------------------------------------------------------------- /Stack/implementationArray: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Stack/implementationArray -------------------------------------------------------------------------------- /Stack/implementationArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Stack 5 | { 6 | 7 | int *arr; 8 | int cap; 9 | int top; 10 | 11 | public: 12 | Stack(int c) 13 | { 14 | cap = c; 15 | arr = new int[cap]; 16 | top = -1; 17 | } 18 | 19 | void push(int x) 20 | { 21 | top++; 22 | arr[top] = x; 23 | } 24 | 25 | int pop() 26 | { 27 | int res = arr[top]; 28 | top--; 29 | return res; 30 | } 31 | 32 | int peek() 33 | { 34 | return arr[top]; 35 | } 36 | 37 | int size() 38 | { 39 | return (top + 1); 40 | } 41 | 42 | bool isEmpty() 43 | { 44 | return (top == -1); 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | Stack s(5); 51 | s.push(1); 52 | s.push(2); 53 | s.push(3); 54 | s.push(4); 55 | s.push(5); 56 | 57 | cout << s.pop() << endl; 58 | cout << s.size() << endl; 59 | cout << s.peek() << endl; 60 | cout << s.isEmpty() << endl; 61 | } -------------------------------------------------------------------------------- /Stack/implementationVector: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Stack/implementationVector -------------------------------------------------------------------------------- /Stack/implementationVector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | class Stack 6 | { 7 | private: 8 | vector v; 9 | 10 | public: 11 | void push(int data) 12 | { 13 | v.push_back(data); 14 | } 15 | 16 | bool empty() 17 | { 18 | return v.size() == 0; 19 | } 20 | 21 | void pop() 22 | { 23 | if (!empty()) 24 | v.pop_back(); 25 | } 26 | 27 | int top() 28 | { 29 | return v[v.size() - 1]; 30 | } 31 | }; 32 | 33 | int main() 34 | { 35 | Stack s; 36 | 37 | for (size_t i = 0; i < 5; i++) 38 | { 39 | s.push(i); 40 | } 41 | 42 | while (!s.empty()) 43 | { 44 | cout << s.top() << endl; 45 | s.pop(); 46 | } 47 | } -------------------------------------------------------------------------------- /Stack/largestAreaHistogram: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Stack/largestAreaHistogram -------------------------------------------------------------------------------- /Stack/largestAreaHistogram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int bar(int arr[], int n) 6 | { 7 | 8 | stack s; 9 | int res = 0; 10 | 11 | int t; 12 | int curr = 0; 13 | int i = 0; 14 | for (i = 0; i < n; i++) 15 | { 16 | 17 | // find prev smaller element 18 | while (s.empty() == false && arr[s.top() >= arr[i]]) 19 | { 20 | t = s.top(); 21 | s.pop(); 22 | 23 | curr = arr[t] * (s.empty() ? i : (i - s.top() - 1)); 24 | 25 | res = max(res, curr); 26 | } 27 | 28 | s.push(i); 29 | } 30 | 31 | // elements which do not have any smaller element on the right 32 | while (s.empty() == false) 33 | { 34 | t = s.top(); 35 | s.pop(); 36 | 37 | curr = arr[t] * (s.empty() ? n : (n - s.top() - 1)); 38 | 39 | res = max(res, curr); 40 | } 41 | 42 | return res; 43 | } 44 | 45 | int main() 46 | { 47 | int arr[] = {6, 2, 5, 4, 5, 1, 6}; 48 | int n = sizeof(arr) / sizeof(arr[0]); 49 | 50 | cout << bar(arr, n) << endl; 51 | } -------------------------------------------------------------------------------- /Stack/nextGreater.cpp: -------------------------------------------------------------------------------- 1 | // Problem with the code: Output is always "-1" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | 10 | vector nextGreater(int arr[], int n) 11 | { 12 | stack s; 13 | vector v; 14 | 15 | s.push(arr[n - 1]); 16 | cout << "-1" 17 | << " "; 18 | 19 | for (size_t i = n - 2; i >= 0; i--) 20 | { 21 | while (!s.empty() && s.top() <= arr[i]) 22 | { 23 | s.pop(); 24 | } 25 | 26 | int nextG = (s.empty()) ? -1 : s.top(); 27 | v.push_back(nextG); 28 | 29 | s.push(arr[i]); 30 | 31 | } 32 | 33 | // reverse(v.begin(), v.end()); 34 | // return v; 35 | } 36 | 37 | int main() 38 | { 39 | int arr[] = {5, 15, 10, 8, 6, 12, 9, 18}; 40 | 41 | vector v1; 42 | v1 = nextGreater(arr, 8); 43 | 44 | for (auto i : v1) 45 | cout << i << " "; 46 | } 47 | -------------------------------------------------------------------------------- /Stack/reverseStack1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Stack/reverseStack1 -------------------------------------------------------------------------------- /Stack/reverseStack1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void transfer(stack &s1, stack &s2, int n) 6 | { 7 | for (size_t i = 0; i < n; i++) 8 | { 9 | s2.push(s1.top()); 10 | s1.pop(); 11 | } 12 | } 13 | 14 | void reverse(stack &s1) 15 | { 16 | // helper stack for 17 | stack s2; 18 | 19 | int n = s1.size(); 20 | 21 | for (size_t i = 0; i < n; i++) 22 | { 23 | // pick the element at top and insert at bottom 24 | int x = s1.top(); 25 | s1.pop(); 26 | 27 | // transfer n-i-1 from s1 to s2 28 | transfer(s1, s2, n - i - 1); 29 | 30 | // insert x in s1 31 | s1.push(x); 32 | 33 | // transfer n-i-1 from s2 to s1 34 | transfer(s2, s1, n - i - 1); 35 | } 36 | } 37 | 38 | int main() 39 | { 40 | stack s; 41 | 42 | s.push(1); 43 | s.push(2); 44 | s.push(3); 45 | s.push(4); 46 | 47 | reverse(s); 48 | while (!s.empty()) 49 | { 50 | cout << s.top() << " "; 51 | s.pop(); 52 | } 53 | } -------------------------------------------------------------------------------- /Stack/reverseStackRecursion: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Stack/reverseStackRecursion -------------------------------------------------------------------------------- /Stack/reverseStackRecursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void insertAtBottom(stack &s, int x) 6 | { 7 | if (s.empty()) 8 | { 9 | s.push(x); 10 | return; 11 | } 12 | 13 | int data = s.top(); 14 | s.pop(); 15 | insertAtBottom(s, x); 16 | 17 | s.push(data); 18 | } 19 | 20 | void revRec(stack &s) 21 | { 22 | if (s.empty()) 23 | { 24 | return; 25 | } 26 | 27 | // pop out the top element and insert it at the bottom of reversed smaller stack 28 | int x = s.top(); 29 | s.pop(); 30 | 31 | // rec reverse the smaller stack 32 | revRec(s); 33 | 34 | insertAtBottom(s, x); 35 | } 36 | 37 | int main() 38 | { 39 | stack s; 40 | 41 | s.push(1); 42 | s.push(2); 43 | s.push(3); 44 | s.push(4); 45 | 46 | revRec(s); 47 | while (!s.empty()) 48 | { 49 | cout << s.top() << " "; 50 | s.pop(); 51 | } 52 | } -------------------------------------------------------------------------------- /Stack/stockSpan: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Stack/stockSpan -------------------------------------------------------------------------------- /Stack/stockSpan.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void span(int arr[], int n) 6 | { 7 | stack s; 8 | s.push(0); //pushing the index 9 | 10 | cout << "1" 11 | << " "; 12 | 13 | for (size_t i = 1; i < n; i++) 14 | { 15 | while (s.empty() == false && arr[s.top()] <= arr[i]) 16 | s.pop(); 17 | 18 | int span = s.empty() ? i + 1 : i - s.top(); 19 | 20 | cout << span << " "; 21 | 22 | s.push(i); 23 | } 24 | } 25 | 26 | int main() 27 | { 28 | 29 | int arr[] = {60, 10, 20, 15, 35, 50}; 30 | span(arr, 6); 31 | } 32 | -------------------------------------------------------------------------------- /Strings/CBNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(int argc, char) 5 | { 6 | // 1. 0 and 1 are not a CB number. 7 | // 2. 2,3,5,7,11,13,17,19,23,29 are CB numbers. 8 | // 3. Any number not divisible by the numbers in point 2( Given above ) are also CB numbers. 9 | 10 | // Deepak's task -> no. of CB nos in the string 11 | //CB must not be sub or super string 12 | // Ex- In **4991**, both **499** and **991** are CB numbers but you can choose either **499** or **991**, not both. 13 | 14 | // - Further, the CB number formed can only be a sub-string of the string 15 | // Ex - In **481**, you can not take **41** as CB number because 41 is not a sub-string of **481**. 16 | 17 | string s; 18 | cin >> s; 19 | 20 | if (s.length() == 1) 21 | { 22 | char ch = s[0]; 23 | if (ch == '1' || ch == '0') 24 | { 25 | cout << "Invalid"; 26 | return; 27 | } 28 | 29 | int c = 1; 30 | 31 | int cb[100]; 32 | for (int i = 0; i < s.length(); i++) 33 | { 34 | 35 | // int cb[] = {2, 36 | // 3, 37 | // 5, 38 | // 7, 39 | // 11, 40 | // 13, 41 | // 17, 42 | // 19, 43 | // 23, 44 | // 29}; 45 | int cb2 = 2 * c - i; 46 | cb[i] = cb2; //2,3,5,7,..., 29 47 | c++; 48 | 49 | for (int j = 0; j < s.length(); j++) 50 | { 51 | if (j % cb[i] != 0) 52 | { 53 | cb[i] = j; 54 | } 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Strings/canYouReadThis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main(int argc, char) 7 | { 8 | 9 | string a; 10 | cin >> a; 11 | cout << a[0]; 12 | for (int i = 1; i < a.size(); i++) 13 | { 14 | if (isupper(a[i])) 15 | { 16 | cout << endl; 17 | cout << a[i]; 18 | // continue; 19 | } 20 | else 21 | { 22 | cout << a[i]; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Strings/isPalRecursion.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | bool isPalRec(char str[], int s, int e) 6 | { 7 | 8 | // If there is only one character 9 | if (s == e) 10 | return true; 11 | 12 | // If first and last 13 | // characters do not match 14 | if (str[s] != str[e]) 15 | return false; 16 | 17 | if (s < e + 1) 18 | return isPalRec(str, s + 1, e - 1); 19 | 20 | return true; 21 | } 22 | 23 | bool isPalindrome(char str[]) 24 | { 25 | int n = strlen(str); 26 | 27 | // An empty string is 28 | // considered as palindrome 29 | if (n == 0) 30 | return true; 31 | 32 | return isPalRec(str, 0, n - 1); 33 | } 34 | 35 | int main() 36 | { 37 | char str[] = "geeg"; 38 | 39 | if (isPalindrome(str)) 40 | cout << "Yes"; 41 | else 42 | cout << "No"; 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Strings/maxCharFreq.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | string s; 7 | cin >> s; 8 | 9 | int freq[100] = {0}; 10 | 11 | for (int i = 0; i < s.length(); i++) 12 | { 13 | freq[s[i] - 'A']++; 14 | } 15 | 16 | int maxVal = 0; 17 | char maxChar; 18 | 19 | for (int i = 0; i < 100; i++) 20 | { 21 | if (freq[i] != 0) 22 | { 23 | if (freq[i] > maxVal) 24 | { 25 | maxVal = freq[i]; 26 | maxChar = i + 'A'; 27 | } 28 | } 29 | } 30 | cout << maxChar << endl; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Strings/sortString: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Strings/sortString -------------------------------------------------------------------------------- /Strings/stringCompression: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Strings/stringCompression -------------------------------------------------------------------------------- /Strings/stringCompression.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printRLE(string str) 5 | { 6 | int n = str.length(); 7 | for (int i = 0; i < n; i++) 8 | { 9 | 10 | // Count occurrences of current character 11 | int count = 1; 12 | while (i < n - 1 && str[i] == str[i + 1]) 13 | { 14 | count++; 15 | i++; 16 | } 17 | 18 | // Print character and its count 19 | cout << str[i] << count; 20 | } 21 | } 22 | 23 | int main() 24 | { 25 | string str = "wwwwaaadexxxxxxywww"; 26 | printRLE(str); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Strings/ultrafastmathematicians.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(int argc, char) 5 | { 6 | // no made of 0 , 1 7 | // i-th digit = 1 if i-th digit of 2 diff nos. differ 8 | //else i-th digit = 0 9 | 10 | // 0010 0010 11 | // ans: 0000 12 | 13 | string s1, s2; 14 | 15 | string s3; 16 | cin >> s1 >> s2; 17 | 18 | for (int i = 0; i < s1.length(); i++) 19 | { 20 | if (s1[i] - s2[i] == 0) 21 | { 22 | s3[i] = '0'; 23 | cout << s3[i]; 24 | } 25 | else 26 | { 27 | s3[i] = '1'; 28 | cout << s3[i]; 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Trees Challenges/bottomView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class node 9 | { 10 | public: 11 | int data; 12 | node *left; 13 | node *right; 14 | 15 | node(int d) 16 | { 17 | data = d; 18 | left = NULL; 19 | right = NULL; 20 | } 21 | }; 22 | 23 | void bottomView(node *root) 24 | { 25 | 26 | queue> q; // node, hd --> take out curr node and hd 27 | q.push({root, 0}); 28 | 29 | map> mp; 30 | 31 | while (!q.empty()) 32 | { 33 | auto f = q.front(); 34 | 35 | node *curr = f.first; 36 | int hd = f.second; 37 | 38 | if (!mp.count(hd)) 39 | mp[hd].push_back(curr->data); 40 | 41 | else 42 | { 43 | for (auto p : mp) 44 | { 45 | vector v = p.second; 46 | 47 | replace(p.second.begin(), p.second.end(), 1, v[hd]); 48 | } 49 | } 50 | // mp[hd].push_back(curr->data); 51 | q.pop(); 52 | 53 | if (curr->left) 54 | q.push({curr->left, hd - 1}); 55 | 56 | if (curr->right) 57 | q.push({curr->right, hd + 1}); 58 | } 59 | 60 | for (auto p : mp) 61 | { 62 | vector v = p.second; 63 | 64 | for (int x : v) 65 | cout << x << " "; 66 | 67 | cout << endl; 68 | } 69 | } 70 | 71 | int main() 72 | { 73 | node *root = new node(10); 74 | root->left = new node(20); 75 | root->right = new node(30); 76 | root->left->left = new node(40); 77 | root->right->left = new node(60); 78 | root->left->right = new node(50); 79 | 80 | bottomView(root); 81 | } 82 | -------------------------------------------------------------------------------- /Trees Challenges/isBalanced.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/Trees Challenges/isBalanced.cpp -------------------------------------------------------------------------------- /Trees Challenges/keysInRange.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node *left; 10 | node *right; 11 | 12 | node(int d) 13 | { 14 | data = d; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | }; 19 | 20 | void Print(node *root, int k1, int k2) 21 | { 22 | 23 | if (root == NULL) 24 | return; 25 | 26 | if (k1 < root->data) 27 | Print(root->left, k1, k2); 28 | 29 | if (k1 <= root->data && k2 >= root->data) 30 | cout << root->data << " "; 31 | 32 | if (k2 > root->data) 33 | Print(root->right, k1, k2); 34 | } 35 | 36 | 37 | 38 | int main() 39 | { 40 | 41 | int k1 = 10, k2 = 25; 42 | 43 | node *root = new node(20); 44 | root->left = new node(8); 45 | root->right = new node(22); 46 | root->left->left = new node(4); 47 | root->left->right = new node(12); 48 | 49 | Print(root, k1, k2); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Trees Challenges/structurallyIndenticalTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node 5 | { 6 | public: 7 | int data; 8 | node *left; 9 | node *right; 10 | 11 | node(int d) 12 | { 13 | data = d; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | bool isSame(node *a, node *b) 20 | { 21 | // 1. both empty 22 | if (a == NULL && b == NULL) 23 | return true; 24 | 25 | // 2. both non-empty -> compare them 26 | if (a != NULL && b != NULL) 27 | { 28 | return ( 29 | isSame(a->left, b->left) and 30 | isSame(a->right, b->right)); 31 | } 32 | 33 | // 3. one empty, one not -> false 34 | return 0; 35 | } 36 | 37 | int main() 38 | { 39 | node *root1 = new node(10); 40 | node *root2 = new node(100); 41 | root1->left = new node(7); 42 | root1->right = new node(15); 43 | root1->left->left = new node(4); 44 | root1->left->right = new node(9); 45 | root1->right->right = new node(20); 46 | 47 | root2->left = new node(70); 48 | root2->right = new node(150); 49 | root2->left->left = new node(40); 50 | root2->left->right = new node(90); 51 | root2->right->right = new node(200); 52 | 53 | if (isSame(root1, root2)) 54 | printf("Yes"); 55 | else 56 | printf("No"); 57 | } 58 | -------------------------------------------------------------------------------- /Trees Challenges/sumAtK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node 5 | { 6 | int data; 7 | struct node *left; 8 | struct node *right; 9 | }; 10 | 11 | struct node *newNode(int data) 12 | { 13 | struct node *temp = new struct node; 14 | temp->data = data; 15 | temp->left = nullptr; 16 | temp->right = nullptr; 17 | return temp; 18 | }; 19 | 20 | int sumOfNodesAtNthLevel(struct node *root, int k) 21 | { 22 | 23 | if (root == nullptr) 24 | return 0; 25 | 26 | queue que; 27 | 28 | que.push(root); 29 | 30 | // Level is used to track 31 | // the current level 32 | int level = 0; 33 | 34 | int sum = 0; 35 | 36 | int flag = 0; 37 | 38 | while (!que.empty()) 39 | { 40 | 41 | int size = que.size(); 42 | 43 | while (size--) 44 | { 45 | 46 | struct node *ptr = que.front(); 47 | que.pop(); 48 | 49 | if (level == k) 50 | { 51 | 52 | flag = 1; 53 | 54 | sum += ptr->data; 55 | } 56 | else 57 | { 58 | 59 | if (ptr->left) 60 | que.push(ptr->left); 61 | 62 | if (ptr->right) 63 | que.push(ptr->right); 64 | } 65 | } 66 | 67 | level++; 68 | 69 | // Break out from the loop after the sum 70 | // of nodes at K level is found 71 | if (flag == 1) 72 | break; 73 | } 74 | return sum; 75 | } 76 | 77 | int main() 78 | { 79 | struct node *root = new struct node; 80 | 81 | root = newNode(50); 82 | root->left = newNode(30); 83 | root->right = newNode(70); 84 | root->left->left = newNode(20); 85 | root->left->right = newNode(40); 86 | root->right->left = newNode(60); 87 | int level = 2; 88 | int result = sumOfNodesAtNthLevel(root, level); 89 | 90 | cout << result; 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /Trees Challenges/zigzag.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class node 9 | { 10 | public: 11 | int data; 12 | node *left; 13 | node *right; 14 | node(int d) 15 | { 16 | data = d; 17 | left = NULL; 18 | right = NULL; 19 | } 20 | }; 21 | 22 | vector zigzag(node *root) 23 | { 24 | queue q; 25 | q.push(root); 26 | vector ans; 27 | 28 | if (root == NULL) 29 | return ans; 30 | 31 | int f = 1; 32 | while (!q.empty()) 33 | { 34 | vector temp; 35 | int sz = q.size(); 36 | 37 | while (sz--) 38 | { 39 | node *t = q.front(); 40 | temp.push_back(t->data); 41 | q.pop(); 42 | 43 | if (t->left) 44 | { 45 | q.push(t->left); 46 | } 47 | 48 | if (t->right) 49 | { 50 | q.push(t->right); 51 | } 52 | } 53 | 54 | if (f % 2 == 0) 55 | reverse(temp.begin(), temp.end()); 56 | 57 | for (size_t i = 0; i < temp.size(); i++) 58 | { 59 | ans.push_back(temp[i]); 60 | } 61 | f = !f; 62 | } 63 | 64 | return ans; 65 | } 66 | 67 | int main() 68 | { 69 | node *root = new node(2); 70 | root->left = new node(1); 71 | root->right = new node(3); 72 | root->right->left = new node(4); 73 | root->left->right = new node(5); 74 | 75 | vector v = zigzag(root); 76 | for (int x : v) 77 | { 78 | cout << x << " "; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Tries/(same)checkIfWordsArePresentInTheSENTENCE.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | char data; 7 | bool isTerminal; 8 | unordered_map mp; 9 | Node(char d) { 10 | data = d; 11 | isTerminal = false; 12 | } 13 | }; 14 | 15 | class Trie { 16 | public: 17 | Node* root; 18 | Trie() { 19 | root = new Node('\0'); 20 | } 21 | 22 | void insert(string words) { 23 | Node* temp = root; 24 | for (auto w : words) { 25 | if (!temp->mp.count(w)) { 26 | Node* n = new Node(w); 27 | temp->mp[w] = n; 28 | } 29 | 30 | temp = temp->mp[w]; 31 | } 32 | 33 | temp->isTerminal = true; 34 | } 35 | 36 | void srchHelper(string s, int i, unordered_map &srchMp) { 37 | Node* temp = root; 38 | 39 | for (int j = i; j < s.size(); j++) { 40 | char ch = s[j]; 41 | 42 | if (!temp->mp.count(ch)) return; 43 | 44 | temp = temp->mp[ch]; 45 | 46 | if (temp->isTerminal) { 47 | string part = s.substr(i, j - i + 1); 48 | srchMp[part] = true; 49 | } 50 | } 51 | 52 | return; 53 | } 54 | 55 | void search(string s, vector words) { 56 | 57 | for (auto w : words) insert(w); 58 | 59 | unordered_map srchMp; 60 | 61 | for (int i = 0; i < s.size(); i++) { 62 | srchHelper(s, i, srchMp); 63 | } 64 | 65 | for (auto w : words) { 66 | if (srchMp[w]) cout << w << ": YES"; 67 | else cout << w << " NO"; 68 | cout << endl; 69 | 70 | } 71 | 72 | return; 73 | 74 | } 75 | 76 | }; 77 | 78 | 79 | int main() { 80 | string s = "little cute cat loves"; 81 | vector words = {"cute cat", "ttle", "kek"}; 82 | Trie t; 83 | t.search(s, words); 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /Tries/completeString_CN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | char data; 7 | unordered_map mp; 8 | bool isTerminal; 9 | 10 | Node(char d) { 11 | data = d; 12 | isTerminal = false; 13 | } 14 | }; 15 | 16 | class Trie { 17 | public: 18 | 19 | Node* root; 20 | 21 | Trie() { 22 | root = new Node('\0'); 23 | } 24 | 25 | void insert(string word) { 26 | 27 | Node* temp = root; 28 | 29 | for (char w : word) { 30 | if (temp->mp.count(w) == 0) { 31 | Node* n = new Node(w); 32 | temp->mp[w] = n; 33 | } 34 | temp = temp->mp[w]; 35 | } 36 | 37 | temp-> isTerminal = true; 38 | } 39 | 40 | bool check(string word) { 41 | Node *temp = root; 42 | for (char w : word) { 43 | if (temp->mp.count(w)) { 44 | temp = temp->mp[w]; 45 | if (!temp->isTerminal) return false; 46 | } 47 | else return false; 48 | } 49 | return true; 50 | } 51 | 52 | string completeString(int n, vector &a) { 53 | for (string word : a) insert(word); 54 | 55 | string res = ""; 56 | 57 | for (string word : a) { 58 | if (check(word)) { 59 | if (word.size() > res.size()) res = word; 60 | else if (word.size() == res.size() and word < res) res = word; 61 | } 62 | } 63 | if (res == "") return "None"; 64 | return res; 65 | } 66 | }; 67 | 68 | 69 | int main() { 70 | vector words = {"ab", "bc"}; 71 | Trie t; 72 | cout << t.completeString(2, words); 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /Tries/countDistinctSubstrings_CN.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | char data; 7 | unordered_map mp; 8 | 9 | Node(char d) { 10 | data = d; 11 | } 12 | }; 13 | 14 | int countDistinctSubstrings(string word) { 15 | Node* root = new Node('\0'); 16 | int cnt = 0; 17 | for (int i = 0; i < word.size(); i++) { 18 | Node* temp = root; 19 | for (int j = i; j < word.size(); j++) { 20 | if (temp->mp.count(word[j]) == 0) { 21 | Node* n = new Node(word[j]); 22 | temp->mp[word[j]] = n; 23 | cnt++; 24 | } 25 | temp = temp->mp[word[j]]; 26 | } 27 | } 28 | return cnt + 1; 29 | } 30 | -------------------------------------------------------------------------------- /Tries/prefixTrie.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | char data; 9 | unordered_map m; 10 | bool isTerminal; 11 | 12 | node(int d) 13 | { 14 | data = d; 15 | isTerminal = false; 16 | } 17 | }; 18 | 19 | class Trie 20 | { 21 | node *root; 22 | 23 | public: 24 | Trie() 25 | { 26 | root = new node('\0'); 27 | } 28 | 29 | void insert(string word) 30 | { 31 | node *temp = root; 32 | 33 | for (char ch : word) 34 | { 35 | if (temp->m.count(ch) == 0) 36 | { 37 | node *n = new node(ch); 38 | temp->m[ch] = n; 39 | } 40 | temp = temp->m[ch]; 41 | } 42 | temp->isTerminal = true; 43 | } 44 | 45 | bool search(string word) 46 | { 47 | node *temp = root; 48 | 49 | for (char ch : word) 50 | { 51 | if (temp->m.count(ch) == 0) 52 | { 53 | return false; 54 | } 55 | temp = temp->m[ch]; 56 | } 57 | 58 | return temp->isTerminal; 59 | } 60 | }; 61 | 62 | int main() 63 | { 64 | string words[] = {"apple", "ape", "no", "news", "not", "never"}; 65 | Trie t; 66 | 67 | for (auto w : words) 68 | { 69 | t.insert(w); 70 | } 71 | 72 | int q; 73 | cin >> q; 74 | 75 | string searchWord; 76 | while (q--) 77 | { 78 | cin >> searchWord; 79 | if (t.search(searchWord)) 80 | cout << "Yes" << endl; 81 | else 82 | cout << "No" << endl; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Tries/suffixTrie.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | char data; 9 | unordered_map m; 10 | bool isTerminal; 11 | 12 | node(int d) 13 | { 14 | data = d; 15 | isTerminal = false; 16 | } 17 | }; 18 | 19 | class SuffixTrie 20 | { 21 | node *root; 22 | 23 | public: 24 | SuffixTrie() 25 | { 26 | root = new node('\0'); 27 | } 28 | 29 | void insert_helper(string word) 30 | { 31 | node *temp = root; 32 | 33 | for (char ch : word) 34 | { 35 | if (temp->m.count(ch) == 0) 36 | { 37 | node *n = new node(ch); 38 | temp->m[ch] = n; 39 | } 40 | temp = temp->m[ch]; 41 | } 42 | temp->isTerminal = true; 43 | } 44 | 45 | bool search(string word) 46 | { 47 | node *temp = root; 48 | 49 | for (char ch : word) 50 | { 51 | if (temp->m.count(ch) == 0) 52 | { 53 | return false; 54 | } 55 | temp = temp->m[ch]; 56 | } 57 | 58 | return temp->isTerminal; 59 | } 60 | 61 | void insert(string word) { 62 | // pick all substrings from idx i till end of string and call insert_helper 63 | for (int i = 0; word[i] != NULL; i++) { 64 | insert_helper(word.substr(i)); 65 | } 66 | } 67 | }; 68 | 69 | int main() 70 | { 71 | string input = "hello"; 72 | string suffixes[] = {"lo", "ell", "hello"}; 73 | 74 | SuffixTrie t; 75 | t.insert(input); 76 | 77 | for (auto sf : suffixes) 78 | { 79 | if (t.search(sf)) 80 | cout << "Yes" << " "; 81 | else 82 | cout << "No" << " "; 83 | 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /Tries/trie_implement1_leetcode.cpp: -------------------------------------------------------------------------------- 1 | class Node { 2 | public: 3 | char data; 4 | unordered_map mp; 5 | bool isTerminal; 6 | 7 | Node(char d) { 8 | data = d; 9 | isTerminal = false; 10 | } 11 | }; 12 | 13 | class Trie { 14 | public: 15 | 16 | Node* root; 17 | 18 | Trie() { 19 | root = new Node('\0'); 20 | } 21 | 22 | 23 | void insert(string word) { 24 | 25 | Node* temp = root; 26 | for (char w : word) { 27 | if (!temp->mp.count(w)) { 28 | Node* n = new Node(w); 29 | temp->mp[w] = n; 30 | } 31 | 32 | temp = temp->mp[w]; 33 | } 34 | 35 | temp->isTerminal = true; 36 | } 37 | 38 | bool search(string word) { 39 | Node* temp = root; 40 | 41 | for (char w : word) { 42 | if (!temp->mp.count(w)) return false; 43 | 44 | temp = temp->mp[w]; 45 | } 46 | 47 | return temp->isTerminal; 48 | } 49 | 50 | bool startsWith(string prefix) { 51 | Node* temp = root; 52 | 53 | for (char w : prefix) { 54 | if (!temp->mp.count(w)) return false; 55 | 56 | temp = temp->mp[w]; 57 | } 58 | 59 | return true; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /binaryTreeCreation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node { 5 | public: 6 | int data; 7 | node* left; 8 | node* right; 9 | 10 | node(int data) { 11 | this->data = data; 12 | left = NULL; 13 | right = NULL; 14 | } 15 | }; 16 | 17 | node *buildTree() { 18 | int d; 19 | cin >> d; 20 | 21 | if (d == -1) 22 | return NULL; 23 | 24 | node *root = new node(d); 25 | root->left = buildTree(); 26 | root->right = buildTree(); 27 | return root; 28 | } 29 | 30 | void print(node* root) { 31 | if (!root) return; 32 | 33 | cout << root->data << endl; 34 | 35 | print(root->left); 36 | 37 | print(root->right); 38 | } 39 | 40 | int main() { 41 | node* root = buildTree(); 42 | print(root); 43 | } 44 | -------------------------------------------------------------------------------- /interv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/proghead00/Interview-Competitive-Cpp/9e6a98a59a901aa65187afae559d57070409039b/interv.png -------------------------------------------------------------------------------- /jdbc steps.txt: -------------------------------------------------------------------------------- 1 | 1. oracle 21xe 2 | 2. jdk (latest) 3 | 3. ojdbc 4 | 4. PATHS: 5 | USER VAR: 6 | 1. CLASSPATH --> C:\Users\Asus\Downloads\ojdbc11.jar;.; 7 | 2. Path: New --> C:\Program Files\Java\jdk-18.0.2\bin 8 | 9 | 3. SYS VAR: 10 | JAVA_HOME --> C:\Program Files\Java\jdk-18.0.2 11 | 12 | 5. check.java --> javac check.java --> java check ||| sqlplus create and stuff -------------------------------------------------------------------------------- /longestCommonSUBSTRING.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int help(string &s1, string &s2, int n, int m, vector> &dp) { 4 | 5 | if (dp[n][m] != -1) return dp[n][m]; 6 | 7 | if (n == 0 or m = 0) return dp[n][m] = 0; 8 | 9 | if (s1[n - 1] == s2[m - 1]) dp[n][m] = 1 + help(s1, s2, n - 1, m - 1, dp); 10 | 11 | else dp[n][m] = 0; 12 | 13 | help(s1, s2, n - 1, m, dp); 14 | help(s1, s2, n, m - 1, dp); 15 | 16 | return dp[n][m]; 17 | } 18 | 19 | int longestCommonSubsequence(string s1, string s2) { 20 | int n = s1.size(); 21 | int m = s2.size(); 22 | 23 | vector> dp(n + 1, vector(m + 1, -1)); 24 | help(s1, s2, n, m, dp); 25 | 26 | int mx = 0; 27 | for (auto i : dp) 28 | for (auto j : i) 29 | mx = max(mx, j); 30 | 31 | return mx; 32 | 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /quickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int partition(vector &v, int l, int h) { 5 | 6 | int pivot = v[h]; 7 | int i = l; 8 | 9 | for (int j = l; j < h; j++) { 10 | if (v[j] < pivot) { 11 | swap(v[i], v[j]); 12 | i++; 13 | } 14 | } 15 | 16 | swap(v[i], v[h]); 17 | return i; 18 | } 19 | 20 | void quick(vector &v, int l, int h) { 21 | 22 | if (l >= h) return; 23 | 24 | int pv = partition(v, l, h); 25 | 26 | quick(v, l, pv - 1); 27 | quick(v, pv + 1, h); 28 | } 29 | 30 | int main() { 31 | vector v = {4, 2, 5, 12, 1, 67, 6, 312, 0}; 32 | quick(v, 0, v.size() - 1); 33 | 34 | for (auto x : v) cout << x << " "; 35 | 36 | } 37 | --------------------------------------------------------------------------------