From 23de3d36aa5f9a0a8d1ee5c26a12cae97d40a983 Mon Sep 17 00:00:00 2001 From: tarunpratap9754 Date: Tue, 19 Jun 2018 14:09:39 +0530 Subject: [PATCH 01/59] Update ConstructBinaryTreeFromInorderAndPreorder.cpp Passing the inorder array by reference to cut down the TLE problem ! --- Trees/ConstructBinaryTreeFromInorderAndPreorder.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Trees/ConstructBinaryTreeFromInorderAndPreorder.cpp b/Trees/ConstructBinaryTreeFromInorderAndPreorder.cpp index 1076071..007d778 100644 --- a/Trees/ConstructBinaryTreeFromInorderAndPreorder.cpp +++ b/Trees/ConstructBinaryTreeFromInorderAndPreorder.cpp @@ -7,10 +7,10 @@ * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ -int index(vector v, int val, int start, int end){ +int index(vector &inorder, int val, int start, int end){ int i; for(i = start; i <= end; i++){ - if(v[i] == val){ + if(inorder[i] == val){ return i; } } From f967f45b3f0da9ff44a397903141171abac2701f Mon Sep 17 00:00:00 2001 From: Hardik Date: Thu, 5 Jul 2018 16:15:49 +0200 Subject: [PATCH 02/59] largest area of rectangle with permutations added --- ...LargestAreaOfRectangleWithPermutations.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 DynamicProgramming/LargestAreaOfRectangleWithPermutations.cpp diff --git a/DynamicProgramming/LargestAreaOfRectangleWithPermutations.cpp b/DynamicProgramming/LargestAreaOfRectangleWithPermutations.cpp new file mode 100644 index 0000000..2144aca --- /dev/null +++ b/DynamicProgramming/LargestAreaOfRectangleWithPermutations.cpp @@ -0,0 +1,47 @@ +int Solution::solve(vector > &A) { + + int hist[A.size()+1][A[0].size()+1]; + + for (int i=0; i=0; j--) + { + if (count[j] > 0) + { + for (int k=0; k max_area) + max_area = curr_area; + } + } + return max_area; +} From 1eacd5fec634070e30fdda014a4ff421cce4eff5 Mon Sep 17 00:00:00 2001 From: Hardik Rana Date: Wed, 18 Jul 2018 09:20:01 +0200 Subject: [PATCH 03/59] MinStepsinInfiniteGrid --- Arrays/MinStepsInInfiniteGrid.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Arrays/MinStepsInInfiniteGrid.cpp b/Arrays/MinStepsInInfiniteGrid.cpp index e4932a0..26e5db0 100644 --- a/Arrays/MinStepsInInfiniteGrid.cpp +++ b/Arrays/MinStepsInInfiniteGrid.cpp @@ -1,6 +1,7 @@ // https://www.interviewbit.com/problems/min-steps-in-infinite-grid/ // Input : X and Y co-ordinates of the points in order. // Each point is represented by (X[i], Y[i]) +/* int Solution::coverPoints(vector &X, vector &Y) { int steps = 0, dx, dy, i = 0; @@ -38,3 +39,18 @@ int Solution::coverPoints(vector &X, vector &Y) { return steps; } +*/ + +int coverPoints(vector &X, vector &Y) { + + int size1=X.size(),size2=Y.size(),ans=0; + + for(int i=1;i Date: Fri, 20 Jul 2018 13:06:59 +0530 Subject: [PATCH 04/59] Update MinStepsInInfiniteGrid.cpp --- Arrays/MinStepsInInfiniteGrid.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Arrays/MinStepsInInfiniteGrid.cpp b/Arrays/MinStepsInInfiniteGrid.cpp index 26e5db0..0d227f0 100644 --- a/Arrays/MinStepsInInfiniteGrid.cpp +++ b/Arrays/MinStepsInInfiniteGrid.cpp @@ -1,6 +1,8 @@ // https://www.interviewbit.com/problems/min-steps-in-infinite-grid/ // Input : X and Y co-ordinates of the points in order. // Each point is represented by (X[i], Y[i]) + +// Explanatory code /* int Solution::coverPoints(vector &X, vector &Y) { @@ -41,6 +43,7 @@ int Solution::coverPoints(vector &X, vector &Y) { } */ +// Concise code int coverPoints(vector &X, vector &Y) { int size1=X.size(),size2=Y.size(),ans=0; From b29683a7a2c5c5d077c9b620ffcbd2b53a1b8012 Mon Sep 17 00:00:00 2001 From: Hardik Rana Date: Mon, 23 Jul 2018 05:59:11 +0200 Subject: [PATCH 05/59] Scramble string added --- DynamicProgramming/Scramble String.cpp | 41 ++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 DynamicProgramming/Scramble String.cpp diff --git a/DynamicProgramming/Scramble String.cpp b/DynamicProgramming/Scramble String.cpp new file mode 100644 index 0000000..157a4c9 --- /dev/null +++ b/DynamicProgramming/Scramble String.cpp @@ -0,0 +1,41 @@ +int Solution::isScramble(string A, string B) +{ + + int length1 = A.length(); + //int length2 = B.length(); + + if(length1 != B.length()) + return false; + if(A == B) + return true; + + bool scrambled[length1][length1][length1]; + for (int i=0; i < length1; ++i) + { + for (int j=0; j < length1; ++j) + { + scrambled[i][j][0] = (A[i] == B[j]); + } + } + + for (int k=1; k < length1; ++k) + { + for (int i=0; i < length1 - k; ++i) + { + for (int j=0; j < length1 - k; ++j) + { + scrambled[i][j][k] = false; + for (int p=0; p < k; ++p) + { + if ((scrambled[i][j][p] && scrambled[i+p+1][j+p+1][k-p-1]) + || (scrambled[i][j+k-p][p] && scrambled[i+p+1][j][k-p-1])) { + scrambled[i][j][k] = true; + break; + } + } + } + } + } + + return scrambled[0][0][length1-1]; + } From ec9c172284003cdfd07d8a031561340746b88a99 Mon Sep 17 00:00:00 2001 From: Santosh Kumar Date: Mon, 30 Jul 2018 01:14:06 +0530 Subject: [PATCH 06/59] Trees - Hotel Reviews Solution --- Trees/HotelReviews.cpp | 107 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 Trees/HotelReviews.cpp diff --git a/Trees/HotelReviews.cpp b/Trees/HotelReviews.cpp new file mode 100644 index 0000000..2820e5e --- /dev/null +++ b/Trees/HotelReviews.cpp @@ -0,0 +1,107 @@ +// https://www.interviewbit.com/problems/hotel-reviews/ + +struct TrieNode{ + unordered_map children; + bool is_word; + TrieNode(bool x) : is_word(x) {} +}; + +struct ResNode{ + int index; + int val; +}; + +bool myfunction (ResNode i,ResNode j) { + bool ret = 0; + if(i.val>j.val){ + ret=1; + } + else if(i.val==j.val){ + if(i.index::iterator it = (current->children).find(good_words[i]); + if(it != (current->children).end()){ + current = it->second; + } + else{ + TrieNode* B = new TrieNode(0); + (current->children)[good_words[i]] = B; + current=B; + } + if(i==good_words.length()-1 || good_words[i+1]=='_'){ + current->is_word = 1; + } + } + } +} + +int solveReview(TrieNode* A, string review){ + int result = 0; + review = review+"_"; + vector arr; + int start = 0; + for(int i=0; i::iterator it = (current->children).find(arr[i][j]); + if(it != (current->children).end()){ + current = it->second; + } + else{ + break; + } + if(j==arr[i].length()-1){ + if(current->is_word == 1){ + result++; + } + } + } + } + return result; +} + +vector Solution::solve(string good_words, vector &reviews) { + // Do not write main() function. + // Do not read input, instead use the arguments to the function. + // Do not print the output, instead return values as specified + // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details + + vector result; + vector temp_res; + TrieNode* A = new TrieNode(0); + construct_trie(good_words, A); + + for(int i=0; i Date: Wed, 1 Aug 2018 00:41:46 +0530 Subject: [PATCH 07/59] Updated BinaryTreeFromInorderAndPostorder.cpp --- Trees/BinaryTreeFromInorderAndPostorder.cpp | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Trees/BinaryTreeFromInorderAndPostorder.cpp diff --git a/Trees/BinaryTreeFromInorderAndPostorder.cpp b/Trees/BinaryTreeFromInorderAndPostorder.cpp new file mode 100644 index 0000000..743e93b --- /dev/null +++ b/Trees/BinaryTreeFromInorderAndPostorder.cpp @@ -0,0 +1,37 @@ +/** + * Definition for binary tree + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +int search(vector &in, int str, int end, int val){ + for(int k=str; k<=end; k++) + if(in[k] == val) + return k; +} + +TreeNode* getTre(vector &post, vector &in, int start, int end, int &treeIndex){ + + if(start > end) + return NULL; + + TreeNode* node = new TreeNode(post[treeIndex--]); + + if(start == end) + return node; + + int root = search(in, start, end, node->val); + + node->right = getTre(post, in, root+1, end, treeIndex); + node->left = getTre(post, in, start, root-1, treeIndex); + + return node; +} + +TreeNode* Solution::buildTree(vector &in, vector &post) { + int treeIndex = in.size()-1; + return getTre(post, in, 0, in.size()-1, treeIndex); +} From fb8c92f2fac162954d801cf64b1da56f935ce9ad Mon Sep 17 00:00:00 2001 From: DEEP SHEKHAR Date: Sat, 22 Sep 2018 00:29:18 +0530 Subject: [PATCH 08/59] Added solution for simplify-directory-path(stacks) --- Stacks-and-Queues/Simplify Directory Path.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Stacks-and-Queues/Simplify Directory Path.cpp diff --git a/Stacks-and-Queues/Simplify Directory Path.cpp b/Stacks-and-Queues/Simplify Directory Path.cpp new file mode 100644 index 0000000..4246dae --- /dev/null +++ b/Stacks-and-Queues/Simplify Directory Path.cpp @@ -0,0 +1,36 @@ +//https://www.interviewbit.com/problems/simplify-directory-path/ + +string Solution::simplifyPath(string A) { + stack st; + + int len = A.length(); + + for(int i=0;i Date: Tue, 9 Oct 2018 00:55:31 +0530 Subject: [PATCH 09/59] Microsoft Amazon --- Bit-Manipulation/DivideInteger.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Bit-Manipulation/DivideInteger.cpp diff --git a/Bit-Manipulation/DivideInteger.cpp b/Bit-Manipulation/DivideInteger.cpp new file mode 100644 index 0000000..cc842e0 --- /dev/null +++ b/Bit-Manipulation/DivideInteger.cpp @@ -0,0 +1,18 @@ +int Solution::divide(int a, int b) { + if(a==0) + return 0; + if(b==0) + return (INT_MAX); + int sign=1; + //remove sign of operands + int t=0,q=0; + a=abs(a); + b=abs(b); + for(int i=31;i>=0;--i){ + if(t+(b<=INT_MAX||sign*q Date: Sat, 13 Oct 2018 23:21:51 +0530 Subject: [PATCH 10/59] Added knight on a chessboard --- Graphs/knightOnAChess.cpp | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Graphs/knightOnAChess.cpp diff --git a/Graphs/knightOnAChess.cpp b/Graphs/knightOnAChess.cpp new file mode 100644 index 0000000..b97ce52 --- /dev/null +++ b/Graphs/knightOnAChess.cpp @@ -0,0 +1,40 @@ +vector x ({1, 2, 2, 1, -1, -2, -1, -2}); +vector y ({2, 1, -1, -2, 2, 1, -2, -1}); + +bool isSafe(int i , int j ,int N, int M){ + if(i >= 0 && i < N && j >= 0 && j < M)return true; + + return false; +} + +int explore(queue > >& q, int A, int B, int C, int D, int E, int F, vector >& visited, int &count){ + while(!q.empty()){ + int distance = q.front().first; + int c = q.front().second.first; + int d = q.front().second.second; + q.pop(); + if ( c == E && d == F)return distance; + visited[c][d] = 1; + + for(int i = 0; i < x.size(); i++){ + int first = c + x[i]; + int second = d + y[i]; + if(isSafe(first, second, A, B)){ + if(visited[first][second] == 0){ + visited[first][second] = 1; + q.push({distance+1, {first, second}}); + } + } + } + } + return -1; +} + +int Solution::knight(int A, int B, int C, int D, int E, int F) { + vector > visited (A, vector (B, 0)); + + int count = 0; + queue > > q; + q.push({0, {C-1, D-1}}); + return explore(q, A, B, C-1, D-1, E-1, F-1, visited, count); +} From ade04f1d60618de2a3829c36cc457debe87b1562 Mon Sep 17 00:00:00 2001 From: Sahil Date: Sun, 14 Oct 2018 16:32:06 +0530 Subject: [PATCH 11/59] Facebook, Google --- Graphs/LargestDistanceBetweenNodesOfATree.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Graphs/LargestDistanceBetweenNodesOfATree.cpp diff --git a/Graphs/LargestDistanceBetweenNodesOfATree.cpp b/Graphs/LargestDistanceBetweenNodesOfATree.cpp new file mode 100644 index 0000000..9dd1ecd --- /dev/null +++ b/Graphs/LargestDistanceBetweenNodesOfATree.cpp @@ -0,0 +1,58 @@ +pair process(queue >& q, vector& visited, unordered_map >& x){ + // Typical BFS with keeping track of the longest distance and farthest element. + int maxi = INT_MIN, farthest = 0; + while(!q.empty()){ + int node = q.front().first; + int distance = q.front().second; + q.pop(); + if(distance > maxi){ + maxi = distance; + farthest = node; + } + visited[node] = 1; + for(int i = 0; i < x[node].size(); i++){ + if(!visited[x[node][i]]){ + visited[x[node][i]] = 1; + q.push({x[node][i], distance+1}); + } + } + } + return {maxi, farthest}; +} + +int Solution::solve(vector &A) { + // Base Case + if(A.size() <= 1)return 0; + + // Visited array to keep track of visited elements + vector visited(A.size(), 0); + + // Map to make the graph from given array + unordered_map > x; + x.clear(); + + for(int i = 0; i < A.size(); i++){ + // If the value is -1, it doesn't have any parent. + // Make the pairs in the adj. list type map + if( A[i] != -1){ + x[A[i]].push_back(i); + x[i].push_back(A[i]); + } + } + + // Start from the first element in the array and mark it visited. + queue > q; + q.push({0, 0}); + visited[0] = 1; + + // Gets the farthest element from the first element + int farthest = process(q, visited, x).second; + + vector vis(A.size(), 0); + + // Now apply BFS on the farthest element found and return the distance + // of the farthest element found so far. + q.push({farthest, 0}); + vis[farthest] = 1; + return process(q, vis, x).first; +} From ed1355a56f6bd0c39f8bd180d34a2a5a9f386300 Mon Sep 17 00:00:00 2001 From: CodeLogist <33797980+CodeLogist@users.noreply.github.com> Date: Sun, 14 Oct 2018 20:45:50 +0530 Subject: [PATCH 12/59] FibSUM.cpp This one is with Better Space and Time complexity with not extra variable space or Vector. Please have a Look --- Graphs/SumOfFibonacciNumbers.cpp | 59 +++++++++++++------------------- 1 file changed, 23 insertions(+), 36 deletions(-) diff --git a/Graphs/SumOfFibonacciNumbers.cpp b/Graphs/SumOfFibonacciNumbers.cpp index c81ba11..a4ad59a 100644 --- a/Graphs/SumOfFibonacciNumbers.cpp +++ b/Graphs/SumOfFibonacciNumbers.cpp @@ -1,39 +1,26 @@ -// https://www.interviewbit.com/problems/sum-of-fibonacci-numbers/ +#include -int Solution::fibsum(int A) { - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details - - vector vec; - - vec.push_back(1); - vec.push_back(1); - - int fib, i = 2; - - while(fib <= A){ - fib = vec[i-2] + vec[i-1]; - vec.push_back(fib); - i++; - } - - int j = vec.size()-1; - int sol = 0; - - LOOP:while(A && j >= 0){ - if(vec[j] == A){ - sol++; - return sol; - } - else if(vec[j] < A){ - sol++; - A = A - vec[j]; - goto LOOP; - } - j--; - } - + +int main()// main fibonacci program +{ + int fib1 = 0; + int fib2 = 1; + int fib3 = 0; + int c; + int sum=0; + //decalare all variables + std::cout << "How many fibonacci numbers do you want to sum?" << std::endl; + std::cin >> c; + //get user input and print the first "0" and "1" + std::cout << fib1 << std::endl;; + std::cout << fib2 << std::endl; + for (int i = 0; i < c; i++)// Looping though the fibonacci algorithm + { + fib3 = fib1 + fib2; + sum += fib3; + fib1 = fib2; + fib2 = fib3; + } + std::cout< Date: Sun, 14 Oct 2018 22:41:59 +0530 Subject: [PATCH 13/59] made as per problem in interview-bit This may Be Easier for the People to understand and implement with same complexity of yours --- Graphs/SumOfFibonacciNumbers.cpp | 43 +++++++++++++------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/Graphs/SumOfFibonacciNumbers.cpp b/Graphs/SumOfFibonacciNumbers.cpp index a4ad59a..cbea68f 100644 --- a/Graphs/SumOfFibonacciNumbers.cpp +++ b/Graphs/SumOfFibonacciNumbers.cpp @@ -1,26 +1,19 @@ -#include - - -int main()// main fibonacci program -{ - int fib1 = 0; - int fib2 = 1; - int fib3 = 0; - int c; - int sum=0; - //decalare all variables - std::cout << "How many fibonacci numbers do you want to sum?" << std::endl; - std::cin >> c; - //get user input and print the first "0" and "1" - std::cout << fib1 << std::endl;; - std::cout << fib2 << std::endl; - for (int i = 0; i < c; i++)// Looping though the fibonacci algorithm - { - fib3 = fib1 + fib2; - sum += fib3; - fib1 = fib2; - fib2 = fib3; - } - std::cout< fib; + fib.push_back(1);fib.push_back(1); // now u have 1 and 1 at v[0] and v[1] + for(int i=2;fib[i-1]0){ + while(fib[size]>n){ // find the largest fibonaci number less tahn n + size--; + } // now decraese the largest fibonaici number from n + n=n-fib[size]; + ans++; + } + return ans; } From 327d448bf79015131419cdc69c6c68f314586d8a Mon Sep 17 00:00:00 2001 From: Sahil Date: Mon, 15 Oct 2018 02:35:44 +0530 Subject: [PATCH 14/59] Create WordSearchBoard.cpp --- Graphs/WordSearchBoard.cpp | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Graphs/WordSearchBoard.cpp diff --git a/Graphs/WordSearchBoard.cpp b/Graphs/WordSearchBoard.cpp new file mode 100644 index 0000000..88df2b3 --- /dev/null +++ b/Graphs/WordSearchBoard.cpp @@ -0,0 +1,49 @@ +vector x({0, 1, -1, 0}); +vector y({1, 0, 0, -1}); + +// Check if the coordinates are safe to visit +bool isSafe(int a, int b, int c, int d){ + if(a >= 0 && a < c && b >= 0 && b < d)return true; + return false; +} + + +void explore(bool& pivot, int val, int a, int b, vector& A, string B){ + // If reached on the last index of the string, + // it means we have found the reqd. string and + // so we return + if(val == B.size()-1){ + pivot = true; + return; + } + + for(int i = 0; i < x.size(); i++){ + int first = a + x[i]; + int second = b + y[i]; + + // Explore the adjacent node only if its value is the next index in the + // given string + if(isSafe(first, second, A.size(), A[0].size()) && A[first][second] == B[val+1]){ + explore(pivot, val+1, first, second, A, B); + // To reduce time limit. + if(pivot == true)return; + } + } + +} + +int Solution::exist(vector &A, string B) { + int l = A.size(), m = A[0].size(); + if(l == 0)return 0; + + bool pivot = false; + for(int i = 0; i < l; i++){ + for(int k = 0; k < m; k++){ + if(A[i][k] == B[0]){ + explore(pivot, 0, i, k, A, B); + } + if(pivot)return pivot; + } + } + return pivot; +} From 5aaa11749457d39480236f1e59ef1dc7117ca3c2 Mon Sep 17 00:00:00 2001 From: CodeLogist <33797980+CodeLogist@users.noreply.github.com> Date: Mon, 15 Oct 2018 02:37:37 +0530 Subject: [PATCH 15/59] 2 typo error corrected --- Graphs/SumOfFibonacciNumbers.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Graphs/SumOfFibonacciNumbers.cpp b/Graphs/SumOfFibonacciNumbers.cpp index cbea68f..cf1dd74 100644 --- a/Graphs/SumOfFibonacciNumbers.cpp +++ b/Graphs/SumOfFibonacciNumbers.cpp @@ -9,9 +9,9 @@ int Solution::fibsum(int n) { int size=fib.size(); size--; while(n>0){ - while(fib[size]>n){ // find the largest fibonaci number less tahn n + while(fib[size]>n){ // find the largest fibonaci number < n size--; - } // now decraese the largest fibonaici number from n + } // now decraese the largest fibonaci number from n n=n-fib[size]; ans++; } From e03c8b814006885d9427e0a496dbafd59ad28d5c Mon Sep 17 00:00:00 2001 From: Sahil Date: Mon, 15 Oct 2018 11:17:07 +0530 Subject: [PATCH 16/59] Update 3SumZero.cpp Reduced code size. --- Two-Pointers/3SumZero.cpp | 146 ++++++++++++++++++++++++-------------- 1 file changed, 91 insertions(+), 55 deletions(-) diff --git a/Two-Pointers/3SumZero.cpp b/Two-Pointers/3SumZero.cpp index 63cc4eb..a4d019d 100644 --- a/Two-Pointers/3SumZero.cpp +++ b/Two-Pointers/3SumZero.cpp @@ -1,70 +1,106 @@ -// https://www.interviewbit.com/problems/3-sum-zero/ - vector > Solution::threeSum(vector &A) { - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details + vector > v; + + if(A.size() == 0)return v; - vector > sol; + vector > v1(A.size()); - if(A.size() < 2){ - return sol; + for(int i = 0; i < A.size(); i++){ + v1[i] = {A[i], i}; } - sort(A.begin(), A.end()); + sort(v1.begin(), v1.end()); - int i = 0; + set > mp; - while(i < A.size()-2){ + for(int i = 0; i < A.size(); i++){ + int firset = v1[i].first; int j = i+1; int k = A.size()-1; - LOOP:while(j < k){ - int sum = A[i] + A[j] + A[k]; - if(sum == 0){ - vector temp; - temp.push_back(A[i]); - temp.push_back(A[j]); - temp.push_back(A[k]); - sol.push_back(temp); - temp.erase(temp.begin(),temp.end()); - while(A[j] == A[j+1]){ - j++; - if(j == A.size()){ - break; - } - } - j++; - } - else if(sum > 0){ - while(A[k] == A[k-1]){ - k--; - if(k == 0){ - break; - } - } - k--; - } - else{ - while(A[j] == A[j+1]){ - j++; - if(j == A.size()){ - break; - } + while(j < k){ + if(v1[j].first + v1[k].first + firset == 0){ + vector v2({A[v1[i].second], A[v1[j].second], A[v1[k].second]}); + sort(v2.begin(), v2.end()); + if(mp.find(v2) == mp.end()){ + v.push_back(v2); + mp.insert(v2); } + j++; k--; + }else if(v1[j].first + v1[k].first + firset < 0){ j++; - } - - } - while(A[i+1] == A[i]){ - i++; - if(i == A.size()-1){ - return sol; - } + }else k--; } - i++; } + return v; +} + +// // https://www.interviewbit.com/problems/3-sum-zero/ + +// vector > Solution::threeSum(vector &A) { +// // Do not write main() function. +// // Do not read input, instead use the arguments to the function. +// // Do not print the output, instead return values as specified +// // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details - return sol; +// vector > sol; -} +// if(A.size() < 2){ +// return sol; +// } + +// sort(A.begin(), A.end()); + +// int i = 0; + +// while(i < A.size()-2){ +// int j = i+1; +// int k = A.size()-1; +// LOOP:while(j < k){ +// int sum = A[i] + A[j] + A[k]; +// if(sum == 0){ +// vector temp; +// temp.push_back(A[i]); +// temp.push_back(A[j]); +// temp.push_back(A[k]); +// sol.push_back(temp); +// temp.erase(temp.begin(),temp.end()); +// while(A[j] == A[j+1]){ +// j++; +// if(j == A.size()){ +// break; +// } +// } +// j++; +// } +// else if(sum > 0){ +// while(A[k] == A[k-1]){ +// k--; +// if(k == 0){ +// break; +// } +// } +// k--; +// } +// else{ +// while(A[j] == A[j+1]){ +// j++; +// if(j == A.size()){ +// break; +// } +// } +// j++; +// } + +// } +// while(A[i+1] == A[i]){ +// i++; +// if(i == A.size()-1){ +// return sol; +// } +// } +// i++; +// } + +// return sol; + +// } From 1f372373188f188448585cdb18570c2cbc4474bb Mon Sep 17 00:00:00 2001 From: Sahil Date: Fri, 19 Oct 2018 00:53:17 +0530 Subject: [PATCH 17/59] Commented the previous solution. --- Graphs/SumOfFibonacciNumbers.cpp | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Graphs/SumOfFibonacciNumbers.cpp b/Graphs/SumOfFibonacciNumbers.cpp index cf1dd74..c50a11b 100644 --- a/Graphs/SumOfFibonacciNumbers.cpp +++ b/Graphs/SumOfFibonacciNumbers.cpp @@ -1,3 +1,5 @@ +// https://www.interviewbit.com/problems/sum-of-fibonacci-numbers/ + int Solution::fibsum(int n) { vector fib; fib.push_back(1);fib.push_back(1); // now u have 1 and 1 at v[0] and v[1] @@ -17,3 +19,43 @@ int Solution::fibsum(int n) { } return ans; } + + + +// int Solution::fibsum(int A) { +// // Do not write main() function. +// // Do not read input, instead use the arguments to the function. +// // Do not print the output, instead return values as specified +// // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details + +// vector vec; + +// vec.push_back(1); +// vec.push_back(1); + +// int fib, i = 2; + +// while(fib <= A){ +// fib = vec[i-2] + vec[i-1]; +// vec.push_back(fib); +// i++; +// } + +// int j = vec.size()-1; +// int sol = 0; + +// LOOP:while(A && j >= 0){ +// if(vec[j] == A){ +// sol++; +// return sol; +// } +// else if(vec[j] < A){ +// sol++; +// A = A - vec[j]; +// goto LOOP; +// } +// j--; +// } + +// return 0; +// } From dced939f2c62e2b9707169b67e2abe629bf9c42b Mon Sep 17 00:00:00 2001 From: Sahil Date: Fri, 19 Oct 2018 03:34:34 +0530 Subject: [PATCH 18/59] Update 2-SumBinaryTree.cpp Added another solution with small variation. --- Trees/2-SumBinaryTree.cpp | 86 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/Trees/2-SumBinaryTree.cpp b/Trees/2-SumBinaryTree.cpp index 35fc495..615226b 100644 --- a/Trees/2-SumBinaryTree.cpp +++ b/Trees/2-SumBinaryTree.cpp @@ -78,3 +78,89 @@ int Solution::t2Sum(TreeNode* A, int B) { return 0; } + +/* +Another method if you are unable to get above method, although both of them work the same. +*/ + + +// bool isPairPresent(int K, TreeNode* A, TreeNode* B, stack s1, stack s2){ +// // Base Case +// if(!A)return 0; + +// // Go to the extreme left +// while(A){ +// s1.push(A); +// A = A ->left; +// } +// // Go to the extreme right +// while(B){ +// s2.push(B); +// B = B->right; +// } + +// Get the lowest and highest elements. +// A = s1.top(); s1.pop(); +// B = s2.top(); s2.pop(); + +// // Make the extremes as lowest and highest values (coz BST) +// int low = A->val, high = B->val; +// bool b1 = true; +// bool b2 = true; +// // While we don't cross the two pointers +// while(low < high){ +// // Return if we have found the sum +// if(low + high == K)return 1; +// // If the sum is less, increase the lower pointer only. +// if(low + high < K){ +// b2 = false; +// b1 = true; +// } +// // Else decrement the higher pointer only. +// else { +// b2 = true; +// b1 = false; +// } +// if(b1){ +// // If the pointer is not NULL, take it to the extreme left +// // of its right child +// if(A){ +// A = A->right; +// while(A){ +// s1.push(A); +// A = A->left; +// } +// } +// // Else just pop the top of the stack and make it as the lowest pointer. +// else { +// A = s1.top(); +// s1.pop(); +// low = A->val; +// } +// } +// // Same as above. +// else if(b2){ + +// if(B){ +// B = B->left; +// while(B){ +// s2.push(B); +// B = B->right; +// } +// }else { +// B = s2.top(); +// s2.pop(); +// high = B->val; +// } +// } +// } +// return 0; +// } + +// int Solution::t2Sum(TreeNode* A, int B) { +// stack s1, s2; + +// TreeNode *head1 = A, *head2 = A; + +// return isPairPresent(B, head1, head2, s1, s2); +// } From 14d700b0da1c321e7f0790a6b81e00fb2ac48662 Mon Sep 17 00:00:00 2001 From: Sahil Date: Fri, 26 Oct 2018 02:02:36 +0530 Subject: [PATCH 19/59] Added solution with less code. --- Arrays/MaxDistance.cpp | 107 ++++++++++++++++++++++++++++------------- 1 file changed, 73 insertions(+), 34 deletions(-) diff --git a/Arrays/MaxDistance.cpp b/Arrays/MaxDistance.cpp index d330e72..bc867f0 100644 --- a/Arrays/MaxDistance.cpp +++ b/Arrays/MaxDistance.cpp @@ -1,41 +1,80 @@ // https://www.interviewbit.com/problems/max-distance/ + +int Solution::maximumGap(const vector &A) { + // Base case + if(A.size() <= 1)return 0; + + // Make two arrays such that one of them holds the minimum from the left + // and the other holds maximum from the right + vector v1 (A.size(), 0), v2(A.size(), 0); + + // Fill the first array with minimum from the left + v1[0] = A[0]; + for(int i = 1 ; i < A.size(); i++)v1[i] = min(v1[i-1], A[i]); + + // Fill the second array with maximum from the right + v2[A.size()-1] = A[A.size()-1]; + for(int i = A.size()-2 ; i >= 0 ; i--)v2[i] = max(v2[i+1], A[i]); + + + int i = 0, j = 0; + int ans = -1; + // While we don't traverse the complete array, check if the minimum element is indeed + // less than the maximum element in the other array, if yes, update the answer. + // Move the pointer as required. If the element in second array is greater than + // that in first array, keep moving the second pointer and update the answer + // else move the first pointer. + while(j < A.size() && i < A.size()){ + if(v2[j] >= v1[i]){ + if(j-i > ans){ + ans = j-i; + } + j = j + 1; + }else i = i + 1; + } + return ans; +} + + + + // Here we are making an array to check whether all the elements on the left of an index are smaller than it or not // If true then we are checking for greater j such that A[j] is greater than A[i]. If so then that j is greater than all i on the left // also. On finding such a j or a false in the check array, we decrement i. -int Solution::maximumGap(const vector &A) { - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details - vector tempArr(A.size()); - int min = A[0]; - int max_distance = 0; - int i = A.size()-1; - int j = A.size()-1; +// int Solution::maximumGap(const vector &A) { +// // Do not write main() function. +// // Do not read input, instead use the arguments to the function. +// // Do not print the output, instead return values as specified +// // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details +// vector tempArr(A.size()); +// int min = A[0]; +// int max_distance = 0; +// int i = A.size()-1; +// int j = A.size()-1; - for(int i = 0; i < A.size(); i++){ - if(A[i] > min){ - tempArr[i] = false; - } - else{ - min = A[i]; - tempArr[i] = true; - } - } +// for(int i = 0; i < A.size(); i++){ +// if(A[i] > min){ +// tempArr[i] = false; +// } +// else{ +// min = A[i]; +// tempArr[i] = true; +// } +// } - LOOP:while(i >= 0){ - if(tempArr[i] == false){ - i--; - goto LOOP; - } - while((A[i] > A[j]) && (j > i)){ - j--; - } - if((j-i) > max_distance){ - max_distance = j-i; - } - i--; - } - return max_distance; -} +// LOOP:while(i >= 0){ +// if(tempArr[i] == false){ +// i--; +// goto LOOP; +// } +// while((A[i] > A[j]) && (j > i)){ +// j--; +// } +// if((j-i) > max_distance){ +// max_distance = j-i; +// } +// i--; +// } +// return max_distance; +// } From 8bdc0c593501c9639a7dfb92c1cb968ad87e8a35 Mon Sep 17 00:00:00 2001 From: Gautam Khanna Date: Wed, 31 Oct 2018 18:29:06 +0530 Subject: [PATCH 20/59] Added Smallest sequence with given Primes --- Graphs/Smallest sequence with given Primes | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Graphs/Smallest sequence with given Primes diff --git a/Graphs/Smallest sequence with given Primes b/Graphs/Smallest sequence with given Primes new file mode 100644 index 0000000..befd7a6 --- /dev/null +++ b/Graphs/Smallest sequence with given Primes @@ -0,0 +1,22 @@ +vector Solution::solve(int A, int B, int C, int D) +{ + set s; + swap(A,D); + int ctr = 0; + vector ans; + s.insert(B); + s.insert(C); + s.insert(D); + while(ctr Date: Wed, 31 Oct 2018 18:41:04 +0530 Subject: [PATCH 21/59] Adding solution for Ways to form Max Heap Problem link : https://www.interviewbit.com/problems/ways-to-form-max-heap/ --- Heaps-and-Maps/Ways to form Max Heap | 48 ++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Heaps-and-Maps/Ways to form Max Heap diff --git a/Heaps-and-Maps/Ways to form Max Heap b/Heaps-and-Maps/Ways to form Max Heap new file mode 100644 index 0000000..e8d5e8d --- /dev/null +++ b/Heaps-and-Maps/Ways to form Max Heap @@ -0,0 +1,48 @@ +long long dp[105]; +long long comb[105][105]; +#define MOD 1000000007 +int rec(int n) +{ + if(n<=1) + return 1; + if(dp[n] != -1) + return dp[n]; + int i; + int fill = 0; + int pw = 2; + int left,right; + left = right = 0; + + while(fill+pw < n-1) + { + fill += pw; + left += pw/2; + right += pw/2; + pw *= 2; + } + int rem = n-1-fill; + if(rem > pw/2) + { + left += pw/2; + right += (rem-pw/2); + } + else + left += rem; + //cout<<"solve "< Date: Wed, 31 Oct 2018 18:43:27 +0530 Subject: [PATCH 22/59] Adding solution for Pretty Json Problem link : https://www.interviewbit.com/problems/pretty-json/ --- Strings/Pretty Json | 60 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Strings/Pretty Json diff --git a/Strings/Pretty Json b/Strings/Pretty Json new file mode 100644 index 0000000..ba16fca --- /dev/null +++ b/Strings/Pretty Json @@ -0,0 +1,60 @@ +vector Solution::prettyJSON(string A) +{ + int n = A.size(),i,j; + vector< string >ans; + int tbctr = 0; + i = 0; + bool flag = false; + while(i Date: Wed, 31 Oct 2018 18:50:43 +0530 Subject: [PATCH 23/59] Added solution for N Queens Problem link : https://www.interviewbit.com/problems/nqueens/ --- Backtracking/N Queens | 54 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Backtracking/N Queens diff --git a/Backtracking/N Queens b/Backtracking/N Queens new file mode 100644 index 0000000..a61de91 --- /dev/null +++ b/Backtracking/N Queens @@ -0,0 +1,54 @@ +vector >ans; +int n; + +void recur(int ind, vector pos) +{ + int i,j; + if(ind == n) + { + vector valid; + for(i=0;i > Solution::solveNQueens(int A) +{ + ans.clear(); + vector pos; + int i; + n = A; + recur(0,pos); + return ans; + // Do not write main() function. + // Do not read input, instead use the arguments to the function. + // Do not print the output, instead return values as specified + // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details +} From 5c9623f5f62bd366c4e8410298b90bcba704ab41 Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 3 Nov 2018 01:31:38 +0530 Subject: [PATCH 24/59] Update N Queens --- Backtracking/N Queens | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Backtracking/N Queens b/Backtracking/N Queens index a61de91..8164dad 100644 --- a/Backtracking/N Queens +++ b/Backtracking/N Queens @@ -47,8 +47,4 @@ vector > Solution::solveNQueens(int A) n = A; recur(0,pos); return ans; - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details } From af1bbdc1d613f47a280e42bd3c9e5eb95f70fe38 Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 3 Nov 2018 01:34:29 +0530 Subject: [PATCH 25/59] Rename N Queens to NQueens.cpp --- Backtracking/{N Queens => NQueens.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Backtracking/{N Queens => NQueens.cpp} (100%) diff --git a/Backtracking/N Queens b/Backtracking/NQueens.cpp similarity index 100% rename from Backtracking/N Queens rename to Backtracking/NQueens.cpp From bb6cd656f3865a9948ec4cc4614c3fd4f84b3786 Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 3 Nov 2018 01:36:36 +0530 Subject: [PATCH 26/59] Rename Pretty Json to PrettyJson.cpp --- Strings/{Pretty Json => PrettyJson.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Strings/{Pretty Json => PrettyJson.cpp} (100%) diff --git a/Strings/Pretty Json b/Strings/PrettyJson.cpp similarity index 100% rename from Strings/Pretty Json rename to Strings/PrettyJson.cpp From 3b55176ee3d7b5d1eeb39a2a2652bf8814f56280 Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 3 Nov 2018 01:39:01 +0530 Subject: [PATCH 27/59] Rename Smallest sequence with given Primes to SmallestSequenceWithGivenPrimes.cpp --- ...ence with given Primes => SmallestSequenceWithGivenPrimes.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graphs/{Smallest sequence with given Primes => SmallestSequenceWithGivenPrimes.cpp} (100%) diff --git a/Graphs/Smallest sequence with given Primes b/Graphs/SmallestSequenceWithGivenPrimes.cpp similarity index 100% rename from Graphs/Smallest sequence with given Primes rename to Graphs/SmallestSequenceWithGivenPrimes.cpp From 540e4f1d1d86a82b33533ec23d91da2b3487fb41 Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 3 Nov 2018 01:41:31 +0530 Subject: [PATCH 28/59] Update and rename Ways to form Max Heap to WaysToFormMaxHeap.cpp --- .../{Ways to form Max Heap => WaysToFormMaxHeap.cpp} | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) rename Heaps-and-Maps/{Ways to form Max Heap => WaysToFormMaxHeap.cpp} (92%) diff --git a/Heaps-and-Maps/Ways to form Max Heap b/Heaps-and-Maps/WaysToFormMaxHeap.cpp similarity index 92% rename from Heaps-and-Maps/Ways to form Max Heap rename to Heaps-and-Maps/WaysToFormMaxHeap.cpp index e8d5e8d..acf5370 100644 --- a/Heaps-and-Maps/Ways to form Max Heap +++ b/Heaps-and-Maps/WaysToFormMaxHeap.cpp @@ -28,9 +28,8 @@ int rec(int n) } else left += rem; - //cout<<"solve "< Date: Sat, 3 Nov 2018 10:53:41 +0530 Subject: [PATCH 29/59] Tushar'sBirthdayBombs.cpp Problem link : https://www.interviewbit.com/problems/tushars-birthday-bombs/ --- DynamicProgramming/Tushar'sBirthdayBombs.cpp | 43 ++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 DynamicProgramming/Tushar'sBirthdayBombs.cpp diff --git a/DynamicProgramming/Tushar'sBirthdayBombs.cpp b/DynamicProgramming/Tushar'sBirthdayBombs.cpp new file mode 100644 index 0000000..2d1da5f --- /dev/null +++ b/DynamicProgramming/Tushar'sBirthdayBombs.cpp @@ -0,0 +1,43 @@ +vector Solution::solve(int A, vector &B) +{ + int mn = INT_MAX; + int n = B.size(),i,j,pos; + for(i=0;i order; + for(i=0;i= 0) + { + ind = j; + rem = rem-B[j]+B[pos]; + break; + } + } + if(j == n) + break; + order[i] = j; + i++; + // pos = order.size(); + } + return order; +} From 447573a820fc789a16d255c6b027cca63263d709 Mon Sep 17 00:00:00 2001 From: Aryan Arora Date: Sun, 4 Nov 2018 00:46:12 +0530 Subject: [PATCH 30/59] A bit of cleaning. --- Trees/HotelReviews.cpp | 186 +++++++++++++++++++++-------------------- 1 file changed, 97 insertions(+), 89 deletions(-) diff --git a/Trees/HotelReviews.cpp b/Trees/HotelReviews.cpp index 2820e5e..2fbb1ba 100644 --- a/Trees/HotelReviews.cpp +++ b/Trees/HotelReviews.cpp @@ -1,107 +1,115 @@ -// https://www.interviewbit.com/problems/hotel-reviews/ - struct TrieNode{ - unordered_map children; - bool is_word; - TrieNode(bool x) : is_word(x) {} + bool isWord; + unordered_map children; + TrieNode(bool word): isWord(word) {} }; - -struct ResNode{ - int index; - int val; + +struct res { + int index, score; }; - -bool myfunction (ResNode i,ResNode j) { - bool ret = 0; - if(i.val>j.val){ - ret=1; - } - else if(i.val==j.val){ - if(i.index &goodWords) { + good_string += "_"; + string temp=""; + + for (int i=0; i::iterator it = (current->children).find(good_words[i]); - if(it != (current->children).end()){ +bool sortByScore (res lhs, res rhs) { + if (lhs.score > rhs.score) return true; + else if (lhs.score == rhs.score) return lhs.index < rhs.index; + return false; +} + +void constructTrie(TrieNode* A, vector goodWords) { + TrieNode* current = A; + + for (int i=0; ichildren).find(goodWords[i][j]); + + if (it != (current->children).end()) { current = it->second; + } else { + + TrieNode* B = new TrieNode(false); + (current->children)[goodWords[i][j]] = B; + current = B; + } - else{ - TrieNode* B = new TrieNode(0); - (current->children)[good_words[i]] = B; - current=B; - } - if(i==good_words.length()-1 || good_words[i+1]=='_'){ - current->is_word = 1; - } + + if (j == goodWords[i].length()-1) current->isWord = true; } } + } - -int solveReview(TrieNode* A, string review){ - int result = 0; - review = review+"_"; - vector arr; - int start = 0; - for(int i=0; i::iterator it = (current->children).find(arr[i][j]); - if(it != (current->children).end()){ - current = it->second; - } - else{ - break; - } - if(j==arr[i].length()-1){ - if(current->is_word == 1){ - result++; + +vector sortReviews(vector reviews, TrieNode* root) { + int score; + vector result; + TrieNode* current; + + vector temp; + + + + for (int i=0; ichildren).find(temp[j][k]); + if (it == (current->children).end()) { + break; } + + current = it->second; + + if (k == temp[j].length()-1 && current->isWord) score++; } } + t.index = i; + t.score = score; + result.push_back(t); } - return result; -} - -vector Solution::solve(string good_words, vector &reviews) { - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details - - vector result; - vector temp_res; - TrieNode* A = new TrieNode(0); - construct_trie(good_words, A); - - for(int i=0; i ret; + + for (int i=0; i Solution::solve(string A, vector &B) { + TrieNode* root = new TrieNode(false); + vector good_words; + + tokenize(A, good_words); + + constructTrie(root, good_words); + + vector result = sortReviews(B, root); + return result; -} \ No newline at end of file +} From 1b03fdb7018107052d2b8378f95f516a9acebe2a Mon Sep 17 00:00:00 2001 From: pockemon Date: Fri, 14 Dec 2018 09:56:41 +0200 Subject: [PATCH 31/59] Solutions for problems in math section-added --- Math/FizzBuzz.cpp | 17 +++++++++++++++++ Math/LargestCoprimeDivisor.cpp | 10 ++++++++++ 2 files changed, 27 insertions(+) create mode 100644 Math/FizzBuzz.cpp create mode 100644 Math/LargestCoprimeDivisor.cpp diff --git a/Math/FizzBuzz.cpp b/Math/FizzBuzz.cpp new file mode 100644 index 0000000..97c9a58 --- /dev/null +++ b/Math/FizzBuzz.cpp @@ -0,0 +1,17 @@ +//see this to check other variations of fizzbuzz: https://www.geeksforgeeks.org/fizz-buzz-implementation/ + +vector Solution::fizzBuzz(int A) { + vector v; + for(int i=1; i<=A; i++) + { + if(i%15==0) + v.push_back("FizzBuzz"); + else if(i%3==0) + v.push_back("Fizz"); + else if(i%5==0) + v.push_back("Buzz"); + else + v.push_back(to_string(i)); + } + return v; +} diff --git a/Math/LargestCoprimeDivisor.cpp b/Math/LargestCoprimeDivisor.cpp new file mode 100644 index 0000000..a83953b --- /dev/null +++ b/Math/LargestCoprimeDivisor.cpp @@ -0,0 +1,10 @@ +//reference: https://www.geeksforgeeks.org/largest-number-divides-x-co-prime-y/ +//Note: you can write the function for gcd [i'm using inbuilt gcd function in c++] + +int Solution::cpFact(int x, int y) { + + while (__gcd(x, y) != 1) { + x = x / __gcd(x, y); + } + return x; +} From d3facea3a5246889b2a06e2bef46388fe7ec6ed7 Mon Sep 17 00:00:00 2001 From: Mudit Joshi Date: Wed, 19 Dec 2018 23:55:04 +0530 Subject: [PATCH 32/59] Reduce Code size for Anagram.cpp --- Hashing/Anagrams.cpp | 24 +++--------------------- 1 file changed, 3 insertions(+), 21 deletions(-) diff --git a/Hashing/Anagrams.cpp b/Hashing/Anagrams.cpp index cde7fc5..411090b 100644 --- a/Hashing/Anagrams.cpp +++ b/Hashing/Anagrams.cpp @@ -1,30 +1,12 @@ // https://www.interviewbit.com/problems/anagrams/ -string mySort(string temp){ - vector str; - for(int i = 0; i < temp.size(); i++){ - str.push_back((int)temp[i]); - } - sort(str.begin(), str.end()); - string ans = ""; - for(int i = 0; i < str.size(); i++){ - ans = ans + (char)str[i]; - } - - return ans; -} - vector > Solution::anagrams(const vector &A) { - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details - vector > sol; unordered_map > myMap; - + string temp; for(int i = 0; i < A.size(); i++){ - string temp = mySort(A[i]); + temp = A[i]; + sort(temp.begin(),temp.end()); myMap[temp].push_back(i+1); } From 1ca2d400dd8cc94791b99f2e83a5e89b2e7788ab Mon Sep 17 00:00:00 2001 From: Sahil Date: Tue, 1 Jan 2019 21:51:27 +0530 Subject: [PATCH 33/59] Update ReverseLinkedList.cpp Added Recursive implementation --- Linked-Lists/ReverseLinkedList.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Linked-Lists/ReverseLinkedList.cpp b/Linked-Lists/ReverseLinkedList.cpp index d46f086..d462627 100644 --- a/Linked-Lists/ReverseLinkedList.cpp +++ b/Linked-Lists/ReverseLinkedList.cpp @@ -29,3 +29,15 @@ ListNode* Solution::reverseList(ListNode* A) { return prev; } + +// A recursive implementation for the same problem. +// +// ListNode* Solution::reverseList(ListNode* A) { +// if(!A || !A->next)return A; + +// ListNode* head = A->next; +// ListNode* p = reverseList(A->next); +// A->next->next = A; +// A->next = NULL; +// return p; +// } From a13c992c504ac95530b6bbf7753543ee6911f9e1 Mon Sep 17 00:00:00 2001 From: Sahil Date: Wed, 6 Mar 2019 14:34:07 +0530 Subject: [PATCH 34/59] Update VerticalOrderTraversalOfBinaryTree.cpp Lesser number of lines in the new code --- Trees/VerticalOrderTraversalOfBinaryTree.cpp | 131 +++++++++++-------- 1 file changed, 80 insertions(+), 51 deletions(-) diff --git a/Trees/VerticalOrderTraversalOfBinaryTree.cpp b/Trees/VerticalOrderTraversalOfBinaryTree.cpp index 72c68b1..336eaba 100644 --- a/Trees/VerticalOrderTraversalOfBinaryTree.cpp +++ b/Trees/VerticalOrderTraversalOfBinaryTree.cpp @@ -7,74 +7,103 @@ * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ -struct node{ - TreeNode* root; - int dis; -}; -void make(map >& m, queue& q){ - if(q.size() == 0){ - return; - } +vector > Solution::verticalOrderTraversal(TreeNode* A) { + vector > v; + if(A == NULL)return v; - TreeNode* root = (q.front()).root; - int dis = (q.front()).dis; + queue > q; + q.push({A, 0}); - if(!root){ - return; + map > mp; + while(!q.empty()){ + pair temp = q.front(); + q.pop(); + + if(temp.first->left){ + q.push({temp.first->left, temp.second-1}); + } + if(temp.first->right){ + q.push({temp.first->right, temp.second+1}); + } + + mp[temp.second].push_back(temp.first->val); + } + + for(map >::iterator it = mp.begin(); it != mp.end(); it++){ + v.push_back(it->second); } + return v; +} + +// struct node{ +// TreeNode* root; +// int dis; +// }; + +// void make(map >& m, queue& q){ +// if(q.size() == 0){ +// return; +// } - m[dis].push_back(root->val); +// TreeNode* root = (q.front()).root; +// int dis = (q.front()).dis; - q.pop(); +// if(!root){ +// return; +// } - if(root->left){ - node l1; - l1.root = root->left; - l1.dis = dis-1; - q.push(l1); - } +// m[dis].push_back(root->val); - if(root->right){ - node l1; - l1.root = root->right; - l1.dis = dis+1; - q.push(l1); - } +// q.pop(); - make(m, q); -} +// if(root->left){ +// node l1; +// l1.root = root->left; +// l1.dis = dis-1; +// q.push(l1); +// } + +// if(root->right){ +// node l1; +// l1.root = root->right; +// l1.dis = dis+1; +// q.push(l1); +// } + +// make(m, q); +// } -vector > Solution::verticalOrderTraversal(TreeNode* A) { - map > m; - vector > sol; - queue q; +// vector > Solution::verticalOrderTraversal(TreeNode* A) { +// map > m; +// vector > sol; +// queue q; - node n; - n.root = A; - n.dis = 0; +// node n; +// n.root = A; +// n.dis = 0; - q.push(n); +// q.push(n); - make(m, q); +// make(m, q); - map > :: iterator it = m.begin(); +// map > :: iterator it = m.begin(); - int curr = 0; +// int curr = 0; - while(it != m.end()){ - vector temp; - sol.push_back(temp); +// while(it != m.end()){ +// vector temp; +// sol.push_back(temp); - temp = it->second; +// temp = it->second; - for(int i = 0; i < temp.size(); i++){ - sol[curr].push_back(temp[i]); - } +// for(int i = 0; i < temp.size(); i++){ +// sol[curr].push_back(temp[i]); +// } - curr++; - it++; - } +// curr++; +// it++; +// } - return sol; -} +// return sol; +// } From 91cbf3b822896a451949e6ff61d6b5632870a725 Mon Sep 17 00:00:00 2001 From: Sahil Date: Wed, 6 Mar 2019 15:01:46 +0530 Subject: [PATCH 35/59] Update PopulateNextRightPointersTree.cpp Added a non recursive solution --- Trees/PopulateNextRightPointersTree.cpp | 116 ++++++++++++++++-------- 1 file changed, 79 insertions(+), 37 deletions(-) diff --git a/Trees/PopulateNextRightPointersTree.cpp b/Trees/PopulateNextRightPointersTree.cpp index c76b483..e7dbac0 100644 --- a/Trees/PopulateNextRightPointersTree.cpp +++ b/Trees/PopulateNextRightPointersTree.cpp @@ -6,47 +6,89 @@ * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ + +// A Non-recursive solution void Solution::connect(TreeLinkNode* A) { - if(A == NULL){ - return; - } + if(A == NULL)return; - if(A->left != NULL){ - if(A->right != NULL){ - (A->left)->next = A->right; - } - else{ - TreeLinkNode* temp = A; - while(temp->next != NULL){ - if((temp->next)->left != NULL){ - (A->left)->next = (temp->next)->left; - break; - } - else if((temp->next)->right != NULL){ - (A->left)->next = (temp->next)->right; - break; - } - temp = temp->next; - } + queue > q; + + q.push({0, A}); + + while(!q.empty()){ + pair temp = q.front(); + + int level = temp.first; + q.pop(); + +// Keep putting the nodes until we are on the same level. + while(!q.empty() and q.front().first == level){ + if(temp.second->left) + q.push({level+1, temp.second->left}); + if(temp.second->right) + q.push({level+1, temp.second->right}); + + temp.second->next = q.front().second; + temp = q.front(); + + q.pop(); } +// + temp.second->next = NULL; + +// if the control doesn't enter the above while loop, accomodate +// the left out nodes. (Consider a three node tree!) + if(temp.second->left) + q.push({level+1, temp.second->left}); + if(temp.second->right) + q.push({level+1, temp.second->right}); + } +} + + +// Recursive Solution +// void Solution::connect(TreeLinkNode* A) { +// if(A == NULL){ +// return; +// } - if(A->right != NULL){ - TreeLinkNode* temp = A; - while(temp->next != NULL){ - if((temp->next)->left != NULL){ - (A->right)->next = (temp->next)->left; - break; - } - else if((temp->next)->right != NULL){ - (A->right)->next = (temp->next)->right; - break; - } - temp = temp->next; - } - } +// if(A->left != NULL){ +// if(A->right != NULL){ +// (A->left)->next = A->right; +// } +// else{ +// TreeLinkNode* temp = A; +// while(temp->next != NULL){ +// if((temp->next)->left != NULL){ +// (A->left)->next = (temp->next)->left; +// break; +// } +// else if((temp->next)->right != NULL){ +// (A->left)->next = (temp->next)->right; +// break; +// } +// temp = temp->next; +// } +// } +// } +// if(A->right != NULL){ +// TreeLinkNode* temp = A; +// while(temp->next != NULL){ +// if((temp->next)->left != NULL){ +// (A->right)->next = (temp->next)->left; +// break; +// } +// else if((temp->next)->right != NULL){ +// (A->right)->next = (temp->next)->right; +// break; +// } +// temp = temp->next; +// } +// } - connect(A->right); - connect(A->left); -} + +// connect(A->right); +// connect(A->left); +// } From e6f7be727c4db124e330aaedea5bcb707d456a9c Mon Sep 17 00:00:00 2001 From: Sahil Date: Thu, 7 Mar 2019 01:41:48 +0530 Subject: [PATCH 36/59] Update 2-SumBinaryTree.cpp Added a third solution for 2 sum binary, short and simple. --- Trees/2-SumBinaryTree.cpp | 168 +++++++++++++++++++++++++------------- 1 file changed, 111 insertions(+), 57 deletions(-) diff --git a/Trees/2-SumBinaryTree.cpp b/Trees/2-SumBinaryTree.cpp index 615226b..d4dcfd2 100644 --- a/Trees/2-SumBinaryTree.cpp +++ b/Trees/2-SumBinaryTree.cpp @@ -9,75 +9,129 @@ * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ - +// A shorter and intuitive method. Check out the next two solutions as well. int Solution::t2Sum(TreeNode* A, int B) { + // Base Case + if(!A)return 0; - stack st1; - stack st2; - - int val1 = 0, val2 = 0; - int done1 = 0, done2 = 0; + // Make two stacks for the two different traversals, + // one from the right side, other from the left. + stack s1, s2; + TreeNode* temp1 = A, *temp2 = A; - TreeNode* curr1 = A; - TreeNode* curr2 = A; + // Take temp1 to the extreme left + while(temp1){ + s1.push(temp1); + temp1 = temp1->left; + } + // and temp2 to extreme right + while(temp2){ + s2.push(temp2); + temp2 = temp2->right; + } + temp1 = s1.top(); + temp2 = s2.top(); - while(1){ - while(done1 == 0){ - if(curr1 != NULL){ - st1.push(curr1); - curr1 = curr1->left; + // While we do not traverse the complete tree + while(temp1 and temp2 and temp1->val < temp2 -> val){ + if(temp1->val + temp2->val == B)return 1; + + if(temp1->val + temp2->val < B){ + // Move Ahead the temp1 pointer + s1.pop(); + // Check out the preorder traversal using stacks + temp1 = temp1->right; + while(temp1){ + s1.push(temp1); + temp1 = temp1->left; } - else{ - if(st1.empty()){ - done1 = 1; - } - else{ - curr1 = st1.top(); - val1 = curr1->val; - st1.pop(); - curr1 = curr1->right; - done1 = 1; - } + temp1 = s1.top(); + }else{ + // Move ahead the temp2 pointer + s2.pop(); + // Inverse of preorder traversal using stacks + // (not to be confused with postorder traversal) + temp2 = temp2->left; + while(temp2){ + s2.push(temp2); + temp2 = temp2->right; } + temp2 = s2.top(); } + } + return 0; +} + + +// int Solution::t2Sum(TreeNode* A, int B) { + +// stack st1; +// stack st2; + +// int val1 = 0, val2 = 0; +// int done1 = 0, done2 = 0; + +// TreeNode* curr1 = A; +// TreeNode* curr2 = A; + + +// while(1){ +// while(done1 == 0){ +// if(curr1 != NULL){ +// st1.push(curr1); +// curr1 = curr1->left; +// } +// else{ +// if(st1.empty()){ +// done1 = 1; +// } +// else{ +// curr1 = st1.top(); +// val1 = curr1->val; +// st1.pop(); +// curr1 = curr1->right; +// done1 = 1; +// } +// } +// } - while(done2 == 0){ - if(curr2 != NULL){ - st2.push(curr2); - curr2 = curr2->right; - } - else{ - if(st2.empty()){ - done2 = 1; - } - else{ - curr2 = st2.top(); - st2.pop(); - val2 = curr2->val; - curr2 = curr2->left; - done2 = 1; - } - } - } +// while(done2 == 0){ +// if(curr2 != NULL){ +// st2.push(curr2); +// curr2 = curr2->right; +// } +// else{ +// if(st2.empty()){ +// done2 = 1; +// } +// else{ +// curr2 = st2.top(); +// st2.pop(); +// val2 = curr2->val; +// curr2 = curr2->left; +// done2 = 1; +// } +// } +// } - if(((val1 + val2) == B) && (val1 != val2)){ - return 1; - } - else if((val1 + val2) < B){ - done1 = 0; - } - else if((val1 + val2) > B){ - done2 = 0; - } +// if(((val1 + val2) == B) && (val1 != val2)){ +// return 1; +// } +// else if((val1 + val2) < B){ +// done1 = 0; +// } +// else if((val1 + val2) > B){ +// done2 = 0; +// } - if(val1 >= val2){ - return 0; - } - } +// if(val1 >= val2){ +// return 0; +// } +// } - return 0; -} +// return 0; +// } /* Another method if you are unable to get above method, although both of them work the same. From 12f9d5f91a29e2ed5ddb9594baf63a33a7d5d001 Mon Sep 17 00:00:00 2001 From: Shivam Gupta Date: Tue, 28 May 2019 14:38:11 +0530 Subject: [PATCH 37/59] added city Tour in MATH --- Math/CityTour.cpp | 164 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 Math/CityTour.cpp diff --git a/Math/CityTour.cpp b/Math/CityTour.cpp new file mode 100644 index 0000000..790b517 --- /dev/null +++ b/Math/CityTour.cpp @@ -0,0 +1,164 @@ +static const int MODULUS = 1000000007; + +// compute 2^k modulo MODULUS +int power2modulo(int k) +{ + long result = 1; + for (int i=0; i numerator, denominator; + priority_queue new_numerator, new_denominator; + int a = std::max(r, n - r); + int b = n - a; + long result = 1; + long T; + + // do not compute factorials, but push the terms that make up the factorials + for (int i=a+1; i<=n; i++) { + numerator.push(i); + } + for (int i=2; i<=b; i++) { + denominator.push(i); + } + + // we try to cancel out the GCD of each numerator with each denominator + int n_len = numerator.size(); + for (int i=0; i segment_t; +typedef vector segments_t; + +// Compute the number of permutations of paths, +// Combine the two segments at a time for ease of understanding. +// For example, consider two segments with 3 cities (AAA) and 4 cities (BBBB). +// There are 7 choose 3 ways to interleave the cities from the two segments. +// One such interleaving pattern is: ABAABBB. +// If there are X different paths for the A cities and Y different paths for B, +// the new combined segment has 7 cities and 7 choose 3 times X times Y paths. +int arrangements(segments_t &segments) { + long num_paths; + while (true) { + auto itA = segments.begin(); + auto itB = segments.end()-1; + if (itA == itB) { + num_paths = itA->second; + break; + } else { + itA->first += itB->first; + num_paths = binomial(itA->first, itB->first); + num_paths %= MODULUS; + num_paths = (num_paths * itA->second) % MODULUS; + num_paths = (num_paths * itB->second) % MODULUS; + itA->second = num_paths; + segments.erase(itB); + } + } + return num_paths; +} + +int Solution::solve(int A, vector &B) { + priority_queue V; + segments_t segments; + + if (B.size() == 0) + return 0; + + // Insert B into priority queue V so we can sort the cities. + for (auto p : B) { + V.push(p); + } + + int right = V.top(); + V.pop(); + if (right < A) { + // Account for corner case where last region is one-sided. + // In this case, there is only one path. + segments.push_back(pair(A - right, 1)); + } + while (!V.empty()) { + if ((V.top() + 1) == right) { + // We skip over adjacent cities that have been visited. + V.pop(); + --right; + } else { + // We make a maximal segment of consecutive unvisited cities. + int consecutive = right; + right = V.top(); + V.pop(); + consecutive -= right + 1; + // For a segment of N consecutive unvisited cities bordered on both sides + // by visited cities, there are 2^^(N-1) posible paths. + // Record the length and number of paths. + segments.push_back(segment_t(consecutive, power2modulo(consecutive-1))); + } + } + if (right != 1) { + // Account for corner case where last region is one-sided. + segments.push_back(segment_t(right - 1, 1)); + } + + return arrangements(segments); +} \ No newline at end of file From 549db939a2fc00ba5383274e829b4bcf2ef09457 Mon Sep 17 00:00:00 2001 From: Shivam Gupta Date: Wed, 29 May 2019 11:58:30 +0530 Subject: [PATCH 38/59] added SortedPermutatioRank.cpp --- Math/SortedPermutatioRank.cpp | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Math/SortedPermutatioRank.cpp diff --git a/Math/SortedPermutatioRank.cpp b/Math/SortedPermutatioRank.cpp new file mode 100644 index 0000000..385452a --- /dev/null +++ b/Math/SortedPermutatioRank.cpp @@ -0,0 +1,46 @@ +#define mod 1000003 + +void buildFact(vector &fact,int len){ + fact.push_back(1); + fact.push_back(1); + for(int i = 2; i<= len ; i++){ + fact.push_back((fact[i-1]*i)%mod); + } +} + +int Solution::findRank(string A){ + vector fact; + // create a vector filled with factorial value of that index modulated + buildFact(fact,A.length()); + + // created a sorted version of given string + string b = A; + sort(b.begin() , b.end()); + + // create to Hash to store actual location of each character in sorted manner + unordered_map pos; + for(int i = 0; i v; + for(int i = 0; i v[i]) + v[j]--; + } + } + reverse(v.begin() , v.end()); + + // factorial arithmatics + long n = 0; + for(int i = 0; i < v.size() ; i++){ + n = (n + v[i]*fact[i])%mod; + } + n++; + return n; +} \ No newline at end of file From 7291b0207019a6fb31f903f5a10fc8270952f6b4 Mon Sep 17 00:00:00 2001 From: Shivam Gupta Date: Wed, 29 May 2019 13:57:19 +0530 Subject: [PATCH 39/59] added MatrixMedian.cpp --- Binary-Search/MatrixMedian.cpp | 72 ++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Binary-Search/MatrixMedian.cpp diff --git a/Binary-Search/MatrixMedian.cpp b/Binary-Search/MatrixMedian.cpp new file mode 100644 index 0000000..dd2d08b --- /dev/null +++ b/Binary-Search/MatrixMedian.cpp @@ -0,0 +1,72 @@ +// Credit: dthoang(InterviewBit UserName) +// This Solution is Slightly modified version +int find_less(vector &A, int B, int &C) { + int head = 0, tail = A.size()-1; + + // shortcuts because A is sorted + if (B > A[tail]) + return tail+1; + if (B <= A[head]) { + C = min(C, A[head]); + return 0; + } + // if shortcut failed then + // binary search + while (head < tail) { + int mid = (head + tail) / 2; + if (B <= A[mid]) { + tail = mid - 1; + } else { + head = mid + 1; + } + } + // make sure we count the number of items strictly less than B + if (A[head] < B) + head++; + + // get the smallest element greater than B + if (head < A.size()) { + C = min(C, A[head]); + } + return head; +} + +int find_less_matrix(vector > &A, int B, int &C) { + int less = 0; + C = INT_MAX; + for (int i=0;i > &A) { + int N = A.size(),M = A[0].size(); + int head = INT_MAX,tail = INT_MIN; + int target = (N*M)/2, actual,result; + + // find min and max elements of A + for (int i=0;i Date: Wed, 29 May 2019 15:08:50 +0530 Subject: [PATCH 40/59] better and smaller Solution for Trees/MinimumDepthOfABinaryTree.cpp --- Trees/MinimumDepthOfABinaryTree.cpp | 28 +++------------------------- 1 file changed, 3 insertions(+), 25 deletions(-) diff --git a/Trees/MinimumDepthOfABinaryTree.cpp b/Trees/MinimumDepthOfABinaryTree.cpp index 2eb4952..62ad33e 100644 --- a/Trees/MinimumDepthOfABinaryTree.cpp +++ b/Trees/MinimumDepthOfABinaryTree.cpp @@ -1,5 +1,3 @@ -// https://www.interviewbit.com/problems/min-depth-of-binary-tree/ - /** * Definition for binary tree * struct TreeNode { @@ -9,28 +7,8 @@ * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ -int depth(TreeNode* root){ - if(root == NULL){ - return 0; - } - else if(root->left == NULL && root->right == NULL){ - return 1; - } - else if(root->left == NULL && root->right != NULL){ - return 1 + depth(root->right); - } - else if(root->left != NULL && root->right == NULL){ - return 1 + depth(root->left); - } - return min(1 + depth(root->right), 1 + depth(root->left)); -} - int Solution::minDepth(TreeNode* A) { - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details - - return depth(A); - + if(A==NULL) return INT_MAX; + if(A->left==NULL && A->right==NULL) return 1; + return min(minDepth(A->left),minDepth(A->right))+1; } From b013f0b8c6ff3c7f9ede87729e3730d8a29c8c6d Mon Sep 17 00:00:00 2001 From: Mayank Mehta Date: Fri, 31 May 2019 22:53:30 +0530 Subject: [PATCH 41/59] Update 3Sum.cpp --- Two-Pointers/3Sum.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Two-Pointers/3Sum.cpp b/Two-Pointers/3Sum.cpp index 412b4ba..3e9b70d 100644 --- a/Two-Pointers/3Sum.cpp +++ b/Two-Pointers/3Sum.cpp @@ -14,7 +14,6 @@ int Solution::threeSumClosest(vector &A, int B) { int i = 0; int sum, minDiff = INT_MAX; - int count = 0; while(i < A.size()-2){ int left = i+1; From 075ede359d4f883e78e85030dddb1f4e7423eb23 Mon Sep 17 00:00:00 2001 From: Rushit Jasani Date: Sun, 9 Jun 2019 14:42:35 +0530 Subject: [PATCH 42/59] Update PrettyJson.cpp --- Strings/PrettyJson.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Strings/PrettyJson.cpp b/Strings/PrettyJson.cpp index ba16fca..4957cff 100644 --- a/Strings/PrettyJson.cpp +++ b/Strings/PrettyJson.cpp @@ -37,7 +37,7 @@ vector Solution::prettyJSON(string A) row += '\t'; row += A[j]; if(j + 1 < n && A[j+1] == ',') - row += A[j++]; + row += A[++j]; ans.push_back(row); i = j+1; break; From 40cb733524a3e462500fd3e47b969cf0c2d79636 Mon Sep 17 00:00:00 2001 From: Shivansh Srivastava <41651033+Shivansh1805@users.noreply.github.com> Date: Fri, 14 Jun 2019 16:59:19 +0530 Subject: [PATCH 43/59] Solution to kingdom War problem --- DynamicProgramming/Kingdom War | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 DynamicProgramming/Kingdom War diff --git a/DynamicProgramming/Kingdom War b/DynamicProgramming/Kingdom War new file mode 100644 index 0000000..f51a0f9 --- /dev/null +++ b/DynamicProgramming/Kingdom War @@ -0,0 +1,35 @@ +int Solution::solve(vector > &A) { + int ans,i,j,dn,rig,r,c,sum; + int n=A.size(); + int m=A[0].size(); + vector > rsum=A; + for(r=0;r=0;c--) + { + rsum[r][c]=A[r][c]+rsum[r][c+1]; + } + } + int ma=A[n-1][m-1]; + int dp[n][m]; + memset(dp,0,sizeof(dp)); + for(j=m-1;j>=0;j--) + { + for(i=n-1;i>=0;i--) + { + rig=0; + dn=0; + if(i!=n-1) + { + dn=dp[i+1][j]; + } + if(j!=m-1) + { + rig=rsum[i][j+1]; + } + dp[i][j]=A[i][j]+rig+dn; + ma=max(ma,dp[i][j]); + } + } + return(ma); +} From 718ca9ce7689ceff025a5212eba6afa63f6c310a Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 15 Jun 2019 15:02:38 +0530 Subject: [PATCH 44/59] Rename Kingdom War to KingdomWar --- DynamicProgramming/{Kingdom War => KingdomWar} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DynamicProgramming/{Kingdom War => KingdomWar} (100%) diff --git a/DynamicProgramming/Kingdom War b/DynamicProgramming/KingdomWar similarity index 100% rename from DynamicProgramming/Kingdom War rename to DynamicProgramming/KingdomWar From cd922d4839b63a96c5810a73f10ea1969c1a6a60 Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 15 Jun 2019 15:31:21 +0530 Subject: [PATCH 45/59] Delete MatrixMedian.cpp Kindly submit your own solutions and not others' without their consent. --- Binary-Search/MatrixMedian.cpp | 72 ---------------------------------- 1 file changed, 72 deletions(-) delete mode 100644 Binary-Search/MatrixMedian.cpp diff --git a/Binary-Search/MatrixMedian.cpp b/Binary-Search/MatrixMedian.cpp deleted file mode 100644 index dd2d08b..0000000 --- a/Binary-Search/MatrixMedian.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// Credit: dthoang(InterviewBit UserName) -// This Solution is Slightly modified version -int find_less(vector &A, int B, int &C) { - int head = 0, tail = A.size()-1; - - // shortcuts because A is sorted - if (B > A[tail]) - return tail+1; - if (B <= A[head]) { - C = min(C, A[head]); - return 0; - } - // if shortcut failed then - // binary search - while (head < tail) { - int mid = (head + tail) / 2; - if (B <= A[mid]) { - tail = mid - 1; - } else { - head = mid + 1; - } - } - // make sure we count the number of items strictly less than B - if (A[head] < B) - head++; - - // get the smallest element greater than B - if (head < A.size()) { - C = min(C, A[head]); - } - return head; -} - -int find_less_matrix(vector > &A, int B, int &C) { - int less = 0; - C = INT_MAX; - for (int i=0;i > &A) { - int N = A.size(),M = A[0].size(); - int head = INT_MAX,tail = INT_MIN; - int target = (N*M)/2, actual,result; - - // find min and max elements of A - for (int i=0;i Date: Sat, 15 Jun 2019 15:31:37 +0530 Subject: [PATCH 46/59] Delete MinimumDepthOfABinaryTree.cpp --- Trees/MinimumDepthOfABinaryTree.cpp | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 Trees/MinimumDepthOfABinaryTree.cpp diff --git a/Trees/MinimumDepthOfABinaryTree.cpp b/Trees/MinimumDepthOfABinaryTree.cpp deleted file mode 100644 index 62ad33e..0000000 --- a/Trees/MinimumDepthOfABinaryTree.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Definition for binary tree - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -int Solution::minDepth(TreeNode* A) { - if(A==NULL) return INT_MAX; - if(A->left==NULL && A->right==NULL) return 1; - return min(minDepth(A->left),minDepth(A->right))+1; -} From 509b95768774ec4a2733a11becfbb346a34a49bd Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 15 Jun 2019 15:32:55 +0530 Subject: [PATCH 47/59] Rename SortedPermutatioRank.cpp to SortedPermutationRank.cpp --- Math/{SortedPermutatioRank.cpp => SortedPermutationRank.cpp} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename Math/{SortedPermutatioRank.cpp => SortedPermutationRank.cpp} (99%) diff --git a/Math/SortedPermutatioRank.cpp b/Math/SortedPermutationRank.cpp similarity index 99% rename from Math/SortedPermutatioRank.cpp rename to Math/SortedPermutationRank.cpp index 385452a..4693785 100644 --- a/Math/SortedPermutatioRank.cpp +++ b/Math/SortedPermutationRank.cpp @@ -43,4 +43,4 @@ int Solution::findRank(string A){ } n++; return n; -} \ No newline at end of file +} From 5ad6cac7368a90df29c6f3411f0f945c461939c6 Mon Sep 17 00:00:00 2001 From: Sahil Date: Sat, 15 Jun 2019 15:35:12 +0530 Subject: [PATCH 48/59] Min Depth of Binary Tree --- Trees/MinDepthOfABinaryTree.cpp | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Trees/MinDepthOfABinaryTree.cpp diff --git a/Trees/MinDepthOfABinaryTree.cpp b/Trees/MinDepthOfABinaryTree.cpp new file mode 100644 index 0000000..da628e5 --- /dev/null +++ b/Trees/MinDepthOfABinaryTree.cpp @@ -0,0 +1,7 @@ +int Solution::minDepth(TreeNode* A) { + if(!A)return 0; + if(!A->left and !A->right) return 1; + if(!A->left)return minDepth(A->right) + 1; + if(!A->right)return minDepth(A->left) + 1; + return min(minDepth(A->left), minDepth(A->right)) + 1; +} From f06e792c60ca785b7eeff1cc2573362d7c3c1f08 Mon Sep 17 00:00:00 2001 From: Bhavik Dhandhalya Date: Fri, 28 Jun 2019 14:10:16 +0530 Subject: [PATCH 49/59] added find permutation --- Arrays/Find Permutation.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Arrays/Find Permutation.cpp diff --git a/Arrays/Find Permutation.cpp b/Arrays/Find Permutation.cpp new file mode 100644 index 0000000..83c9ff2 --- /dev/null +++ b/Arrays/Find Permutation.cpp @@ -0,0 +1,32 @@ +/* +Solution by : Bhavik Dhandhalya +Given a positive integer n and a string s consisting only of letters D or I, you have to find any permutation of first n positive integer that satisfy the given input string. + +D means the next number is smaller, while I means the next number is greater. + +Notes +Length of given string s will always equal to n - 1 +Your solution should run in linear time and space. + +Input 1: + +n = 3 +s = ID +Return: [1, 3, 2] + +Solution Complexity : O(N) time and O(1) space +Refer this URL for lexicographically smaller permutation solution: +https://leetcode.com/articles/find-permutation/ +*/ + +vector Solution::findPerm(const string A, int B) { + vector < int > ans; + int n = A.length(); + int maxi = n + 1, mini = 1; + for (int i = 0; i < n; i++) { + if (A[i] == 'I') ans.push_back(mini++); + if (A[i] == 'D') ans.push_back(maxi--); + } + ans.push_back(maxi); + return ans; +} From bb51ac5d764e5f189d643f4b085faec5d0d59632 Mon Sep 17 00:00:00 2001 From: Bhavik Dhandhalya Date: Sat, 29 Jun 2019 11:18:05 +0530 Subject: [PATCH 50/59] much simpler code than what was already here change name later. --- Arrays/Flip simple code.cpp | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Arrays/Flip simple code.cpp diff --git a/Arrays/Flip simple code.cpp b/Arrays/Flip simple code.cpp new file mode 100644 index 0000000..5c5e87c --- /dev/null +++ b/Arrays/Flip simple code.cpp @@ -0,0 +1,51 @@ +/* +You are given a binary string(i.e. with characters 0 and 1) S consisting of characters S1, S2, …, SN. In a single operation, you can choose two indices L and R such that 1 ≤ L ≤ R ≤ N and flip the characters SL, SL+1, …, SR. By flipping, we mean change character 0 to 1 and vice-versa. + +Your aim is to perform ATMOST one operation such that in final string number of 1s is maximised. If you don’t want to perform the operation, return an empty array. Else, return an array consisting of two elements denoting L and R. If there are multiple solutions, return the lexicographically smallest pair of L and R. + +Notes: + +Pair (a, b) is lexicographically smaller than pair (c, d) if a < c or, if a == c and b < d. +For example, +S = 010 +Output = [1 1] +*/ + +vector Solution::flip(string A) { + int n = A.length(); + int ones = 0; + int zeros = 0; + int L = INT_MAX, R = 0; + int ansL = 0, ansR = 0; + int prev = 0; + bool found = false; + + for (int i = 0; i < n; i++) { + ones += A[i] == '1'; + zeros += A[i] == '0'; + if (zeros) found = true; + + if (ones > zeros) { + ones = 0; + zeros = 0; + L = INT_MAX; + R = 0; + } else if (A[i] == '0') { + L = min(L, i); + R = i; + + if (zeros - ones > prev) { + ansR = R; + ansL = L; + prev = zeros - ones; + } + } + } + + vector < int > ans; + if (found) { + ans.push_back(ansL + 1); + ans.push_back(ansR + 1); + } + return ans; +} From d444c8a64e1adcc412ff4c5aec6a2bb6b2204b38 Mon Sep 17 00:00:00 2001 From: Hardik Rana Date: Sun, 7 Jul 2019 06:34:04 +0200 Subject: [PATCH 51/59] Rotated Sorted Array Search --- Binary-Search/RotatedSortedArraySearch.cpp | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Binary-Search/RotatedSortedArraySearch.cpp b/Binary-Search/RotatedSortedArraySearch.cpp index 6f46735..6d6ce5d 100644 --- a/Binary-Search/RotatedSortedArraySearch.cpp +++ b/Binary-Search/RotatedSortedArraySearch.cpp @@ -1,5 +1,43 @@ // https://www.interviewbit.com/problems/rotated-sorted-array-search/ +int search1(const vector &arr, int low, int high, int B) +{ + if (low > high) return -1; + + int mid = (low) + (high-low)/2; + if (arr[mid] == B) return mid; + + if (arr[low] <= arr[mid]) + { + if (B >= arr[low] && B <= arr[mid]) + return search1(arr, low, mid-1, B); + + return search1(arr, mid+1, high, B); + } + + else if (arr[mid] <= arr[high]) + { + if (B >= arr[mid] && B <= arr[high]) + return search1(arr, mid+1, high, B); + + return search1(arr, low, mid-1, B); + } +} + + +int Solution::search(const vector &A, int B) { + + int n = A.size(); + int i = search1(A, 0, n-1, B); + + if (i != -1) + return i; + else + return -1; + +} + +/* int findPivot(const vector &A){ int start = 0; int end = A.size()-1; @@ -64,3 +102,4 @@ int Solution::search(const vector &A, int B) { // B < A[pivot] } +*/ From 142ebaaca48301937b3cae16591d7a10d594c08f Mon Sep 17 00:00:00 2001 From: Hardik Rana Date: Sun, 7 Jul 2019 07:00:18 +0200 Subject: [PATCH 52/59] Palindrome String --- Strings/PalindromeString.cpp | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Strings/PalindromeString.cpp b/Strings/PalindromeString.cpp index 650ffd3..081521c 100644 --- a/Strings/PalindromeString.cpp +++ b/Strings/PalindromeString.cpp @@ -1,5 +1,43 @@ // https://www.interviewbit.com/problems/palindrome-string/ +int Solution::isPalindrome(string A) { + + int len = A.length(); + + for(int i=0;i='a' && A[l]<='z') && !(A[l]>='0' && A[l]<='9')) + { + l++; + } + + else if(!(A[h]>='a' && A[h]<='z') && !(A[h]>='0' && A[h]<='9')) + { + h--; + } + else if(A[l] == A[h]) + { + l++; + h--; + } + else + { + return 0; + } + } + + return 1; +} + +/* int Solution::isPalindrome(string A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. @@ -85,3 +123,4 @@ int Solution::isPalindrome(string A) { return 1; } +*/ From 603f71b1e9acbac037f544110b6f363be5250cf2 Mon Sep 17 00:00:00 2001 From: Mohit Saini Date: Fri, 26 Jul 2019 00:57:15 +0530 Subject: [PATCH 53/59] Facebook Microsoft --- Two-Pointers/SortByColor.cpp | 37 ++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Two-Pointers/SortByColor.cpp diff --git a/Two-Pointers/SortByColor.cpp b/Two-Pointers/SortByColor.cpp new file mode 100644 index 0000000..7f13b18 --- /dev/null +++ b/Two-Pointers/SortByColor.cpp @@ -0,0 +1,37 @@ +// https://www.interviewbit.com/problems/sort-by-color/ + +void Solution::sortColors(vector &A) { + // Do not write main() function. + // Do not read input, instead use the arguments to the function. + // Do not print the output, instead return values as specified + // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details + + int lo = 0; + int hi = A.size() - 1; + int mid = 0; + + // Iterate till all the elements + // are sorted + while (mid <= hi) + { + switch (A[mid]) + { + + // If the element is 0 + case 0: + swap(A[lo++], A[mid++]); + break; + + // If the element is 1 . + case 1: + mid++; + break; + + // If the element is 2 + case 2: + swap(A[mid], A[hi--]); + break; + } + } + +} \ No newline at end of file From 0657594878e7a932c4f557da000fc2d1af02725a Mon Sep 17 00:00:00 2001 From: aashish-ak Date: Sat, 3 Aug 2019 17:36:17 +0530 Subject: [PATCH 54/59] Added CombinationSum.cpp --- Backtracking/CombinationSum.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Backtracking/CombinationSum.cpp diff --git a/Backtracking/CombinationSum.cpp b/Backtracking/CombinationSum.cpp new file mode 100644 index 0000000..4c2c668 --- /dev/null +++ b/Backtracking/CombinationSum.cpp @@ -0,0 +1,27 @@ +void aux(int i, int sum, int k, vector &A, vector &temp, set> &ans) { + if(i == A.size() || sum >= k){ + if(sum == k){ + ans.insert(temp); + } + return; + } + + temp.push_back(A[i]); + aux(i, sum+A[i], k, A, temp, ans); + aux(i+1, sum+A[i], k, A, temp, ans); + temp.pop_back(); + aux(i+1, sum, k, A, temp, ans); +} + +vector > Solution::combinationSum(vector &A, int B) { + set> ans; + sort(A.begin(), A.end()); + vector temp; + aux(0, 0, B, A, temp, ans); + vector> res; + + for(auto i = ans.begin(); i != ans.end(); i++){ + res.push_back(*i); + } + return res; +} From 688df2fff4609c217d4f1a0268c15809927d48e3 Mon Sep 17 00:00:00 2001 From: Seokjin Hong Date: Fri, 16 Aug 2019 13:44:02 +0900 Subject: [PATCH 55/59] Added CloneGraph.cpp (Google, Facebook, Amazon) --- Graphs/CloneGraph.cpp | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Graphs/CloneGraph.cpp diff --git a/Graphs/CloneGraph.cpp b/Graphs/CloneGraph.cpp new file mode 100644 index 0000000..ed6e982 --- /dev/null +++ b/Graphs/CloneGraph.cpp @@ -0,0 +1,46 @@ +/** + * Definition for undirected graph. + * struct UndirectedGraphNode { + * int label; + * vector neighbors; + * UndirectedGraphNode(int x) : label(x) {}; + * }; + */ +UndirectedGraphNode *Solution::cloneGraph(UndirectedGraphNode *node) { + std::map m; + queue q; + + q.push(node); + + while (!q.empty()) { + auto n = q.front(); + q.pop(); + + UndirectedGraphNode* new_node = nullptr; + + if (m.find(n->label) == m.end()) { + // not exist in map + new_node = new UndirectedGraphNode(n->label); + m[n->label] = new_node; + } else { + // exist in map + new_node = m[n->label]; + } + + for (auto neighbor: n->neighbors) { + if (m.find(neighbor->label) == m.end()) { + // not exist in map + m[neighbor->label] = new UndirectedGraphNode(neighbor->label); + new_node->neighbors.push_back(m[neighbor->label]); + + q.push(neighbor); + } else { + // exist in map + new_node->neighbors.push_back(m[neighbor->label]); + } + } + } + + return m[node->label]; +} + From f5feb5c6d9817e707042743b3121af6ac557496f Mon Sep 17 00:00:00 2001 From: mailtokartik1 Date: Thu, 30 Apr 2020 16:01:02 +0900 Subject: [PATCH 56/59] Numbers of Length N solution --- Math/NumbersOfLengthN.cpp | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Math/NumbersOfLengthN.cpp diff --git a/Math/NumbersOfLengthN.cpp b/Math/NumbersOfLengthN.cpp new file mode 100644 index 0000000..ab47920 --- /dev/null +++ b/Math/NumbersOfLengthN.cpp @@ -0,0 +1,50 @@ +int all(bool digits[], int B, int total) { + bool isZero = digits[0] ? 1 : 0; + long long int count = 1; + if (B == 1) { + return total; + } + count *= isZero ? total - 1 : total; + count *= pow(total, B - 1); + return count; +} +int compare(bool digits[], int B, int C, int total) { + string c = to_string(C); + vector count(10); + for (int i = 1; i < 10; i ++) { + count[i] = digits[i - 1] + count[i - 1]; + } + int dp[B + 1]; + dp[0] = 0; + bool flag = 1; + for (int i = 1; i <= B; i ++) { + dp[i] = dp[i - 1] * total; + if (flag || i == 1) { + int smallCount = count[c[i - 1] - '0']; + if (B != 1 && i == 1 && digits[0]) { + smallCount --; + } + dp[i] += smallCount; + if (!digits[c[i - 1] - '0']) { + flag = false; + } + } + } + return dp[B]; +} +int Solution::solve(vector &A, int B, int C) { + int length = log10(C) + 1; + bool digits[10] = {0}; + int total = 0; + for (int i = 0; i < A.size(); i ++) { + digits[A[i]] = 1; + total ++; + } + if (B > length || B == 0) { + return 0; + } else if (B < length) { + return all(digits, B, total); + } else { + return compare(digits, B, C, total); + } +} From 3eea0fc6acdfd92377fe6f870da5c765c04db17a Mon Sep 17 00:00:00 2001 From: mailtokartik1 Date: Fri, 1 May 2020 00:12:38 +0900 Subject: [PATCH 57/59] add sorted permutation with repeats sultion --- Math/SortedPermutationRankWithRepeats.cpp | 62 +++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Math/SortedPermutationRankWithRepeats.cpp diff --git a/Math/SortedPermutationRankWithRepeats.cpp b/Math/SortedPermutationRankWithRepeats.cpp new file mode 100644 index 0000000..c42bdda --- /dev/null +++ b/Math/SortedPermutationRankWithRepeats.cpp @@ -0,0 +1,62 @@ +#define MOD 1000003 +long long int fact(int n) { + if (n == 0 || n == 1) { + return 1; + } + return (fact(n - 1) * n) % MOD; +} + long long int inverseNumber(int num) { + long long int ans = 1, base = (long long) num; + int power = MOD - 2; + while (power > 0) { + if (power == 1) { + return (ans * base) % MOD; + } + if (power % 2 == 0) { + base = (base * base) % MOD; + power /= 2; + } else { + ans = (ans * base) % MOD; + power--; + } + } + return ans; +} +int Solution::findRank(string A) { + if (A.size() <= 0) { + return 0; + } + int alpha[52] = {0}; + for (int i = 0; i < A.size(); i ++) { + if (islower(A[i])) { + alpha[A[i] - 'a' + 26] ++; + } else { + alpha[A[i] - 'A'] ++; + } + } + long long int total = 0; + for (int i = 0; i < A.size(); i ++) { + long long localCount = 0; + int size = islower(A[i]) ? A[i] - 'a' + 26 : A[i] - 'A'; + long long int count = (fact(A.size() - i - 1)); + for (int j = 0; j < size; j ++) { + if (alpha[j]) { + alpha[j] --; + localCount = count; + for (int k = 0; k < 52; k ++) { + if (alpha[k]) { + localCount = (localCount * inverseNumber(fact(alpha[k]))) % MOD; + } + } + alpha[j] ++; + total = (total + localCount) % MOD; + } + } + if (islower(A[i])) { + alpha[A[i] - 'a' + 26] --; + } else { + alpha[A[i] - 'A'] --; + } + } + return (total + 1) % MOD; +} From f005d6c81af5d58d9ed2c02e1a5f71a14bb5d6f8 Mon Sep 17 00:00:00 2001 From: mailtokartik1 Date: Sun, 3 May 2020 16:27:12 +0900 Subject: [PATCH 58/59] add alternative solution using recursion for valid ip address --- Strings/ValidIPAddresses.cpp | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Strings/ValidIPAddresses.cpp b/Strings/ValidIPAddresses.cpp index 00a5bd1..f94148a 100644 --- a/Strings/ValidIPAddresses.cpp +++ b/Strings/ValidIPAddresses.cpp @@ -137,3 +137,51 @@ vector Solution::restoreIpAddresses(string A) { return sol; } + +// Alternate solution using recursion + +// Helper function to check validity of a string + +bool checkValidNum(string a) { + return a.size() > 1 && a[0] == '0' ? 0 : stoll(a) >= 0 && stoll(a) <= 255; +} + +// Helper function to check validity of a whole IP + +bool checkValidIP(string a) { + int occurences = count(a.begin(), a.end(), '.'); + if (occurences != 3) { + return 0; + } + int start = 0; + while (a.find('.', start) != string::npos) { + string temp = a.substr(start, a.find('.', start) - start); + if (!checkValidNum(temp)) { + return 0; + } + start = a.find('.', start) + 1; + } + return checkValidNum(a.substr(start)); +} + +// Helper function to generate all possibilities + +void generate (string A, vector &res, int index, string local) { + if (index >= A.size()) { + if (checkValidIP(local)) { + res.push_back(local); + } + return; + } + for (int i = 1; i <= A.size() - index; i ++) { + string temp = A.substr(index, i); + generate(A, res, index + i, local.size() ? local + "." + temp : temp); + } + return; +} +vector Solution::restoreIpAddresses(string A) { + vector res; + generate(A, res, 0, string()); + return res; +} + From 8ec48dfea83de575d164035ecf706ca388021426 Mon Sep 17 00:00:00 2001 From: mailtokartik1 Date: Tue, 5 May 2020 19:19:57 +0900 Subject: [PATCH 59/59] add Stringoholics solution --- Strings/Stringoholics.cpp | 91 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Strings/Stringoholics.cpp diff --git a/Strings/Stringoholics.cpp b/Strings/Stringoholics.cpp new file mode 100644 index 0000000..25f7e80 --- /dev/null +++ b/Strings/Stringoholics.cpp @@ -0,0 +1,91 @@ +#define MOD 1000000007 +typedef long long ll; + +// Helper function to return progressive sum + +ll prod(ll n) { + return ((n * (n + 1))) / 2; +} + +// Function to return the min time taken to get the original string after rotation + +ll timeTaken(string s) { + if (s.size() == 1) { + return 1; + } + while (s.size() % 2 == 0) { + string firstHalf = string(s.begin(), s.begin() + s.size() / 2); + string secondHalf = string(s.begin() + s.size() / 2, s.end()); + if (firstHalf == secondHalf) { + s = firstHalf; + } else break; + } + ll res = 1; + int i = 1; + for (; i < 2 * s.size(); i ++) { + if (prod(i) % s.size() == 0) { + return i; + } + } + return i; +} + +// Create sieve of erastothenes and map prime numbers + +unordered_map makeSieve(int n = 500) { + unordered_map umap; + vector num(n, 1); + for (int i = 2; i * i <= n; i ++) { + for (int j = 2; j * i <= n; j ++) { + num[i * j] = 0; + } + } + for (int i = 2; i < num.size(); i ++) { + if (num[i]) { + umap[i] = 0; + } + } + return umap; +} + +// Seperate the factors of the min. time to get LCM + +void seperateFactors(ll num, unordered_map &umap) { + for (auto it: umap) { + ll exponentVal = 0; + if (num % it.first == 0) { + while (num % it.first == 0) { + exponentVal ++; + num /= it.first; + } + if (exponentVal > it.second) { + umap[it.first] = exponentVal; + } + } + } + if (num != 1) { + umap[num] = 1; + } + return; +} + +// Driver + +int Solution::solve(vector &A) { + ll res = 1; + auto umap = makeSieve(); + for (int i = 0; i < A.size(); i ++) { + long long val = timeTaken(A[i]); + seperateFactors(val, umap); + } + for (auto it: umap) { + ll expVal = 1; + ll maxExp = it.second; + while (maxExp) { + expVal = (expVal * it.first) % MOD; + maxExp --; + } + res = (res * expVal) % MOD; + } + return res; +} \ No newline at end of file