├── Codersbit ├── Try some SQL.cpp ├── Going back to OS.cpp ├── Shortest Path in Simple Graph.cpp ├── MinimiZe.cpp ├── The square game.cpp ├── Delete and Conquer.cpp ├── Array and Prime Divisors.cpp ├── The Sequence game.cpp ├── EZPZ.cpp ├── Smallest Subarray.cpp ├── Three Numbers.cpp ├── Prime Subarrays.cpp ├── Distinct Primes.cpp ├── Scores.cpp └── Another chocolate game.cpp ├── iblogo.png ├── Math ├── Distribute in Circle!.cpp ├── Number Of Open Doors.cpp ├── LargestCoPrimeDivisor.cpp ├── Total Moves For Bishop!.cpp ├── Solve sub-sequences and return OR.cpp ├── Finding Position.cpp ├── Step by Step.cpp ├── Maximum height of the staircase.cpp ├── Consecutive Numbers Sum.cpp ├── Find if two rectangles overlap.cpp ├── Alice and Bob.cpp ├── Is Rectangle.cpp ├── SumOfPairwiseHammingDistance.cpp ├── Find nth Magic Number.cpp ├── FizzBuzz.cpp ├── MATH_BUG01.cpp ├── PowerOfTwoIntegers.cpp ├── Consecutive Number Sum.cpp ├── MATH_BUG02.cpp ├── Day of the week.cpp ├── GreatestCommonDivisor.cpp ├── VerifyPrime.cpp ├── RearrangeArray.cpp ├── Count of divisors for multiple queries.cpp ├── ReverseInteger.cpp ├── 01 String.py ├── Number of Digit One.cpp ├── Divisibility by 8.cpp ├── PalindromeInteger.cpp ├── TrailingZeroesInFactorial.cpp ├── Number of Hosts per Subnet.cpp ├── SortedPermutationRank.cpp ├── SUM OF SQUARES.cpp ├── ALL GCD PAIR.cpp ├── Rectangle Area.cpp ├── Sum of all Submatrices.cpp ├── AllFactors.cpp ├── BinaryRepresentation.cpp ├── Compute nCr % m.cpp ├── Next Similar Number.cpp └── ExcelColumnNumber.cpp ├── Bit Manipulation ├── Trailing Zeroes.cpp ├── MinXORValue.cpp ├── XOR-ing the Subarrays!.cpp ├── DifferentBitsSumPairwise.cpp ├── ReverseBits.cpp ├── SingleNumber.cpp ├── NumberOf1Bits.cpp ├── SUBARRAY OR.cpp └── SingleNumber-II.cpp ├── Stacks and Queues ├── Reverse a stack using recursion.cpp ├── Balanced Parantheses!.cpp ├── Reduce the string.cpp ├── Remove Duplicate Letters.cpp └── ReverseString.cpp ├── Arrays ├── Max Min.cpp ├── Leaders in an array.cpp ├── Pick from both sides!.cpp ├── Max Chunks To Make Sorted 2.cpp ├── Row with maximum number of ones.cpp ├── ARRAY_BUG.cpp ├── Max Chunks To Make Sorted.cpp ├── Sum of adjacent elements is always even.cpp ├── HotelBookingsPossible.cpp ├── Search in a row wise and column wise sorted matrix.cpp ├── Noble Integer.cpp ├── Minimum Absolute Difference.cpp ├── Minimum Size Subarray Sum.cpp ├── Count pairs in array whose sum is divisible by the given number.cpp ├── Toeplitz Matrix.cpp ├── Into Blocks.cpp ├── Perfect Peak of Array.cpp ├── Reverse pairs.cpp ├── Multiple left rotations of the array.cpp ├── Sort array with squares!.cpp ├── MaximumAbsoluteDifference.cpp ├── MergeOverlappingIntervals.cpp ├── MaximumUnsortedSubarray.cpp ├── WaveArray.cpp ├── Maximum Difference.cpp ├── KthRowOfPascalTriangle.cpp ├── Count of Range Sum.cpp ├── PascalTriangleRows.cpp ├── Count of Smaller Numbers After Self.cpp ├── Multiplication of previous and next.cpp ├── Elements which have at-least two greater elements.cpp ├── Alternate positive and negative elements.cpp └── Bob and Queries.cpp ├── Trees ├── Merge two Binary Tree.cpp ├── Reverse Level Order.cpp ├── Equal Tree Partition.cpp ├── Maximum level sum.cpp ├── Leaf nodes from Preorder of a Binary Search Tree.cpp ├── Longest Consecutive Sequence in Binary Tree.cpp ├── Burn a Tree.cpp ├── OrderOfPeopleHeights.cpp ├── K DISTANCE.cpp ├── GREEDY PICK.cpp ├── Vertex Cover Problem.cpp ├── InvertTheBinaryTree.cpp ├── Check for BST with exactly one child of each internal nodes.cpp ├── MaxDepthOfABinaryTree.cpp ├── BinaryTreeFromInorderAndPostorder.cpp ├── Binary Tree Paths.cpp ├── ConstructBinaryTreeFromInorderAndPreorder.cpp ├── Distance between Nodes of BST.cpp ├── BST nodes in a range.cpp └── LeastCommonAncestor.cpp ├── Dynamic Programming ├── Egg Drop Problem!.cpp ├── Maximum Path in Triangle.cpp ├── Tiling With Dominoes.cpp ├── Tiling Problem.cpp ├── UniqueBinarySearchTree-II.cpp ├── WaysToColor3XNBoard.cpp ├── String count.cpp ├── Maximum Size Square Sub-matrix.cpp ├── Subset Sum Problem!.cpp ├── Paint House!.cpp ├── Russian Doll Envelopes.cpp ├── CoinSumInfinite.cpp ├── Another Coin Problem.cpp ├── ALL GCD.cpp ├── Best Time to Buy and Sell Stock with Cooldown.cpp ├── Chain of Pairs.cpp ├── LONGEST COMMON SUBSTRING.cpp ├── Maximise the coins by popping balloons.cpp ├── IntersectingChordsInACircle.cpp ├── PalindromePartitioning-II.cpp ├── TusharsBirthdayParty.cpp ├── Deepu and girlfriend.cpp ├── FlipArray.cpp ├── BestTimeToBuyAndSellStocks-III.cpp ├── 0-1 Knapsack.cpp ├── MaxProductSubarray.cpp ├── Minimum Difference Subsets!.cpp ├── Longest Palindromic Substring.cpp ├── Travelling Saleman Problem.cpp ├── Stairs.cpp ├── RegularExpression-II.cpp ├── Merge elements.cpp ├── REDUCTION.cpp ├── LongestArithmeticProgression.cpp ├── Text Justification.cpp ├── DungeonPrincess.cpp ├── Matrix Chain Multiplication.cpp ├── UniquePathsInAGrid.cpp ├── LargestAreaOfRectanglesWithPremutations.cpp ├── Burst Balloons.cpp ├── Divisor Sequences.cpp ├── BestTimeToBuyAndSellStocks-I.cpp ├── BestTimeToBuyAndSellStocks-II.cpp ├── Increasing Path in Matrix.cpp ├── TusharBirthdayBombs.cpp ├── JumpGameArray.cpp ├── Length of Longest Fibonacci Subsequence.cpp ├── NdigitNumberWithSumS.cpp ├── MaxSumWithoutAdjacentElements.cpp ├── Best Time to Buy and Sell Stock atmost B times.cpp ├── Longest Common Subsequence.cpp ├── Grid Unique Paths II.cpp ├── LongestValidParenthesis.cpp ├── Maximum coin in a tree.cpp ├── LongestIncreasingSubsequence.cpp └── MinSumPathInTriangle.cpp ├── Hashing ├── Subarray Sum Equals K.cpp ├── Subarray with B odd numbers.cpp ├── Invoiced Billing.cpp ├── Pairs With Given Xor.cpp ├── An Increment Problem.cpp ├── Count Right Triangles.cpp ├── Contiguous Array.cpp ├── Two out of Three.cpp ├── Subarray with given XOR.cpp ├── First Repeating element.cpp ├── Subarray with equal occurences!.cpp ├── Subarray with equal occurences.cpp ├── Find pairs in array whose sum is already present.cpp ├── Find if there is a sub-array with 0 sum.cpp ├── Parity Queries.cpp └── Sort an array according to the order defined by another array.cpp ├── Heaps and Maps ├── B Closest Points to Origin.py ├── Profit Maximisation.cpp ├── Merge K sorted arrays!.cpp ├── Task Scheduler.cpp ├── Kth Smallest Element in a Sorted Matrix.cpp ├── Longest Subarray Sum B.cpp ├── MagicianAndChocolates.cpp ├── Activity Selection.cpp ├── Maximum Sum Combinations.cpp ├── Maximum array sum after B negations.cpp ├── Connect ropes with minimum length.cpp ├── Minimum Number of Refueling Stops.cpp ├── K Largest Elements.cpp ├── KEEP SWAPPING.cpp └── NMaxPairCombinations.cpp ├── Time Complexity ├── Cut the rod.cpp ├── String count.cpp ├── Find subsequence.cpp ├── Best Time to Buy and Sell Stock with Transaction Fee.cpp ├── Matrix Permutation.cpp ├── Longest Palindromic Substring.cpp ├── XOR TRIPLETS.cpp ├── Arithmetic Subsequences.cpp ├── Move all zeroes to end of the array.cpp ├── Count Palindromic Subsequences.cpp └── Floyd Warshall Algorithm.cpp ├── Strings ├── INFINITE STRING.cpp ├── Custom Sort String.cpp ├── Remove Consecutive Characters.cpp ├── Minimum Appends for Palindrome!.cpp ├── Minimum Parantheses!.cpp ├── Palindromic Substrings Count.cpp ├── Minimum Characters required to make a String Palindromic.cpp ├── PalindromeInteger.cpp ├── Ugly Pairs.cpp ├── ImplementStrStr.cpp ├── Convert to Palindrome.cpp ├── LengthOfLastWord.cpp ├── EDIBLE STRINGS.cpp └── MultiplyStrings.cpp ├── .gitignore ├── Two Pointers ├── Count of pairs with the given sum II.cpp ├── Pair With Given Difference.cpp ├── Counting Subarrays!.cpp ├── Subarrays with distinct integers!.cpp ├── Count of pairs with the given sum.py ├── Maximum Ones After Modification.cpp ├── Counting Triangles.cpp ├── Count of rectangles with area less than the given number.cpp ├── RemoveDuplicatesFromSortedArrayI.cpp ├── MinimizeTheAbsoluteDifference.cpp ├── IntersectionOfSortedArrays.cpp ├── Good Subarrays.cpp ├── MergeTwoSortedLists.cpp ├── SortByColor.cpp ├── ContainerWithMostWater.cpp ├── DEVICE CROSSOVER.cpp ├── Diffk.cpp └── MergeTwoSortedListsII.cpp ├── Graphs ├── Cycle in Undirected Graph.cpp ├── Cows and snacks.cpp ├── LargestDistanceBetweenNodesOfATree.cpp ├── SmallestSequenceWithGivenPrimes.cpp ├── Permutation Swaps!.cpp ├── Roads and Libraries.cpp ├── WordLadder-I.cpp ├── Path in Directed Graph.cpp └── Path with good nodes!.cpp ├── Binary Search ├── MatrixMedian.cpp ├── Ath Magical Number.cpp ├── Smallest Good Base.cpp ├── ADD OR NOT.cpp ├── Aggressive cows.cpp └── Search in Bitonic Array!.cpp ├── Greedy ├── Another Coin Problem.cpp ├── Largest Permutation.cpp ├── Bulbs.cpp ├── Byes.cpp ├── Disjoint Intervals.cpp ├── MajorityElement.cpp ├── GasStation.cpp └── AssignMiceToHoles.cpp ├── Backtracking ├── GenerateAllParenthesesII.cpp ├── Maximal String.cpp ├── Subset.cpp ├── GrayCode.cpp ├── ModularExpression.cpp └── Combinations.cpp ├── Linked Lists ├── Kth Node From Middle.cpp ├── Sort Binary Linked List.cpp ├── Middle element of linked list.cpp ├── Even Reverse.cpp ├── Reverse Alternate K Nodes.cpp └── ReverseLinkedList.cpp └── Jump └── PrettyPrint.cpp /Codersbit/Try some SQL.cpp: -------------------------------------------------------------------------------- 1 | 14 -------------------------------------------------------------------------------- /Codersbit/Going back to OS.cpp: -------------------------------------------------------------------------------- 1 | 19.6 -------------------------------------------------------------------------------- /Codersbit/Shortest Path in Simple Graph.cpp: -------------------------------------------------------------------------------- 1 | 6 -------------------------------------------------------------------------------- /Codersbit/MinimiZe.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A, int B) { 2 | return __gcd(A,B); 3 | } 4 | -------------------------------------------------------------------------------- /iblogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/black-shadows/InterviewBit-Topicwise-Solutions/HEAD/iblogo.png -------------------------------------------------------------------------------- /Math/Distribute in Circle!.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A, int B, int C) { 2 | 3 | return (A%B+C%B)%B-1; 4 | } -------------------------------------------------------------------------------- /Math/Number Of Open Doors.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A) 2 | { 3 | 4 | return sqrt(A); 5 | 6 | } 7 | -------------------------------------------------------------------------------- /Codersbit/The square game.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A, int B, int C, int D) { 2 | return (abs(C-A-1)*abs(D-B-1)); 3 | } -------------------------------------------------------------------------------- /Math/LargestCoPrimeDivisor.cpp: -------------------------------------------------------------------------------- 1 | int Solution::cpFact(int A, int B) { 2 | while(__gcd(A,B) != 1){ 3 | A = A / __gcd(A,B); 4 | } 5 | return A; 6 | } -------------------------------------------------------------------------------- /Bit Manipulation/Trailing Zeroes.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int a) { 2 | for(int i=0; i<31; i++){ 3 | if((a>>i) & 1){ 4 | return i; 5 | } 6 | } 7 | return 31; 8 | } -------------------------------------------------------------------------------- /Stacks and Queues/Reverse a stack using recursion.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &A) 2 | { 3 | 4 | reverse(A.begin(), A.end()); 5 | 6 | return A; 7 | 8 | } 9 | -------------------------------------------------------------------------------- /Bit Manipulation/MinXORValue.cpp: -------------------------------------------------------------------------------- 1 | int Solution::findMinXor(vector &A) { 2 | sort(A.begin(), A.end()); 3 | int res = A[0]^A[1]; 4 | for(int i=1 ; i &A) 2 | { 3 | int n=A.size(); 4 | int maxm=A[0],minm=A[0]; 5 | for(int i=1;imaxm) maxm=A[i]; 8 | else if(A[i] &arr) 2 | { 3 | 4 | int result = arr[0]; 5 | for (int i = 1; i < arr.size(); i++) 6 | result = __gcd(arr[i], result); 7 | 8 | return result == 1 ? 1 : 0; 9 | } 10 | -------------------------------------------------------------------------------- /Bit Manipulation/XOR-ing the Subarrays!.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A) { 2 | int res=0; 3 | for(int i=0;ival += B->val; 7 | A->left = solve(A->left,B->left); 8 | A->right = solve(A->right,B->right); 9 | return A; 10 | } -------------------------------------------------------------------------------- /Math/Finding Position.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int n) 2 | { 3 | 4 | if(n&(n-1)==0){ 5 | return n; 6 | }else{ 7 | int ans = 1; 8 | while(n!=1){ 9 | ans <<= 1; 10 | n >>= 1; 11 | } 12 | return ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Dynamic Programming/Egg Drop Problem!.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A, int B) { 2 | vectordp(A+1, 0); 3 | int m; 4 | for(m = 0; dp[A] < B; m++) 5 | { 6 | for(int k = A; k>0; k--) 7 | { 8 | dp[k] += dp[k-1] + 1; 9 | } 10 | } 11 | return m; 12 | } -------------------------------------------------------------------------------- /Hashing/Subarray Sum Equals K.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | unordered_map mp; 3 | mp[0]=1; 4 | long long sum=0; 5 | int ans=0; 6 | for(auto &it:A){ 7 | sum+=it; 8 | ans+=mp[sum-B]; 9 | ++mp[sum]; 10 | } 11 | return ans; 12 | } -------------------------------------------------------------------------------- /Math/Step by Step.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A) { 2 | int target = abs(A); 3 | int n = ceil((-1.0 + sqrt(1 + 8.0 * target)) / 2); 4 | int sum = n * (n + 1) / 2; 5 | if (sum == target) 6 | return n; 7 | 8 | int d = sum - target; 9 | if ((d & 1) == 0) 10 | return n; 11 | else 12 | return n + ((n & 1) ? 2 : 1); 13 | } -------------------------------------------------------------------------------- /Hashing/Subarray with B odd numbers.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | int n = A.size(), ans = 0, s = 0; 3 | vector v(n+1, 0); 4 | 5 | for(int i=0; i=0) ans += v[s-B]; 9 | } 10 | 11 | return ans; 12 | } -------------------------------------------------------------------------------- /Heaps and Maps/B Closest Points to Origin.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of list of integers 3 | # @param B : integer 4 | # @return a list of list of integers 5 | def solve(self, points, K): 6 | 7 | points.sort(key = lambda K: K[0]**2 + K[1]**2) 8 | 9 | return points[:K] 10 | -------------------------------------------------------------------------------- /Codersbit/Delete and Conquer.cpp: -------------------------------------------------------------------------------- 1 | int Solution::deleteandconquer(vector &a) { 2 | vector c(1000001,0); 3 | for(int i=0;i > &A) { 2 | int m=A.size(); 3 | int n=A[0].size(); 4 | for(int i=A.size()-2;i>=0;i--) 5 | { 6 | for(int j=0;j0) 7 | { 8 | if(n>=p) 9 | { 10 | ans++; 11 | n-=p; 12 | } 13 | else 14 | break; 15 | p++; 16 | } 17 | return ans; 18 | } 19 | -------------------------------------------------------------------------------- /Arrays/Leaders in an array.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &A) { 2 | vector ans; 3 | int soldier=A[A.size()-1]; 4 | ans.push_back(soldier); 5 | for(int i=A.size()-2;i>=0;i--){ 6 | if(A[i]>soldier){ 7 | ans.push_back(A[i]); 8 | } 9 | soldier=max(soldier,A[i]); 10 | } 11 | return ans; 12 | } -------------------------------------------------------------------------------- /Heaps and Maps/Profit Maximisation.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | priority_queue p; 3 | for(int i:A){ 4 | p.push(i); 5 | } 6 | int ans=0; 7 | for(int i=0;i &B) { 2 | int dp[A+1]; 3 | dp[0] = 0; 4 | for(int i=1;i<=A;i++) 5 | { 6 | int var = B[i-1]; 7 | for(int j = 1;j < i;j++) 8 | { 9 | var = max(dp[i-j] + dp[j], var); 10 | } 11 | dp[i] = var; 12 | } 13 | return dp[A]; 14 | } -------------------------------------------------------------------------------- /Math/Consecutive Numbers Sum.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A) { 2 | while((A&1)==0) A >>= 1; 3 | int ans = 1, d = 3; 4 | while(d*d <= A){ 5 | int e = 0; 6 | while(A%d == 0){ 7 | A /= d; 8 | e++; 9 | } 10 | ans *= e + 1; 11 | d += 2; 12 | } 13 | if(A > 1) 14 | ans <<= 1; 15 | return ans; 16 | } -------------------------------------------------------------------------------- /Hashing/Invoiced Billing.cpp: -------------------------------------------------------------------------------- 1 | int Solution::countMismatchedPayments(vector &A, vector &B, vector &C, vector &D) { 2 | unordered_map mp; 3 | int cnt=0; 4 | for (int i=0;i Solution::solve(vector > &A) { 2 | int k=A.size(),n=A[0].size(); 3 | vector ans; 4 | for(int i=0;i &a, int k) { 2 | int n=a.size(); 3 | vector prefix(n,0); 4 | for(int i=0;i=-1){ 8 | ans=max(ans,(l>=0?prefix[l]:0)+prefix[n-1]-prefix[r-1]); 9 | l--,r--; 10 | } 11 | return ans; 12 | } 13 | -------------------------------------------------------------------------------- /Hashing/Pairs With Given Xor.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | unordered_mapm(A.size()); 3 | int ans=0; 4 | for(int i=0;i= G || E >= C) 6 | return false; 7 | 8 | // If one rectangle is above other 9 | if (B >= H || F >= D) 10 | return false; 11 | 12 | return true; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Strings/INFINITE STRING.cpp: -------------------------------------------------------------------------------- 1 | int bc(int n, int k) 2 | { 3 | return n * (n-1) / 2; 4 | } 5 | int Solution::solve(string A) { 6 | const int n = A.length(); 7 | int d = 0, add = 1; 8 | for (int i = 1; i < n; ++i) { 9 | if (A[i] == A[i-1]) 10 | d += add, add++; 11 | else 12 | add = 1; 13 | } 14 | return ((long)n * (n-1) / 2 - d) % 10000000; 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /Math/Alice and Bob.cpp: -------------------------------------------------------------------------------- 1 | int solveit(vector &A) 2 | { 3 | int g=A[0],mx=A[0],n=A.size(); 4 | 5 | for(int x:A) 6 | { 7 | g = __gcd(x,g); 8 | 9 | mx=max(mx,x); 10 | 11 | } 12 | 13 | return (mx/g - n)%2; 14 | 15 | } 16 | 17 | int Solution::solve(vector &A) 18 | { 19 | 20 | return solveit(A); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Math/Is Rectangle.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A, int B, int C, int D) { 2 | map m; 3 | m[A]++; 4 | m[B]++; 5 | m[C]++; 6 | m[D]++; 7 | 8 | if(m.size()==2) 9 | { 10 | for(auto it: m) 11 | { 12 | if(it.second!=2){return 0;} 13 | } 14 | return 1; 15 | } 16 | else 17 | { 18 | return 0; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Two Pointers/Count of pairs with the given sum II.cpp: -------------------------------------------------------------------------------- 1 | int tc=0; 2 | const int mx=1000005; 3 | const int mod=1000000007; 4 | long long dp[mx]; 5 | 6 | void pre(){ 7 | if(tc) 8 | return; 9 | tc=1; 10 | dp[1]=1; 11 | dp[2]=2; 12 | for(int i=3; i &arr) 2 | { 3 | long res = 0, sum1 = 0, sum2 = 0; 4 | vector expect = arr; 5 | sort(expect.begin(), expect.end()); 6 | for (int i = 0; i < arr.size(); ++i) { 7 | sum1 += arr[i]; 8 | sum2 += expect[i]; 9 | if (sum1 == sum2) ++res; 10 | } 11 | return res; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Graphs/Cycle in Undirected Graph.cpp: -------------------------------------------------------------------------------- 1 | int findpar(int x,vector&par){ 2 | while(par[x]!=-1) 3 | x=par[x]; 4 | return x; 5 | } 6 | int Solution::solve(int A, vector > &B) { 7 | vector par(A+1,-1); 8 | for(int i=0;i &A, int B) { 2 | if(A.empty()) 3 | return 0; 4 | sort(A.begin(), A.end()); 5 | 6 | int i=0; 7 | int j=0; 8 | while(i < A.size() && j < A.size()){ 9 | int k = A[j] - A[i]; 10 | if(k == B && i != j) 11 | return 1; 12 | else if(k < B) 13 | j++; 14 | else 15 | i++; 16 | } 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Arrays/Row with maximum number of ones.cpp: -------------------------------------------------------------------------------- 1 | int solveit(vector > &a){ 2 | int n=a.size(); 3 | int ans=0; 4 | int row =0,i,j; 5 | for (i=0,j=n-1; i0;i++){ 6 | while (a[i][j]==1&&j>=0){ 7 | row = i; 8 | j--; 9 | } 10 | } 11 | return row; 12 | } 13 | 14 | int Solution::solve(vector > &A) { 15 | return solveit(A); 16 | 17 | } -------------------------------------------------------------------------------- /Dynamic Programming/UniqueBinarySearchTree-II.cpp: -------------------------------------------------------------------------------- 1 | vector memo; 2 | 3 | unsigned int solve(int N){ 4 | if(memo[N]) return memo[N]; 5 | unsigned int res = 0; 6 | for(int i=0 ; i(A+1); 14 | memo[0] = memo[1] = 1; 15 | return solve(A); 16 | } -------------------------------------------------------------------------------- /Dynamic Programming/WaysToColor3XNBoard.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A) { 2 | long int color2=12; 3 | long int color3=24; 4 | for(int i=2;i<=A;++i){ 5 | long int temp = color3; 6 | color3 = (11 * color3 + 10*color2 ) % 1000000007; 7 | 8 | color2 = ( 5 * temp + 7*color2 ) % 1000000007; 9 | } 10 | long num = (color3 + color2)% 1000000007; 11 | return (int)num; 12 | } 13 | -------------------------------------------------------------------------------- /Time Complexity/String count.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A) { 2 | long long mod = 1000000007; 3 | long long dp[2][A+1]; 4 | dp[0][1] = 1LL; 5 | dp[1][1] = 1LL; 6 | for(int i = 2;i <= A;i++) 7 | { 8 | dp[0][i] = dp[0][i - 1] + dp[1][i - 1]; 9 | dp[0][i] %= mod; 10 | dp[1][i] = dp[0][i - 1] % mod; 11 | dp[1][i] %= mod; 12 | } 13 | return (dp[0][A] + dp[1][A])%mod; 14 | } -------------------------------------------------------------------------------- /Arrays/ARRAY_BUG.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/array_bug/ 2 | 3 | vector Solution::rotateArray(vector &A, int B) { 4 | vector ret; 5 | int j = 0; 6 | B = B%(A.size()); 7 | for (int i = 0; i < A.size(); i++) { 8 | if((i+B) < A.size()){ 9 | ret.push_back(A[i + B]); 10 | } 11 | else{ 12 | ret.push_back(A[j]); 13 | j++; 14 | } 15 | 16 | } 17 | return ret; 18 | } 19 | -------------------------------------------------------------------------------- /Dynamic Programming/String count.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int A) { 2 | long long mod = 1000000007; 3 | long long dp[2][A+1]; 4 | dp[0][1] = 1LL; 5 | dp[1][1] = 1LL; 6 | for(int i = 2;i <= A;i++) 7 | { 8 | dp[0][i] = dp[0][i - 1] + dp[1][i - 1]; 9 | dp[0][i] %= mod; 10 | dp[1][i] = dp[0][i - 1] % mod; 11 | dp[1][i] %= mod; 12 | } 13 | return (dp[0][A] + dp[1][A])%mod; 14 | } -------------------------------------------------------------------------------- /Math/SumOfPairwiseHammingDistance.cpp: -------------------------------------------------------------------------------- 1 | int Solution::hammingDistance(const vector &nums) { 2 | long long int res=0, size=nums.size(); 3 | for(int i=0,ones ; i<31 ; ++i){ 4 | ones=0; 5 | for(int j=0 ; j &A, int B) { 2 | int i=0,j=0,count=0; 3 | int sum=0; 4 | while(j > &A) { 2 | 3 | int n=A.size(); 4 | int m=A[0].size(); 5 | int ans=1; 6 | for(int i=1;i Solution::solve(vector &A) { 2 | vector res; 3 | for(int i=0;i>= 1; // or n = n/2 17 | } 18 | return answer; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Math/FizzBuzz.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::fizzBuzz(int A) { 2 | vector out; 3 | for(int i=1; i<=A; i++){ 4 | if(i %15 ==0){ 5 | out.push_back("FizzBuzz"); 6 | }else if(i%5 == 0){ 7 | out.push_back("Buzz"); 8 | }else if(i%3 ==0){ 9 | out.push_back("Fizz"); 10 | }else{ 11 | out.push_back(to_string(i)); 12 | } 13 | } 14 | return out; 15 | } -------------------------------------------------------------------------------- /Math/MATH_BUG01.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/math_bug01/ 2 | 3 | // Return 1 if A is prime, else 0 4 | int Solution::isPrime(int A) { 5 | int upperLimit = round(sqrt(A)); 6 | if(A > 1){ 7 | for (int i = 2; i <= upperLimit; i++) { 8 | if (A % i == 0){ 9 | return 0; 10 | } 11 | } 12 | } 13 | else{ 14 | return 0; 15 | } 16 | return 1; 17 | } 18 | -------------------------------------------------------------------------------- /Binary Search/MatrixMedian.cpp: -------------------------------------------------------------------------------- 1 | int Solution::findMedian(vector > &A) { 2 | int n = A.size(); 3 | int m = A[0].size(); 4 | int k = n * m / 2; 5 | 6 | vector A_copy; 7 | for (int i = 0; i < n; i++) 8 | for (int j = 0; j < m; j++) 9 | A_copy.push_back(A[i][j]); 10 | A.clear(); 11 | 12 | std::nth_element(A_copy.begin(), A_copy.begin() + k, A_copy.end()); 13 | return A_copy[k]; 14 | } -------------------------------------------------------------------------------- /Math/PowerOfTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/power-of-two-integers/ 2 | 3 | bool Solution::isPower(int A) { 4 | 5 | if(A == 1){ 6 | return true; 7 | } 8 | 9 | for(int i = 2; i < 32; i++){ 10 | for(int j = 2; j <= pow(INT_MAX, 1.0/i); j++){ 11 | if(pow(j, i) == A){ 12 | return true; 13 | } 14 | } 15 | } 16 | return false; 17 | } 18 | -------------------------------------------------------------------------------- /Arrays/Max Chunks To Make Sorted.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &arr) { 2 | 3 | int res = 0, n = arr.size(); 4 | for (int i = 0; i < n; ++i) { 5 | int cur = arr[i], j = i + 1; 6 | for (; j <= cur; ++j) { 7 | cur = max(cur, arr[j]); 8 | if (cur >= arr.back()) return res + 1; 9 | } 10 | i = j - 1; 11 | ++res; 12 | } 13 | return res; 14 | 15 | } -------------------------------------------------------------------------------- /Arrays/Sum of adjacent elements is always even.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &arr) 2 | { 3 | 4 | int countOdd = 0, n = arr.size(); 5 | 6 | // Stores the new value 7 | for (int i = 0; i < n; i++) 8 | 9 | // Count odd numbers 10 | if (arr[i] % 2) 11 | countOdd++; 12 | 13 | // Return the minimum of even and 14 | // odd count 15 | return min(countOdd, n - countOdd); 16 | 17 | } -------------------------------------------------------------------------------- /Dynamic Programming/Subset Sum Problem!.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | int sum=0; 3 | int n=A.size(); 4 | for(int i=0;isum) return 0; 8 | vector dp(sum+1,0); 9 | dp[0] = 1; 10 | for(int i=0; i>= 1; 4 | int ans = 1, d = 3; 5 | 6 | while (d * d <= A) { 7 | int e = 0; 8 | while (A % d == 0) { 9 | A /= d; 10 | e++; 11 | } 12 | ans *= e + 1; 13 | d += 2; 14 | } 15 | 16 | if (A > 1) ans <<= 1; 17 | return ans; 18 | } -------------------------------------------------------------------------------- /Math/MATH_BUG02.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/math_bug02/ 2 | 3 | vector > Solution::squareSum(int A) { 4 | vector > ans; 5 | for (int a = 1; a * a < A; a++) { 6 | for (int b = a; b * b <= A; b++) { 7 | if (a * a + b * b == A) { 8 | vector newEntry; 9 | newEntry.push_back(a); 10 | newEntry.push_back(b); 11 | ans.push_back(newEntry); 12 | } 13 | } 14 | } 15 | return ans; 16 | } 17 | -------------------------------------------------------------------------------- /Strings/Custom Sort String.cpp: -------------------------------------------------------------------------------- 1 | string Solution::solve(string A, string B) { 2 | int a[26]={0}; 3 | for(auto &it:B) 4 | ++a[it-'a']; 5 | string ans; 6 | for(auto &it:A){ 7 | while(a[it-'a']--) 8 | ans.push_back(it); 9 | } 10 | for(int i=0; i<26; ++i){ 11 | if(a[i]>0){ 12 | while(a[i]--) 13 | ans.push_back(i+'a'); 14 | } 15 | } 16 | return ans; 17 | 18 | } -------------------------------------------------------------------------------- /Two Pointers/Subarrays with distinct integers!.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | 3 | int res = 0; 4 | int K = B; 5 | vector m(A.size() + 1); 6 | for(auto i = 0, j = 0, prefix = 0, cnt = 0; i < A.size(); ++i) { 7 | if (m[A[i]]++ == 0) ++cnt; 8 | if (cnt > K) --m[A[j++]], --cnt, prefix = 0; 9 | while (m[A[j]] > 1) ++prefix, --m[A[j++]]; 10 | if (cnt == K) res += prefix + 1; 11 | } 12 | return res; 13 | } -------------------------------------------------------------------------------- /Arrays/HotelBookingsPossible.cpp: -------------------------------------------------------------------------------- 1 | bool Solution::hotel(vector &arrive, vector &depart, int K) { 2 | sort(arrive.begin(),arrive.end()); 3 | sort(depart.begin(),depart.end()); 4 | int i=0,j=0,c=0; 5 | while(iK) 12 | return false; 13 | } 14 | return true; 15 | } -------------------------------------------------------------------------------- /Arrays/Search in a row wise and column wise sorted matrix.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector > &matrix, int target) 2 | { 3 | 4 | int i = 0; 5 | int j = matrix[0].size() - 1; 6 | 7 | while(i < matrix.size() && j >= 0) { 8 | if(matrix[i][j] == target) 9 | return ((i+1) * 1009 + j + 1); 10 | 11 | if(matrix[i][j] < target) 12 | i++; 13 | else 14 | j--; 15 | } 16 | 17 | return -1; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Time Complexity/Find subsequence.cpp: -------------------------------------------------------------------------------- 1 | string Solution::solve(string A, string B) { 2 | int m = A.length(); 3 | int n = B.length(); 4 | int i=0,j=0; 5 | while(i > &A) { 2 | int n=A.size(); 3 | int dp[n+1][3]; 4 | int i,j; 5 | for(i=0;i<=2;i++) 6 | dp[0][i]=0; 7 | for(i=1;i<=n;i++) 8 | { 9 | dp[i][0]=A[i-1][0]+min(dp[i-1][1],dp[i-1][2]); 10 | dp[i][1]=A[i-1][1]+min(dp[i-1][0],dp[i-1][2]); 11 | dp[i][2]=A[i-1][2]+min(dp[i-1][0],dp[i-1][1]); 12 | } 13 | 14 | return min(dp[n][0],min(dp[n][1],dp[n][2])); 15 | } -------------------------------------------------------------------------------- /Heaps and Maps/Task Scheduler.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(string A, int B) { 2 | unordered_map record; 3 | int max_freq = 0; 4 | int max_tasks = 0; 5 | for(auto a : A) { 6 | record[a]++; 7 | max_freq = max(max_freq, record[a]); 8 | } 9 | for (auto task : record) 10 | if (task.second == max_freq) 11 | max_tasks++; 12 | int ans = (max_freq - 1) * (B+1) + max_tasks; 13 | return ans > A.size() ? ans : A.size(); 14 | } -------------------------------------------------------------------------------- /Codersbit/Array and Prime Divisors.cpp: -------------------------------------------------------------------------------- 1 | bool isprime(int n){ 2 | if(n==1){ 3 | return false; 4 | } 5 | for(int i=2;i<=sqrt(n);i++){ 6 | if(n%i==0){ 7 | return false; 8 | } 9 | } 10 | return true; 11 | } 12 | 13 | int Solution::solve(vector &A, int B) { 14 | int n = A.size(),ans=0; 15 | for(int i=0;i &A, vector &B) { 2 | unordered_mapma1,ma2; 3 | 4 | for(int i=0;i &a,int fee){ 2 | int n=a.size(); 3 | int dp[n]; 4 | memset(dp,0,sizeof dp); 5 | int max_prof = dp[0] - a[0] - fee; 6 | for(int i = 1; i &A, int B) { 14 | return solveit(A,B); 15 | } -------------------------------------------------------------------------------- /Dynamic Programming/Russian Doll Envelopes.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector > &A) { 2 | sort(A.begin(), A.end(), [](const vector & p1, const vector & p2){ 3 | return p1[0] == p2[0] ? p1[1] > p2[1] : p1[0] < p2[0]; 4 | }); 5 | vectordp; 6 | for(auto x: A){ 7 | int pos = lower_bound(dp.begin(), dp.end(), x[1]) - dp.begin(); 8 | if(pos == dp.size()) dp.push_back(x[1]); 9 | else dp[pos] = x[1]; 10 | } 11 | return dp.size(); 12 | } -------------------------------------------------------------------------------- /Math/Day of the week.cpp: -------------------------------------------------------------------------------- 1 | int dayofweek(int d, int m, int y) 2 | { 3 | static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; 4 | y -= m < 3; 5 | return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; 6 | } 7 | 8 | string Solution::solve(int A, int B, int C) 9 | { 10 | 11 | int day = dayofweek(A, B, C); 12 | 13 | string data[] = {"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"}; 14 | 15 | return data[day]; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Trees/Reverse Level Order.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(TreeNode* A) { 2 | vector G,i; 3 | queue Q; 4 | TreeNode* root = A; 5 | Q.push(A); 6 | while(!Q.empty()){ 7 | root = Q.front(); 8 | Q.pop(); 9 | G.push_back(root->val); 10 | if(root->right) Q.push(root->right); 11 | if(root->left) Q.push(root->left); 12 | } 13 | for(int j = G.size()-1;j>=0;j--){ 14 | cout< &A) { 2 | int n=A.size(); 3 | if(n==0) 4 | return 0; 5 | unordered_map mp; 6 | int sum=0,ans=0; 7 | mp[0]=-1; 8 | for(int i=0; i Solution::solve(vector &A, vector &B, vector &C) { 2 | vector a(100001,false) , b(100001,false) , c(100001,false); 3 | 4 | for(auto i:A) 5 | a[i]=true; 6 | for(auto i:B) 7 | b[i]=true; 8 | for(auto i:C) 9 | c[i]=true; 10 | 11 | vector res; 12 | for(int i=1;i<100001;i++) 13 | { 14 | if((a[i]+b[i]+c[i]) > 1) 15 | res.push_back(i); 16 | } 17 | return res; 18 | } -------------------------------------------------------------------------------- /Strings/Remove Consecutive Characters.cpp: -------------------------------------------------------------------------------- 1 | string Solution::solve(string A, int B) { 2 | string s; 3 | for(int i=0;i &A, int B) { 4 | 5 | int ways[B+1]; 6 | memset(ways, 0, sizeof(ways)); 7 | 8 | ways[0] = 1; 9 | 10 | for(int i = 0; i < A.size(); i++){ 11 | for(int j = A[i]; j <= B; j++){ 12 | ways[j] = ways[j] + ways[j-A[i]]; 13 | ways[j] = ways[j]%1000007; 14 | } 15 | } 16 | 17 | return ways[B]; 18 | } 19 | -------------------------------------------------------------------------------- /Greedy/Another Coin Problem.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(int n) { 2 | long dp[100]; 3 | for(int i = 0; i < 100; i++) dp[i] = 1000; 4 | dp[0] = 0; 5 | for(int i = 1; i < 100; i++) dp[i] = min(dp[i-1] + 1, dp[i]); 6 | for(int i = 10; i < 100; i++) dp[i] = min(dp[i-10] + 1, dp[i]); 7 | for(int i = 25; i < 100; i++) dp[i] = min(dp[i-25] + 1, dp[i]); 8 | long ans = 0; 9 | while(n > 0) { 10 | ans += dp[(int)(n % 100)]; 11 | n /= 100; 12 | } 13 | return ans; 14 | } 15 | -------------------------------------------------------------------------------- /Arrays/Noble Integer.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A) { 2 | int n = A.size(), ans = -1, i = 0; 3 | 4 | if(!n){ 5 | return ans; 6 | } 7 | 8 | sort(A.begin(), A.end()); 9 | 10 | while(i < n){ 11 | while(i+1 < n && A[i] == A[i+1]){ 12 | i++; 13 | } 14 | 15 | if(n - (i+1) == A[i]){ 16 | ans = 1; 17 | break; 18 | } 19 | 20 | i++; 21 | } 22 | 23 | return ans; 24 | } 25 | -------------------------------------------------------------------------------- /Greedy/Largest Permutation.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &C, int B) { 2 | vector index(C); 3 | for(int i=0;i &arr) 2 | { 3 | 4 | int n = arr.size(); 5 | 6 | sort(arr.begin(), arr.end()); 7 | // Initialize difference as infinite 8 | int diff = INT_MAX; 9 | 10 | // Find the min diff by comparing adjacent 11 | // pairs in sorted array 12 | for (int i=0; i 0) { 10 | ans += dp[(int)(n % 100)]; 11 | n /= 100; 12 | } 13 | return ans; 14 | } 15 | -------------------------------------------------------------------------------- /Trees/Equal Tree Partition.cpp: -------------------------------------------------------------------------------- 1 | long f(TreeNode* x) { 2 | return x?x->val+f(x->left)+f(x->right):0L; 3 | } 4 | long g(TreeNode* x, long s, bool& res) { 5 | if(!x)return 0; 6 | long a = g(x->left, s, res); 7 | long b = g(x->right, s, res); 8 | if(x->left&&a==s)res=true; 9 | if(x->right&&b==s)res=true; 10 | return a+x->val+b; 11 | } 12 | int Solution::solve(TreeNode* A) { 13 | long s = f(A); 14 | if(!A||(s&1))return 0; 15 | bool res=false; 16 | g(A,s/2,res); 17 | return res; 18 | } 19 | -------------------------------------------------------------------------------- /Dynamic Programming/ALL GCD.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A){ 2 | int n=A.size(); 3 | assert(n>=1&&n<=1000); 4 | for(auto &it:A) 5 | assert(it>=1&&it<=1000); 6 | int ans=0; 7 | int vis[1001]={0}; 8 | vector v; 9 | for(int i=0; i& a) { 2 | int n=a.size(); 3 | if(n==0) 4 | return 0; 5 | vector buy(n, 0), sell(n, 0); 6 | buy[0]=-a[0]; 7 | sell[0] = 0; 8 | for(int i=1; i=0 ? sell[i-2]:0)-a[i]); 10 | sell[i]=max(sell[i-1],buy[i-1]+a[i]); 11 | } 12 | return max(buy[n-1], sell[n-1]); 13 | } 14 | 15 | int Solution::solve(vector &A) { 16 | return maxProfit(A); 17 | } -------------------------------------------------------------------------------- /Hashing/Subarray with given XOR.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &a, int k) { 2 | int n = a.size(); 3 | unordered_map map; 4 | map.reserve(n); 5 | int temp, ans = 0, xorpre = a[0]; 6 | if(a[0] == k) 7 | ans = 1; 8 | map[a[0]] = 1; 9 | for(int i=1; i &s,string temp,int a,int n){ 2 | if(a>n) 3 | return; 4 | if(a==0){ 5 | while(n--) 6 | temp+=")"; 7 | s.push_back(temp); 8 | return; 9 | } 10 | temp+='('; 11 | paranthesis(s,temp,a-1,n); 12 | temp[temp.length()-1]=')'; 13 | paranthesis(s,temp,a,n-1); 14 | } 15 | 16 | vector Solution::generateParenthesis(int A) { 17 | vector s; 18 | string temp=""; 19 | paranthesis(s,temp,A,A); 20 | return s; 21 | } 22 | -------------------------------------------------------------------------------- /Dynamic Programming/Chain of Pairs.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector > &a) { 2 | 3 | int n=a.size(); 4 | int dp[n]; 5 | dp[0]=1; 6 | for(int i=1;i a[j][1] && dp[i]<=dp[j]){ 10 | dp[i]=1+dp[j]; 11 | } 12 | } 13 | } 14 | int ans=INT_MIN; 15 | for(int i=0;ians){ 17 | ans=dp[i]; 18 | } 19 | } 20 | return ans; 21 | } 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LONGEST COMMON SUBSTRING.cpp: -------------------------------------------------------------------------------- 1 | int L[1001][10001]; 2 | 3 | int Solution::solve(string A, string B) { 4 | 5 | int maxlen = 0; 6 | for (int i = 1; i <= A.length(); i++) 7 | { 8 | for (int j = 1; j <= B.length(); j++) 9 | { 10 | if(A[i-1] == B[j-1]){ 11 | L[i][j] = L[i-1][j-1]+1; 12 | maxlen = max(maxlen, L[i][j]); 13 | } 14 | else 15 | L[i][j] = 0; 16 | } 17 | } 18 | 19 | return maxlen; 20 | } -------------------------------------------------------------------------------- /Dynamic Programming/Maximise the coins by popping balloons.cpp: -------------------------------------------------------------------------------- 1 | int Solution::maxCoins(vector &A) { 2 | int n=A.size(); 3 | A.insert(A.begin(),1); 4 | A.push_back(1); 5 | vector> dp(n+2,vector(n+2,0)); 6 | for(int len=1;len<=n;len++){ 7 | for(int i=1;i<=n-len+1;i++){ 8 | int j=i+len-1; 9 | for(int k=i;k<=j;k++){ 10 | dp[i][j]=max(dp[i][j],dp[i][k-1]+A[i-1]*A[k]*A[j+1]+dp[k+1][j]); 11 | } 12 | } 13 | } 14 | return dp[1][n]; 15 | } 16 | -------------------------------------------------------------------------------- /Strings/Minimum Appends for Palindrome!.cpp: -------------------------------------------------------------------------------- 1 | int palindrome(string s) 2 | { 3 | 4 | for(int i=0;i &nums, int s) 2 | { 3 | 4 | int l=0,r=-1,sum=0,res=INT_MAX,len=nums.size(); 5 | if(nums.empty()) return 0; 6 | while(r=s) 9 | { 10 | res=min(res,r-l+1); 11 | sum-=nums[l]; 12 | l++; 13 | } 14 | else 15 | { 16 | r++; 17 | if(r > &A, int B) { 2 | int n=A.size(); 3 | int m=A[0].size(); 4 | priority_queue q; 5 | for(int i=0;is; 7 | for(i=0;i>1; 7 | long long temp=m/A+m/B-m/ab; 8 | if(temp>=N){ 9 | ans=m; 10 | r=m-1; 11 | } 12 | else 13 | l=m+1; 14 | } 15 | return (int)(ans%mod); 16 | } 17 | 18 | int Solution::solve(int A, int B, int C) { 19 | return solveit(A,B,C); 20 | } 21 | -------------------------------------------------------------------------------- /Greedy/Bulbs.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/bulbs/ 2 | 3 | int Solution::bulbs(vector &A) { 4 | 5 | int count = 0; 6 | int orig = 1; 7 | 8 | for(int i = 0; i < A.size(); i++){ 9 | if(A[i] == 0){ 10 | if(orig == 1){ 11 | count++; 12 | orig = 0; 13 | } 14 | } 15 | else{ 16 | if(orig == 0){ 17 | count++; 18 | orig = 1; 19 | } 20 | } 21 | } 22 | 23 | return count; 24 | } 25 | -------------------------------------------------------------------------------- /Math/GreatestCommonDivisor.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/greatest-common-divisor/ 2 | 3 | int Solution::gcd(int A, int B) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | while(A != 0){ 10 | int temp = B; 11 | B = A; 12 | A = temp%A; 13 | } 14 | 15 | return B; 16 | } 17 | -------------------------------------------------------------------------------- /Dynamic Programming/IntersectingChordsInACircle.cpp: -------------------------------------------------------------------------------- 1 | int Solution::chordCnt(int n){ 2 | long long int dp[n+1]; 3 | // if(n%2!=0) return 0; 4 | if(n==0||n==1) 5 | return 1; 6 | else if(n==2) 7 | return 2; 8 | else if(n>2){ 9 | dp[0]=1; 10 | dp[1]=1; 11 | dp[2]=2; 12 | for(int i=3;i<=n;i++){ 13 | dp[i]=0; 14 | for(int k=0;k &A) { 2 | 3 | vector v(A); 4 | unordered_set s; 5 | 6 | sort(A.begin(),A.end()); 7 | int num,temp=0; 8 | for(int i=0;i s; 5 | string ans; 6 | char temp; 7 | for(int i=0; ival, sz,sum; 4 | queue q; 5 | q.push(A); 6 | TreeNode* p; 7 | 8 | while(!q.empty()){ 9 | sz=q.size(); 10 | sum=0; 11 | while(sz--){ 12 | p=q.front(); 13 | sum+=(p->val); 14 | q.pop(); 15 | if(p->left) q.push(p->left); 16 | if(p->right) q.push(p->right); 17 | } 18 | ans = max(sum,ans); 19 | } 20 | 21 | return ans; 22 | } 23 | -------------------------------------------------------------------------------- /Arrays/Count pairs in array whose sum is divisible by the given number.cpp: -------------------------------------------------------------------------------- 1 | int mod = 1000000007; 2 | 3 | int Solution::solve(vector &a, int k) 4 | { 5 | long long int n = a.size(); 6 | long long int m[k]; 7 | for(int i=0; i v(n+1,INT_MAX); 12 | v[n]=-1; 13 | for(i=n-1;i>=0;i--){ 14 | for(j=i;j>& matrix) { 2 | int n=matrix.size(); 3 | int m=matrix[0].size(); 4 | if(n<=1||m<=1) 5 | return true; 6 | for(int i=0; i > &A) { 18 | if(isToeplitzMatrix(A)) 19 | return 1; 20 | return 0; 21 | } -------------------------------------------------------------------------------- /Strings/Palindromic Substrings Count.cpp: -------------------------------------------------------------------------------- 1 | int countSubstrings(string s) { 2 | int ans=0; 3 | int n=s.size(); 4 | for(int i=0; i=0; ++k,--j) 6 | if(s[k]==s[j]) 7 | ++ans; 8 | else 9 | break; 10 | for(int k=i,j=i-1; k=0; ++k,--j) 11 | if(s[k]==s[j]) 12 | ++ans; 13 | else 14 | break; 15 | } 16 | return ans; 17 | } 18 | 19 | int Solution::solve(string A) { 20 | return countSubstrings(A); 21 | } -------------------------------------------------------------------------------- /Greedy/Byes.cpp: -------------------------------------------------------------------------------- 1 | int numZeroes(long long v) { 2 | if (v == 0) return 0; 3 | return 64 - __builtin_clzll(v) - __builtin_popcountll(v); 4 | } 5 | 6 | int Solution::solve(int lowerBound, int numberOfByes) { 7 | if (numberOfByes > 0) { 8 | lowerBound = max(lowerBound, 2); 9 | } 10 | lowerBound --; 11 | while (numZeroes(lowerBound) < numberOfByes) { 12 | lowerBound += (lowerBound & (-lowerBound)); 13 | } 14 | for (long long v = 1; numZeroes(lowerBound) > numberOfByes; v <<= 1) { 15 | lowerBound |= v; 16 | } 17 | return lowerBound+1; 18 | } 19 | -------------------------------------------------------------------------------- /Trees/Leaf nodes from Preorder of a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | #define pb emplace_back 2 | 3 | vector Solution::solve(vector &A) { 4 | int n = A.size(); 5 | stack st; 6 | vector ans; 7 | for (int i=0;iA[i+1]) {st.push(A[i]);} 10 | else{ 11 | while (!st.empty()){ 12 | if (A[i+1]>st.top()) {st.pop(); f=1;} 13 | else {break;} 14 | } 15 | if (f==1) {ans.pb(A[i]);} 16 | } 17 | } 18 | ans.pb(A[n-1]); 19 | return ans; 20 | } -------------------------------------------------------------------------------- /Graphs/Cows and snacks.cpp: -------------------------------------------------------------------------------- 1 | int dsu[100001]; 2 | int find(int x) 3 | { 4 | while(x!=dsu[x]) 5 | { 6 | dsu[x]=dsu[dsu[x]]; 7 | x=dsu[x]; 8 | } 9 | return x; 10 | } 11 | 12 | int solveit(int A,vector > &B) 13 | { 14 | int ans=0; 15 | for(int i=0;i<=A;i++) 16 | dsu[i]=i; 17 | for(auto i:B) 18 | if(find(i[0])==find(i[1])) 19 | ans++; 20 | else 21 | dsu[find(i[0])]=find(i[1]); 22 | return ans; 23 | } 24 | int Solution::solve(int A, vector > &B) { 25 | return solveit(A,B); 26 | } -------------------------------------------------------------------------------- /Linked Lists/Kth Node From Middle.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(ListNode* A, int B) { 2 | if(!A) 3 | return -1; 4 | ListNode* f = A, *s = A, *mid = NULL; 5 | int k = 0; 6 | while(f && f->next) 7 | { 8 | k++; 9 | s = s->next; 10 | f = f->next->next; 11 | } 12 | if(B > k) 13 | return -1; 14 | mid = s; 15 | f = A, s = A; 16 | for(int i = 0; i < B; i++) 17 | { 18 | f = f->next; 19 | } 20 | while(f != mid) 21 | { 22 | s = s->next; 23 | f = f->next; 24 | } 25 | return s->val; 26 | } 27 | -------------------------------------------------------------------------------- /Jump/PrettyPrint.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/prettyprint/ 2 | 3 | vector > Solution::prettyPrint(int A) { 4 | int size, temp, limit, i, j; 5 | 6 | size = 2*A-1; 7 | limit = size; 8 | temp = 0; 9 | 10 | vector > mat(size, vector(size)); 11 | 12 | while(A > 0){ 13 | for(i = temp; i < limit; i++){ 14 | for(j = temp; j < limit; j++){ 15 | mat[i][j] = A; 16 | } 17 | } 18 | A--; 19 | limit--; 20 | temp++; 21 | } 22 | 23 | return mat; 24 | } 25 | -------------------------------------------------------------------------------- /Bit Manipulation/DifferentBitsSumPairwise.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/different-bits-sum-pairwise/ 2 | 3 | #define mod 1000000007 4 | 5 | int Solution::cntBits(vector &A) { 6 | 7 | long long int ans = 0; 8 | int count; 9 | 10 | for(int i = 0; i < 31; i++){ 11 | count = 0; 12 | for(int j = 0; j < A.size(); j++){ 13 | if(A[j] & (1 << i)){ 14 | count++; 15 | } 16 | } 17 | ans = ans + (2*count*(A.size()-count)); 18 | ans = ans%mod; 19 | } 20 | 21 | return (int)ans; 22 | } 23 | -------------------------------------------------------------------------------- /Dynamic Programming/TusharsBirthdayParty.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(const vector &A, const vector &B, const vector &C) { 2 | vector dp(1001,INT_MAX); 3 | dp[0]=0; 4 | for(int i =0; ival==v+1) 7 | ++out ; 8 | else 9 | out=1 ; 10 | ans=max(ans, out); 11 | dfs(root->left,root->val,out); 12 | dfs(root->right,root->val,out); 13 | } 14 | int longestConsecutive(TreeNode* root) { 15 | if (!root) 16 | return 0; 17 | ans=0; 18 | dfs(root,root->val, 0); 19 | return ans; 20 | } 21 | 22 | int Solution::solve(TreeNode* A) { 23 | return longestConsecutive(A); 24 | } 25 | -------------------------------------------------------------------------------- /Dynamic Programming/Deepu and girlfriend.cpp: -------------------------------------------------------------------------------- 1 | string Solution::solve(int A, vector &B) { 2 | bool game[A+1]; 3 | memset(game,0,sizeof(game)); 4 | for(int i=0;i 0) continue; 7 | while (!res.empty() && res.back() > ch && cnt[res.back() - 'a'] > 0) { 8 | used[res.back() - 'a'] = 0; 9 | res.pop_back(); 10 | } 11 | res.push_back(ch); 12 | } 13 | return res; 14 | } 15 | 16 | string Solution::solve(string A) 17 | { 18 | 19 | return removeDuplicateLetters(A); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Time Complexity/Matrix Permutation.cpp: -------------------------------------------------------------------------------- 1 | string Solution :: solve(vector > &A) 2 | { 3 | int n = A.size(); 4 | string temp = ""; 5 | for (int i = 0 ; i < n ; i++) 6 | { 7 | temp = temp + "-" + to_string(A[0][i]); 8 | } 9 | temp += temp; 10 | for (int i=1; i &a) { 2 | vectorcnt(200005,0); 3 | vectorr(200005,0); 4 | int last=0; 5 | int maxx=0; 6 | int ans=0; 7 | int most=0; 8 | 9 | for(int i = 0;i &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | for(int i = 0; i < A.size(); i++){ 10 | A[i] = A[i] + (A[A[i]]%(A.size()))*A.size(); 11 | } 12 | 13 | for(int i = 0; i < A.size(); i++){ 14 | A[i] = A[i]/A.size(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Hashing/Subarray with equal occurences!.cpp: -------------------------------------------------------------------------------- 1 | #define ll long long 2 | int Solution::solve(vector &A, int B, int C) { 3 | map mp; 4 | ll int b_count=0; 5 | ll int c_count=0; 6 | ll int n=A.size(); 7 | ll int ans=0; 8 | for(ll int i=0;isecond-1)*it->second/2; 21 | } 22 | return ans; 23 | } -------------------------------------------------------------------------------- /Hashing/Subarray with equal occurences.cpp: -------------------------------------------------------------------------------- 1 | #define ll long long 2 | int Solution::solve(vector &A, int B, int C) { 3 | map mp; 4 | ll int b_count=0; 5 | ll int c_count=0; 6 | ll int n=A.size(); 7 | ll int ans=0; 8 | for(ll int i=0;isecond-1)*it->second/2; 21 | } 22 | return ans; 23 | } -------------------------------------------------------------------------------- /Trees/Burn a Tree.cpp: -------------------------------------------------------------------------------- 1 | bool sol(TreeNode*root,int &h,int &ans,int B) 2 | { 3 | if(root==NULL) 4 | return false; 5 | int hl=0,hr=0; 6 | bool lf=sol(root->left,hl,ans,B); 7 | bool rf=sol(root->right,hr,ans,B); 8 | if(!lf&&!rf) 9 | h=1+max(hl,hr); 10 | else 11 | if(lf) 12 | h=hl+1; 13 | else 14 | h=hr+1; 15 | if(B==root->val||lf||rf) 16 | { 17 | ans=max(ans,hl+hr+1); 18 | return true; 19 | } 20 | else 21 | return false; 22 | } 23 | int Solution::solve(TreeNode* A, int B) { 24 | int ans=0,h=0; 25 | sol(A,h,ans,B); 26 | return ans-1; 27 | } 28 | -------------------------------------------------------------------------------- /Dynamic Programming/FlipArray.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(const vector &A) 2 | { 3 | int sum=0; 4 | for(int i=0;idp(temp+1,INT_MAX); 8 | dp[0]=0; 9 | for(int i=0;i=A[i];j--) 12 | { 13 | if(dp[j-A[i]]!=INT_MAX) 14 | { 15 | dp[j]=min(dp[j],dp[j-A[i]]+1); 16 | } 17 | } 18 | } 19 | for(int j=temp;j>=0;j++) 20 | { 21 | if(dp[j]!=INT_MAX) 22 | return dp[j]; 23 | } 24 | 25 | 26 | 27 | } -------------------------------------------------------------------------------- /Strings/Minimum Characters required to make a String Palindromic.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(string A) { 2 | int n = A.size(), match = 1; 3 | 4 | if(n == 0){ 5 | return 0; 6 | } 7 | 8 | for(int i = 1; i < n; i++){ 9 | int start = 0, end = i, pal = 1; 10 | while(start < end){ 11 | if(A[start] != A[end]){ 12 | pal = 0; 13 | break; 14 | } 15 | start++; 16 | end--; 17 | } 18 | 19 | if(pal){ 20 | match = i + 1; 21 | } 22 | } 23 | 24 | return n - match; 25 | } 26 | -------------------------------------------------------------------------------- /Trees/OrderOfPeopleHeights.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::order(vector &A, vector &B) 2 | { 3 | vector result(A.size(),-1); 4 | map htsAndFronts; 5 | for(int i = 0;i::iterator it = htsAndFronts.begin(); 10 | it != htsAndFronts.end(); ++it) 11 | { 12 | int i = 0; 13 | int j = 0; 14 | while(i!=it->second) 15 | { 16 | if(result[j]==-1) 17 | i++; 18 | j++; 19 | } 20 | while(result[j]!=-1) 21 | j++; 22 | result[j] = it->first; 23 | } 24 | return result; 25 | } -------------------------------------------------------------------------------- /Arrays/Perfect Peak of Array.cpp: -------------------------------------------------------------------------------- 1 | int Solution::perfectPeak(vector &A) { 2 | int n=A.size(); 3 | int i=1,l=A[0]; 4 | if(n<3) 5 | return 0; 6 | while(il) 9 | { 10 | l=A[i]; 11 | int j=i+1; 12 | while(j::iterator begin, vector::iterator end) { 2 | if (end - begin <= 1) 3 | return 0; 4 | auto mid = begin + (end - begin) / 2; 5 | int count = sort_and_count(begin, mid) + sort_and_count(mid, end); 6 | for (auto i = begin, j = mid; i != mid; ++i) { 7 | while (j != end and *i > 2L * *j) 8 | ++j; 9 | count += j - mid; 10 | } 11 | inplace_merge(begin, mid, end); 12 | return count; 13 | } 14 | 15 | int Solution::solve(vector &nums) 16 | { 17 | 18 | return sort_and_count(nums.begin(), nums.end()); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Bit Manipulation/ReverseBits.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/reverse-bits/ 2 | 3 | unsigned int Solution::reverse(unsigned int A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | unsigned int num = 0; 9 | int bits = 31; 10 | int i = 0; 11 | while(A){ 12 | num = num + pow(2,31-i)*(A%2); 13 | A = A/2; 14 | i++; 15 | } 16 | 17 | return num; 18 | } 19 | -------------------------------------------------------------------------------- /Linked Lists/Sort Binary Linked List.cpp: -------------------------------------------------------------------------------- 1 | ListNode* Solution::solve(ListNode* head) { 2 | ListNode dummy1(0); 3 | ListNode* zero = &dummy1; 4 | ListNode dummy2(0); 5 | ListNode* one = &dummy2; 6 | 7 | while(head){ 8 | if(head->val == 0){ 9 | zero->next = head; 10 | zero = zero->next; 11 | head = head->next; 12 | } 13 | else if(head->val == 1){ 14 | one->next = head; 15 | one = one->next; 16 | head = head->next; 17 | } 18 | } 19 | one->next = NULL; 20 | zero->next = dummy2.next; 21 | return dummy1.next; 22 | } -------------------------------------------------------------------------------- /Arrays/Multiple left rotations of the array.cpp: -------------------------------------------------------------------------------- 1 | vector leftRotate(vector arr, int n, int k) 2 | { 3 | 4 | vector result; 5 | // Print array after k rotations 6 | for (int i = k; i < k + n; i++) 7 | result.push_back(arr[i%n]); 8 | 9 | return result; 10 | } 11 | 12 | vector > Solution::solve(vector &A, vector &B) 13 | { 14 | 15 | vector > ans; 16 | 17 | for(int i=0; i &A) { 2 | if(!A.size()) return 0; 3 | 4 | int size = A.size(), big, sml; 5 | vector sol(size), sag(size); 6 | 7 | sol[0] = 0; 8 | sml = A[0]; 9 | for(int i=1 ; i-1 ; --i){ 17 | big = max(big, A[i]); 18 | sag[i] = max(sag[i+1], big - A[i]); 19 | } 20 | 21 | int res = 0; 22 | for(int i=0 ; i &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | if(A.size() == 0){ 9 | return 0; 10 | } 11 | 12 | int number = A[0]; 13 | for(int i = 1; i < A.size(); i++){ 14 | number = number ^ A[i]; 15 | } 16 | 17 | return number; 18 | } 19 | -------------------------------------------------------------------------------- /Codersbit/Smallest Subarray.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | int min=INT_MAX;long sum=A[0]; 3 | int start=0; 4 | if(sum>=B) 5 | { 6 | min=1; 7 | return 1; 8 | } 9 | for(int i=1;i=B && start <=i) 14 | { if((i-start)+1 &A, vector &B, int C) { 2 | int n = A.size(); 3 | 4 | int dp[n+1][C+1]; 5 | 6 | for(int i=0;i<=n;i++){ 7 | dp[i][0] = 0; 8 | } 9 | for(int j=0;j<=C;j++){ 10 | dp[0][j] = 0; 11 | } 12 | 13 | for(int i=1;i<=n;i++){ 14 | for(int j=0;j<=C;j++){ 15 | if(B[i-1] <= j){ 16 | dp[i][j] = max(A[i-1] + dp[i-1][j-B[i-1]], dp[i-1][j]); 17 | } 18 | else{ 19 | dp[i][j] = dp[i-1][j]; 20 | } 21 | } 22 | } 23 | 24 | return dp[n][C]; 25 | } -------------------------------------------------------------------------------- /Graphs/LargestDistanceBetweenNodesOfATree.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A) { 2 | vector res1; 3 | vector res2; 4 | res1.resize(A.size()); 5 | res2.resize(A.size()); 6 | for(int i=A.size()-1;i>0;i--){ 7 | if(res1[A[i]] Solution::solve(vector &A) { 2 | int mx = *max_element(A.begin(), A.end()) + 2; 3 | vector d(mx); 4 | for (int i = 0; i < mx; ++i)d[i]=i; 5 | for (int i = 2; i*i < mx; ++i)if(d[i]==i) { 6 | for (int j = i*i; j < mx; j+=i)d[j]=i; 7 | } 8 | auto res = A; 9 | 10 | for (int i = 0; i < A.size(); ++i) { 11 | int r = 1, x = A[i]; 12 | while(x > 1) { 13 | int p = d[x], c = 0; 14 | while(x%p==0)++c,x/=p; 15 | r *= c + 1; 16 | } 17 | res[i]=r; 18 | } 19 | 20 | return res; 21 | } 22 | -------------------------------------------------------------------------------- /Math/ReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/reverse-integer/ 2 | 3 | int Solution::reverse(int A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | long int sol = 0; 9 | 10 | while(A != 0){ 11 | sol = sol*10 + (A%10); 12 | A = A/10; 13 | } 14 | 15 | if(sol > INT_MAX || sol < INT_MIN){ 16 | return 0; 17 | } 18 | 19 | return (int)sol; 20 | } 21 | -------------------------------------------------------------------------------- /Heaps and Maps/Longest Subarray Sum B.cpp: -------------------------------------------------------------------------------- 1 | int SubarraySumB(vector &A,int B) { 2 | unordered_map um; 3 | int n=A.size(); 4 | int sum = 0, maxLen = -1; 5 | for (int i = 0; i < n; i++) { 6 | sum += A[i]; 7 | if (sum == B) 8 | maxLen = i + 1; 9 | if (um.find(sum) == um.end()) 10 | um[sum] = i; 11 | if (um.find(sum - B) != um.end()) { 12 | if (maxLen < (i - um[sum - B])) 13 | maxLen = i - um[sum - B]; 14 | } 15 | } 16 | return maxLen; 17 | } 18 | 19 | int Solution::solve(vector &A, int B) { 20 | return SubarraySumB(A,B); 21 | 22 | } -------------------------------------------------------------------------------- /Linked Lists/Middle element of linked list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | int Solution::solve(ListNode* head) 10 | { 11 | 12 | ListNode* slow_ptr = head; 13 | ListNode* fast_ptr = head; 14 | 15 | if (head!=NULL) 16 | { 17 | while (fast_ptr != NULL && fast_ptr->next != NULL) 18 | { 19 | fast_ptr = fast_ptr->next->next; 20 | slow_ptr = slow_ptr->next; 21 | } 22 | return slow_ptr->val; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Greedy/Disjoint Intervals.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector > &A) { 2 | 3 | int i,j,k,n; 4 | n = A.size(); 5 | 6 | pair p[n]; 7 | 8 | int ans=1; 9 | 10 | for(i=0;i pp; 13 | pp.first=A[i][1]; 14 | pp.second=A[i][0]; 15 | p[i]=pp; 16 | 17 | } 18 | 19 | sort(p,p+n); 20 | int last=p[0].first; 21 | 22 | 23 | for(i=1;ilast){ 27 | ans++; 28 | last=p[i].first; 29 | } 30 | } 31 | return ans; 32 | } 33 | -------------------------------------------------------------------------------- /Backtracking/Maximal String.cpp: -------------------------------------------------------------------------------- 1 | int N,b; 2 | string sol,ans; 3 | 4 | void recur(int indx, int left, string &A){ 5 | if(left==0 || indx==N){ 6 | sol = (A>sol ? A : sol); 7 | return; 8 | } 9 | 10 | for(int i=indx+1; iA[indx]){ 12 | swap(A[indx],A[i]); 13 | recur(indx+1,left-1,A); 14 | swap(A[indx],A[i]); 15 | } 16 | } 17 | recur(indx+1,left,A); 18 | } 19 | 20 | string Solution::solve(string A, int B) { 21 | sol.clear(); ans.clear(); 22 | N=A.size(), b=B; 23 | if(N<=1 || B==0) return A; 24 | 25 | recur(0,B,A); 26 | return sol; 27 | } -------------------------------------------------------------------------------- /Codersbit/Three Numbers.cpp: -------------------------------------------------------------------------------- 1 | long long gcd(long long u,long long v){ 2 | if(v==0) return u; 3 | return gcd(v,u%v); 4 | } 5 | long long lcm(long long x,long long y){ 6 | return x*y/gcd(x,y); 7 | } 8 | long long lcm(long long x,long long y,long long z){ 9 | return lcm(lcm(x,y),z); 10 | } 11 | 12 | int Solution::solve(int A, int B, int C, int D) { 13 | D--; 14 | long a1=D/A; 15 | long a2=D/B; 16 | long a3=D/C; 17 | long b1=D/lcm(A,B); 18 | long b2=D/lcm(B,C); 19 | long b3=D/lcm(C,A); 20 | long c; 21 | if(!b1&&!b2&&!b3) c=0; 22 | else c=D/lcm(A,B,C); 23 | 24 | return (a1+a2+a3-b1-b2-b3+c)%1000000007; 25 | } 26 | -------------------------------------------------------------------------------- /Dynamic Programming/MaxProductSubarray.cpp: -------------------------------------------------------------------------------- 1 | int Solution::maxProduct(const vector &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | int minm, maxm; 7 | minm=maxm=A[0]; 8 | int ans=maxm; 9 | for(int i=1;i &A) { 2 | int n=A.size(); 3 | int s=0; 4 | for(int i=0; i=0; i--) 26 | { 27 | if(dp[n][i]) 28 | return( abs(s-2*i) ) ; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Time Complexity/Longest Palindromic Substring.cpp: -------------------------------------------------------------------------------- 1 | string Solution::longestPalindrome(string s) { 2 | if (s.empty()) return ""; 3 | if (s.size() == 1) return s; 4 | int min_start = 0, max_len = 1; 5 | for (int i = 0; i < s.size();) { 6 | if (s.size() - i <= max_len / 2) break; 7 | int j = i, k = i; 8 | while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters. 9 | i = k+1; 10 | while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand. 11 | int new_len = k - j + 1; 12 | if (new_len > max_len) { min_start = j; max_len = new_len; } 13 | } 14 | return s.substr(min_start, max_len); 15 | } -------------------------------------------------------------------------------- /Dynamic Programming/Longest Palindromic Substring.cpp: -------------------------------------------------------------------------------- 1 | string Solution::longestPalindrome(string s) { 2 | if (s.empty()) return ""; 3 | if (s.size() == 1) return s; 4 | int min_start = 0, max_len = 1; 5 | for (int i = 0; i < s.size();) { 6 | if (s.size() - i <= max_len / 2) break; 7 | int j = i, k = i; 8 | while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters. 9 | i = k+1; 10 | while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand. 11 | int new_len = k - j + 1; 12 | if (new_len > max_len) { min_start = j; max_len = new_len; } 13 | } 14 | return s.substr(min_start, max_len); 15 | } -------------------------------------------------------------------------------- /Heaps and Maps/MagicianAndChocolates.cpp: -------------------------------------------------------------------------------- 1 | int check(priority_queue& q, int& A){ 2 | int ans = 0, divi = pow(10, 9) + 7; 3 | 4 | while(A){ 5 | int top = q.top(); 6 | 7 | ans = (ans + (top%divi))%divi; 8 | 9 | q.pop(); 10 | q.push(top/2); 11 | 12 | A--; 13 | } 14 | 15 | return ans; 16 | } 17 | 18 | int Solution::nchoc(int A, vector &B) { 19 | priority_queue q; 20 | 21 | if(B.size() == 0){ 22 | return 0; 23 | } 24 | 25 | for(int i = 0; i < B.size(); i++){ 26 | q.push(B[i]); 27 | } 28 | 29 | return check(q, A); 30 | } 31 | -------------------------------------------------------------------------------- /Codersbit/Prime Subarrays.cpp: -------------------------------------------------------------------------------- 1 | #define ll long long int 2 | const int mn = 1e6 + 5; 3 | 4 | bool p[mn]; 5 | 6 | void sieve() { 7 | if(p[0]) return; 8 | p[0] = p[1] = 1; 9 | for(ll i = 2; i < mn; i += 1) { 10 | if(!p[i]) 11 | for(ll j = i*i; j < mn; j += i) 12 | p[j] = 1; 13 | } 14 | } 15 | 16 | int Solution::solve(vector &A) { 17 | sieve(); 18 | ll sum = 0, ans = 0; 19 | int n = (int)A.size(); 20 | for(int i = 0; i < n; i += 1) { 21 | sum = 0; 22 | for(int j = i; j < n; j += 1) { 23 | sum += A[j]; 24 | ans += !p[sum]; 25 | } 26 | } 27 | return ans; 28 | } -------------------------------------------------------------------------------- /Dynamic Programming/Travelling Saleman Problem.cpp: -------------------------------------------------------------------------------- 1 | int dp[10][(1<<10)]; 2 | int minCost(vector > &B,int A,int u,int mask){ 3 | if(mask==0){ 4 | return B[u][0]; 5 | } 6 | int ans=INT_MAX; 7 | if(dp[u][mask]!=-1)return dp[u][mask]; 8 | for(int i=0;i > &B) { 16 | if(A==1)return 0; 17 | for(int i=0;i<10;i++){ 18 | for(int j=0;j<(1<<10);j++)dp[i][j]=-1; 19 | } 20 | return minCost(B,A,0,((1<>= 1 9 | while i: #这组循环统计整数二进制形式下最开头的1是多少位 10 | mid += 1 11 | i >>= 1 12 | 13 | ans = 0 14 | mid = 1< k: #不是小于k的中心点就找更小的中心点 17 | mid >>= 1 18 | continue 19 | k -= mid 20 | k = mid - k #得到对称位置 21 | ans ^= 1 22 | mid >>= 1 23 | 24 | return ans 25 | -------------------------------------------------------------------------------- /Dynamic Programming/Stairs.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/stairs/ 2 | 3 | int steps(int n){ 4 | if(n < 0){ 5 | return 0; 6 | } 7 | else if(n == 1){ 8 | return 1; 9 | } 10 | else if(n == 2){ 11 | return 2; 12 | } 13 | return steps(n-2) + steps(n-1); 14 | } 15 | 16 | int Solution::climbStairs(int A) { 17 | // Do not write main() function. 18 | // Do not read input, instead use the arguments to the function. 19 | // Do not print the output, instead return values as specified 20 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 21 | 22 | return steps(A); 23 | } 24 | -------------------------------------------------------------------------------- /Codersbit/Distinct Primes.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector& nums) 2 | { 3 | int s = nums.empty() ? 0 : *max_element(nums.begin(), nums.end()); 4 | vector sieve(s + 1, 1), numsMap(s + 1, 0); 5 | for (int n : nums) { 6 | numsMap[n] = 1; 7 | } 8 | int primeDivisorsCount = 0; 9 | for (int i = 2; i <= s; i++) { 10 | if (!sieve[i]) { 11 | continue; 12 | } 13 | bool isPresent = numsMap[i]; 14 | for (int j = 2 * i; j <= s; j += i) { 15 | sieve[j] = 0; 16 | isPresent |= numsMap[j]; 17 | } 18 | primeDivisorsCount += (isPresent) ? 1 : 0; 19 | } 20 | return primeDivisorsCount; 21 | } -------------------------------------------------------------------------------- /Dynamic Programming/RegularExpression-II.cpp: -------------------------------------------------------------------------------- 1 | bool _isMatch(const string &str, int s, const string &pat, int p){ 2 | if(p == pat.length()) return s == str.size(); 3 | 4 | bool star = p < pat.size()-1 and pat[p + 1] == '*'; 5 | bool match = s < str.size() and (pat[p] == '.' or str[s] == pat[p]); 6 | // if theres kleene 7 | if(star){ 8 | // dont match rec, match rec. 9 | return _isMatch(str, s, pat, p+2) 10 | or ( match and _isMatch(str, s+1, pat, p)); 11 | } 12 | return match and _isMatch(str, s+1, pat, p+1); 13 | } 14 | 15 | 16 | int Solution::isMatch(const string str, const string pat) { 17 | return _isMatch(str, 0, pat, 0); 18 | } -------------------------------------------------------------------------------- /Graphs/SmallestSequenceWithGivenPrimes.cpp: -------------------------------------------------------------------------------- 1 | #define pb push_back 2 | vector Solution::solve(int A, int B, int C, int D) 3 | { 4 | vector dp; 5 | dp.pb(1); 6 | int i1 = 0,i2 = 0, i3 = 0; 7 | for(int i = 1; i <= D; i++) 8 | { 9 | 10 | dp.pb(min(dp[i1]*A,min(dp[i2]*B,dp[i3]*C))); 11 | 12 | if(dp[i] == dp[i1]*A) 13 | i1++; 14 | 15 | if(dp[i] == dp[i2]*B) 16 | i2++; 17 | 18 | if(dp[i] == dp[i3]*C) 19 | i3++; 20 | } 21 | vectorans; 22 | for(int i = 1; i < dp.size(); i++) 23 | ans.pb(dp[i]); 24 | 25 | return ans; 26 | 27 | } -------------------------------------------------------------------------------- /Binary Search/Smallest Good Base.cpp: -------------------------------------------------------------------------------- 1 | size_t try_k(size_t n, int k) { 2 | double ord = 1.0 / (k-1); 3 | double root = pow(n, ord); //O(log n) for required floating point precission 4 | size_t a = floor(root); 5 | if (a < 2) return 0; 6 | size_t sum = 1; 7 | for (int i = 0; i < k-1; i++) sum = sum * a + 1; // k-1 time, which is O(log n) 8 | if (sum != n) return 0; 9 | return a; 10 | } 11 | 12 | string Solution::solve(string nstr) 13 | { 14 | 15 | size_t n = stoull(nstr); 16 | for (int k = 63; k >= 3; k--) { 17 | size_t result = try_k(n, k); 18 | if (result > 0) return to_string(result); 19 | } 20 | return to_string(n-1); 21 | } 22 | -------------------------------------------------------------------------------- /Arrays/Sort array with squares!.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &A) { 2 | int s = 0, e = A.size()-1; 3 | vector res; 4 | while(s<=e){ 5 | if(s==e){ res.push_back(A[s]*A[s]); break;} 6 | if(abs(A[s])>abs(A[e])){ 7 | res.push_back(A[s]*A[s]); 8 | s++; 9 | } 10 | else if(abs(A[s])& A, vector temp, int curr, vector >& ans){ 2 | int n = A.size(); 3 | 4 | ans.push_back(temp); 5 | 6 | if(curr == n){ 7 | return; 8 | } 9 | 10 | for(int i = curr; i < n; i++){ 11 | vector temp1(temp); 12 | temp1.push_back(A[i]); 13 | make(A, temp1, i+1, ans); 14 | } 15 | } 16 | 17 | vector > Solution::subsets(vector &A) { 18 | vector > ans; 19 | vector temp; 20 | 21 | if(A.size()){ 22 | sort(A.begin(), A.end()); 23 | } 24 | 25 | make(A, temp, 0, ans); 26 | 27 | return ans; 28 | } 29 | -------------------------------------------------------------------------------- /Trees/K DISTANCE.cpp: -------------------------------------------------------------------------------- 1 | int BIT[200000]; 2 | #define ni 200000 3 | void update(int x, int delta) 4 | { 5 | for(; x <= ni; x += x&-x) 6 | BIT[x] += delta; 7 | } 8 | int query(int x) 9 | { 10 | int sum = 0; 11 | for(; x > 0; x -= x&-x) 12 | sum += BIT[x]; 13 | return sum; 14 | } 15 | #define mod 1000000007 16 | int Solution::solve(TreeNode* A, int B) { 17 | if(A == NULL) 18 | { 19 | return 0; 20 | } 21 | 22 | update(A->val,1); 23 | int val1 = solve(A->left,B); 24 | int val2 = solve(A->right,B); 25 | update(A->val, -1); 26 | return (val1+val2+query(min(A->val+B,100000)) - query(max(A->val-B-1,0)))%mod; 27 | } 28 | -------------------------------------------------------------------------------- /Two Pointers/Maximum Ones After Modification.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | 3 | int count = 0; 4 | int gap = 0; 5 | int r = 0; 6 | int l = 0; 7 | 8 | while(r < A.size()) 9 | { 10 | if(A[r] == 0) 11 | { 12 | count++; 13 | } 14 | if(count > B) 15 | { 16 | if(A[l] == 0) 17 | { 18 | count--; 19 | } 20 | l++; 21 | } 22 | if(count <= B) 23 | { 24 | if(r-l > gap) 25 | { 26 | gap = r-l; 27 | } 28 | } 29 | r++; 30 | } 31 | return gap+1; 32 | } -------------------------------------------------------------------------------- /Dynamic Programming/Merge elements.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A) { 2 | int n = A.size(); 3 | if(n==0) 4 | return 0; 5 | 6 | vector> dp(n,vector(n,0)); 7 | vector sum(n,0); 8 | sum[0] = A[0]; 9 | 10 | for(int i=1;i &A, int B) 2 | { 3 | int N = (int)A.size(); 4 | int K = B; 5 | if((N - 1) % (K - 1)) return -1; 6 | 7 | vector sum(N + 1, 0); 8 | for(int i = 0; i < N; i++) sum[i + 1] = sum[i] + A[i]; 9 | 10 | vector > dp(N + 1, vector(N, 0)); 11 | for(int l = K; l <= N; l++) 12 | for(int i = 0; i + l <= N; i++) 13 | { 14 | dp[l][i] = 10000; 15 | for(int k = 1; k < l; k += K - 1) 16 | dp[l][i] = min(dp[l][i], dp[k][i] + dp[l - k][i + k]); 17 | if((l - 1) % (K - 1) == 0) dp[l][i] += sum[i + l] - sum[i]; 18 | } 19 | return dp[N][0]; 20 | } -------------------------------------------------------------------------------- /Dynamic Programming/LongestArithmeticProgression.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(const vector &a) { 2 | int n=a.size(); 3 | if(n<=2) return n; 4 | int A[n]; 5 | for(int i=0;i0;j--){ 15 | int i=j-1,k=j+1; 16 | while(i>=0&&k 1) 12 | count = count + (before + 1) * i; 13 | else if (current == 0) 14 | count = count + before * i; 15 | else if(current == 1) 16 | count = count + before * i + after + 1; 17 | i *= 10; 18 | } 19 | return count; 20 | } 21 | 22 | int Solution::solve(int A) 23 | { 24 | 25 | return CountOne3(A); 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Trees/GREEDY PICK.cpp: -------------------------------------------------------------------------------- 1 | #define ll long long 2 | #define mod 1000000007 3 | vector robSub(TreeNode* root) { 4 | if (root == NULL) { 5 | return vector(2,0LL); 6 | } 7 | 8 | vector left = robSub(root->left); 9 | vector right = robSub(root->right); 10 | 11 | vector res(2,0LL); 12 | res[0] = max(left[0], left[1]) + max(right[0], right[1]); 13 | res[1] = root->val + left[0] + right[0]; 14 | res[0]%=mod; 15 | res[1]%=mod; 16 | vector ans(2); 17 | ans[0] = res[0]; 18 | ans[1] = res[1]; 19 | return ans; 20 | } 21 | int Solution::solve(TreeNode* A) { 22 | vector res = robSub(A); 23 | return max(res[0], res[1]); 24 | } 25 | -------------------------------------------------------------------------------- /Arrays/MaximumAbsoluteDifference.cpp: -------------------------------------------------------------------------------- 1 | int Solution::maxArr(vector &A) { 2 | int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN, max4 = INT_MIN; 3 | assert(!A.empty()); 4 | int ans = INT_MIN; 5 | int size = A.size(); 6 | for (auto i = 0; i Solution::solve(vector &A, int B) { 2 | sort(A.begin(), A.end()); 3 | int n = A.size(); 4 | int mx = INT_MIN; 5 | int el = 0; 6 | int req = 0; 7 | int i=0,j=0; 8 | while(j ans; 25 | ans.push_back(mx); 26 | ans.push_back(el); 27 | return ans; 28 | } 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Text Justification.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &words, int L) 2 | { 3 | vector res; 4 | for(int i = 0, k, l; i < words.size(); i += k) { 5 | for(k = l = 0; i + k < words.size() and l + words[i+k].size() <= L - k; k++) { 6 | l += words[i+k].size(); 7 | } 8 | string tmp = words[i]; 9 | for(int j = 0; j < k - 1; j++) { 10 | if(i + k >= words.size()) tmp += "#"; 11 | else tmp += string((L - l) / (k - 1) + (j < (L - l) % (k - 1)), '#'); 12 | tmp += words[i+j+1]; 13 | } 14 | tmp += string(L - tmp.size(), '#'); 15 | res.push_back(tmp); 16 | } 17 | return res; 18 | } 19 | -------------------------------------------------------------------------------- /Two Pointers/Counting Triangles.cpp: -------------------------------------------------------------------------------- 1 | int Solution::nTriang(vector &A) { 2 | // 2 pointer solution 3 | 4 | int ans = 0, n = A.size(), num = pow(10, 9) + 7; 5 | 6 | if(!n){ 7 | return ans; 8 | } 9 | 10 | sort(A.begin(), A.end()); 11 | 12 | for(int k = n - 1; k >= 0; k--){ 13 | int i = 0, j = k - 1; 14 | while(i < j){ 15 | long int miniSum = A[i] + A[j], maxi = A[k]; 16 | if(miniSum > maxi){ 17 | ans = (ans + (j - i)%num)%num; 18 | j--; 19 | } 20 | else{ 21 | i++; 22 | } 23 | } 24 | } 25 | 26 | return ans; 27 | } 28 | -------------------------------------------------------------------------------- /Arrays/MergeOverlappingIntervals.cpp: -------------------------------------------------------------------------------- 1 | bool comp(Interval i1, Interval i2) 2 | { 3 | return (i1.start < i2.start); 4 | } 5 | 6 | 7 | vector Solution::merge(vector &A) { 8 | vector ans; 9 | int i=1,f=0; 10 | sort(A.begin(),A.end(),comp); 11 | Interval s; 12 | s.start=A[0].start; 13 | s.end=A[0].end; 14 | while(is.end) 17 | { 18 | ans.push_back(s); 19 | s.start=A[i].start; 20 | s.end=A[i].end; 21 | } 22 | else if(A[i].end>s.end) 23 | s.end=A[i].end; 24 | i++; 25 | 26 | } 27 | ans.push_back(s); 28 | return ans; 29 | } -------------------------------------------------------------------------------- /Graphs/Permutation Swaps!.cpp: -------------------------------------------------------------------------------- 1 | int dp[100001]; 2 | 3 | int root(int x) 4 | { 5 | while(x!=dp[x]) 6 | { 7 | dp[x]=dp[dp[x]]; 8 | x=dp[x]; 9 | } 10 | return x; 11 | } 12 | void unio(int x,int y) 13 | { 14 | dp[root(x)]=dp[root(y)]; 15 | } 16 | int Solution::solve(vector &a, vector &b, vector > &c) { 17 | int i; 18 | for(i=0;i<100001;i++) 19 | dp[i]=i; 20 | int n=a.size(); 21 | int m=c.size(); 22 | for(i=0;i &arr) 2 | { 3 | 4 | int n = arr.size(); 5 | 6 | int ans = 0; 7 | 8 | // Hash to store all element of array 9 | unordered_set s; 10 | for (int i = 0; i < n; i++) 11 | s.insert(arr[i]); 12 | 13 | //bool found = false; 14 | for (int i = 0; i < n; i++) { 15 | for (int j = i + 1; j < n; j++) { 16 | // Check sum already exists or not 17 | if (s.find(arr[i] + arr[j]) != s.end()) { 18 | ans++; 19 | //found = true; 20 | } 21 | } 22 | } 23 | 24 | return ans; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Two Pointers/Count of rectangles with area less than the given number.cpp: -------------------------------------------------------------------------------- 1 | #define mod 1000000007 2 | 3 | int Solution::solve(vector &A, int k) 4 | { 5 | 6 | long long int count = 0; 7 | 8 | int left = 0, right = A.size() - 1; 9 | 10 | while(left <= right) 11 | { 12 | 13 | if(A[left] * A[right] < k) 14 | { 15 | 16 | count = (count + 2*(right - left) + 1)%mod; 17 | 18 | left++; 19 | 20 | } 21 | 22 | else 23 | { 24 | 25 | right--; 26 | 27 | } 28 | 29 | } 30 | 31 | return count; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Dynamic Programming/DungeonPrincess.cpp: -------------------------------------------------------------------------------- 1 | int Solution::calculateMinimumHP(vector > &A) { 2 | // init dimensions 3 | const int I = A.size(); const int J = A[0].size(); 4 | vector< vector > sol(I, vector(J, 0)); 5 | 6 | 7 | // init last row & column 8 | sol[I-1][J-1] = max(1, -A[I-1][J-1]+1); 9 | for(int j=J-2 ; j>-1 ; --j) sol[I-1][j] = max(1, sol[I-1][j+1] - A[I-1][j]); 10 | for(int i=I-2 ; i>-1 ; --i) sol[i][J-1] = max(1, sol[i+1][J-1] - A[i][J-1]); 11 | 12 | for(int i=I-2 ; i>-1 ; --i){ 13 | for(int j=J-2 ; j>-1 ; --j){ 14 | int rite = max(1, sol[i][j+1] - A[i][j]); 15 | int down = max(1, sol[i+1][j] - A[i][j]); 16 | sol[i][j] = min(rite, down); 17 | } 18 | } 19 | return sol[0][0]; 20 | } -------------------------------------------------------------------------------- /Time Complexity/XOR TRIPLETS.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A) 2 | { 3 | int n = A.size(); 4 | long long xorval = 0; 5 | map> m; 6 | pair p; 7 | p.first = -1; 8 | p.second = 1; 9 | m[xorval] = p; 10 | long long ans = 0; 11 | for (int i = 0; i < n; i++) { 12 | xorval ^= A[i]; 13 | if (m.find(xorval) == m.end()) { 14 | pair p; 15 | p.first = i; 16 | p.second = 1; 17 | m[xorval] = p; 18 | } else { 19 | pair p = m[xorval]; 20 | long long x = p.first; 21 | long long y = p.second; 22 | ans += i * y - x - y; 23 | p.first += i; 24 | p.second++; 25 | m[xorval] = p; 26 | } 27 | } 28 | return ans; 29 | } 30 | -------------------------------------------------------------------------------- /Arrays/MaximumUnsortedSubarray.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::subUnsort(vector &A){ 2 | vector ans; 3 | int n = A.size(); 4 | int i = 0, j = n-1; 5 | while(i< n - 1 and A[i] <= A[i + 1]){ 6 | i++; 7 | } 8 | while(j > 0 and A[j] >= A[j - 1]){ 9 | j--; 10 | } 11 | if(i == n - 1){ // if array is already sorted, output -1 12 | ans.push_back(-1); 13 | return ans; 14 | } 15 | int mn = A[i + 1], mx = A[i + 1]; 16 | for(int k = i; k <= j; k++){ 17 | mx = max(mx, A[k]); 18 | mn = min(mn, A[k]); 19 | } 20 | int l = 0, r = n - 1; 21 | while(A[l] <= mn and l <= i){ 22 | l++; 23 | } 24 | while(A[r] >= mx and r >= j){ 25 | r--; 26 | } 27 | ans.push_back(l); 28 | ans.push_back(r); 29 | return ans; 30 | } -------------------------------------------------------------------------------- /Hashing/Find if there is a sub-array with 0 sum.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A) 2 | { 3 | 4 | unordered_map hash; 5 | 6 | long long int sum = 0; 7 | 8 | bool b = false; 9 | 10 | for(int i=0; i &A, vector &B) { 2 | vector >ans; 3 | priority_queue,vector>,greater>> q; 4 | for(int i=0;i= end){ 15 | start = itr.second; 16 | end = itr.first; 17 | ans.push_back(make_pair(start,end)); 18 | } 19 | } 20 | return (int)(ans.size()); 21 | } -------------------------------------------------------------------------------- /Math/Divisibility by 8.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(string str) 2 | { 3 | 4 | int n = str.length(); 5 | 6 | // Empty string 7 | if (n == 0) 8 | return false; 9 | 10 | // If there is single digit 11 | if (n == 1) 12 | return ((str[0]-'0')%8 == 0); 13 | 14 | // If there is double digit 15 | if (n == 2) 16 | return (((str[n-2]-'0')*10 + (str[n-1]-'0'))%8 == 0); 17 | 18 | // If number formed by last three digits is 19 | // divisible by 8. 20 | int last = str[n-1] - '0'; 21 | int second_last = str[n-2] - '0'; 22 | int third_last = str[n-3] - '0'; 23 | 24 | return ((third_last*100 + second_last*10 + last) % 8 == 0); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Trees/Vertex Cover Problem.cpp: -------------------------------------------------------------------------------- 1 | void trav(TreeNode *A) 2 | { 3 | if(A==NULL) 4 | return ; 5 | A->val=0; 6 | trav(A->left); 7 | trav(A->right); 8 | } 9 | int v(TreeNode* A) 10 | { 11 | if(A==NULL) 12 | return 0; 13 | if(A->right==NULL && A->left==NULL) 14 | return 0; 15 | if(A->val!=0) 16 | return A->val; 17 | int s1=1+v(A->left)+v(A->right); 18 | int s2=0; 19 | if(A->left!=NULL) 20 | s2+=1+v(A->left->left)+v(A->left->right); 21 | if(A->right!=NULL) 22 | s2+=1+v(A->right->left)+v(A->right->right); 23 | return A->val=min(s2,s1); 24 | } 25 | int Solution::solve(TreeNode* A) { 26 | int count=0; 27 | trav(A); 28 | return v(A); 29 | } -------------------------------------------------------------------------------- /Dynamic Programming/Matrix Chain Multiplication.cpp: -------------------------------------------------------------------------------- 1 | int MatrixMultiplicationCost(vector &A) { 2 | int n=A.size(); 3 | int m[n][n]; 4 | int i, j, k, L, q; 5 | for (i=1; i=0); 19 | return m[1][n-1]; 20 | } 21 | 22 | int Solution::solve(vector &A) { 23 | return MatrixMultiplicationCost(A); 24 | } -------------------------------------------------------------------------------- /Dynamic Programming/UniquePathsInAGrid.cpp: -------------------------------------------------------------------------------- 1 | int Solution::uniquePathsWithObstacles(vector > &A) { 2 | 3 | vector> dp(A.size(), vector(A[0].size(), 0)); 4 | dp[0][0] = A[0][0] ^ 1; 5 | for(int i = 1; i < A.size(); ++i) { 6 | if(!A[i][0]) dp[i][0] += dp[i-1][0]; 7 | else dp[i][0] = 0; 8 | } 9 | for(int i = 1; i < A[0].size(); ++i) { 10 | if(!A[0][i]) dp[0][i] += dp[0][i-1]; 11 | else dp[0][i] = 0; 12 | } 13 | for(int i = 1; i < A.size(); ++i) 14 | for(int j = 1; j < A[0].size(); ++j) { 15 | if(A[i][j]) continue; 16 | dp[i][j] += dp[i-1][j] + dp[i][j-1]; 17 | } 18 | return dp[(int)A.size() - 1][(int)A[0].size() - 1]; 19 | } 20 | -------------------------------------------------------------------------------- /Dynamic Programming/LargestAreaOfRectanglesWithPremutations.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector > &A) { 2 | int n=A.size(),m=A[0].size(); 3 | int count[n][m]; 4 | for(int i=0;i Solution::solve(vector &A, vector &B, int C) { 2 | sort(A.rbegin(),A.rend()); 3 | sort(B.rbegin(),B.rend()); 4 | vector ans; 5 | priority_queue > > q; 6 | q.push({A[0]+B[0],{0,0}}); 7 | while(C-->0){ 8 | pair > p=q.top();q.pop(); 9 | ans.push_back(p.first); 10 | if(p.second.first+1ev,od; 4 | int count=0; 5 | while(p!=NULL) 6 | { 7 | if(count%2!=0) 8 | ev.push_back(p->val); 9 | else 10 | od.push_back(p->val); 11 | count++; 12 | p=p->next; 13 | } 14 | reverse(ev.begin(),ev.end()); 15 | int i=0,p1=0,p2=0; 16 | p=A; 17 | while(p!=NULL) 18 | { 19 | if(i%2!=0) 20 | { 21 | p->val=ev[p1]; 22 | p1++; 23 | } 24 | else 25 | { 26 | p->val=od[p2]; 27 | p2++; 28 | } 29 | p=p->next; 30 | i++; 31 | } 32 | return A; 33 | } -------------------------------------------------------------------------------- /Math/PalindromeInteger.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/palindrome-integer/ 2 | 3 | bool Solution::isPalindrome(int A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | stringstream ss; 9 | 10 | while(A){ 11 | ss << A%10; 12 | A = A/10; 13 | } 14 | 15 | string B = ss.str(); 16 | 17 | for(int i = 0; i < B.size()/2; i++){ 18 | if(B[i] != B[B.size()-i-1]){ 19 | return false; 20 | } 21 | } 22 | 23 | return true; 24 | } 25 | -------------------------------------------------------------------------------- /Strings/PalindromeInteger.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/palindrome-integer/ 2 | 3 | bool Solution::isPalindrome(int A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | stringstream ss; 9 | 10 | while(A){ 11 | ss << A%10; 12 | A = A/10; 13 | } 14 | 15 | string B = ss.str(); 16 | 17 | for(int i = 0; i < B.size()/2; i++){ 18 | if(B[i] != B[B.size()-i-1]){ 19 | return false; 20 | } 21 | } 22 | 23 | return true; 24 | } 25 | -------------------------------------------------------------------------------- /Strings/Ugly Pairs.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(string A) { 2 | 3 | string odd = ""; 4 | string even = ""; 5 | 6 | for(int i = 0; i < A.length(); i++) 7 | { 8 | if((int)A[i] % 2 == 1) 9 | { 10 | odd = odd + A[i]; 11 | } 12 | else 13 | { 14 | even = even + A[i]; 15 | } 16 | } 17 | 18 | for(int i = 0; i < even.length(); i++) 19 | { 20 | for(int j = 0; j < odd.length(); j++) 21 | { 22 | if((((int)even[i] + 1) != (int)odd[j]) && (((int)even[i] - 1) != (int)odd[j])) 23 | { 24 | return 1; 25 | } 26 | 27 | } 28 | } 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Arrays/WaveArray.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/wave-array/ 2 | 3 | void swap(int &a, int &b){ 4 | int temp = a; 5 | a = b; 6 | b = temp; 7 | } 8 | 9 | vector Solution::wave(vector &A) { 10 | // Do not write main() function. 11 | // Do not read input, instead use the arguments to the function. 12 | // Do not print the output, instead return values as specified 13 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 14 | sort(A.begin(), A.end()); 15 | int size = A.size(); 16 | if(A.size()%2 != 0){ 17 | size = A.size()-1; 18 | } 19 | for(int i = 0; i < size; i=i+2){ 20 | swap(A[i],A[i+1]); 21 | } 22 | 23 | return A; 24 | } 25 | -------------------------------------------------------------------------------- /Trees/InvertTheBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/invert-the-binary-tree/ 2 | 3 | /** 4 | * Definition for binary tree 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | 13 | void invert(TreeNode* root){ 14 | if(root == NULL){ 15 | return; 16 | } 17 | 18 | invert(root->left); 19 | invert(root->right); 20 | 21 | TreeNode* temp = root->left; 22 | root->left = root->right; 23 | root->right = temp; 24 | 25 | } 26 | 27 | TreeNode* Solution::invertTree(TreeNode* root) { 28 | 29 | invert(root); 30 | 31 | return root; 32 | } 33 | -------------------------------------------------------------------------------- /Time Complexity/Arithmetic Subsequences.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A) 2 | { 3 | if(A.empty()) return 0; 4 | vector> dp(A.size());//[index, [difference, count]] 5 | 6 | int res = 0; 7 | for(int i = 0; i < A.size(); ++i){ 8 | for(int j = 0; j < i; ++j){ 9 | if((long)A[i] - (long)A[j] > INT_MAX || (long)A[i] - (long)A[j] < INT_MIN) continue;// do not ignore this step, it will help you save time & space to pass OJ. 10 | int dif = A[i] - A[j]; 11 | dp[i][dif] += 1; 12 | if(dp[j].find(dif) != dp[j].end()){ 13 | dp[i][dif] += dp[j][dif]; 14 | res += dp[j][dif]; 15 | } 16 | } 17 | } 18 | return res; 19 | } 20 | -------------------------------------------------------------------------------- /Dynamic Programming/Burst Balloons.cpp: -------------------------------------------------------------------------------- 1 | int dp[105][105]; 2 | int rec(int i,int j,vector &A){ 3 | if(j-i<=1) 4 | return 0; 5 | auto &ans=dp[i][j]; 6 | if(ans!=-1) 7 | return ans; 8 | ans=0; 9 | for(int k=i+1; k<=j-1; ++k) 10 | ans=max(ans,rec(i,k,A)+rec(k,j,A)+A[i]*A[k]*A[j]); 11 | return ans; 12 | } 13 | int maxCoins(vector& A) { 14 | A.insert(A.begin(), 1); 15 | A.push_back(1); 16 | int n=A.size(); 17 | for(int i=0;i<=n; ++i) 18 | for(int j=0; j<=n; ++j) 19 | dp[i][j]=-1; 20 | int ans=rec(0,n-1,A); 21 | assert(ans<=INT_MAX); 22 | return ans; 23 | } 24 | 25 | int Solution::solve(vector &A) { 26 | return maxCoins(A); 27 | } -------------------------------------------------------------------------------- /Dynamic Programming/Divisor Sequences.cpp: -------------------------------------------------------------------------------- 1 | #define REP(i,n) for (int i = 0; i < n; i++) 2 | #define remax(a,b) a = max(a,b) 3 | #define all(v) v.begin(),v.end() 4 | typedef map mii; 5 | 6 | int dp[10000005]; 7 | mii dpm; 8 | 9 | int f(int x){ 10 | if(x <= 1) return 0; 11 | if(x <= 10000000 and dp[x] != -1) return dp[x]; 12 | if(x > 10000000 and dpm.find(x) != dpm.end()) return dpm[x]; 13 | int res = 1; 14 | for(int d = 2; d*d <= x; d ++){ 15 | if(x%d == 0){ 16 | remax(res,1+f((x-d)/d)); 17 | remax(res,1+f((x-(x/d))/(x/d))); 18 | } 19 | } 20 | if(x <= 10000000) return dp[x] = res; 21 | return dpm[x] = res; 22 | } 23 | 24 | int Solution::solve(int N) { 25 | REP(i,10000005) dp[i] = -1; 26 | return max(f(N),1+f(N-1)); 27 | } -------------------------------------------------------------------------------- /Heaps and Maps/Maximum array sum after B negations.cpp: -------------------------------------------------------------------------------- 1 | bool comparator(int a, int b) 2 | { 3 | return (a& arr, int k) 7 | { 8 | sort(arr.begin(), arr.end(), comparator); 9 | int sum = 0; 10 | int min_value = INT_MAX; 11 | for(auto& x : arr) { 12 | if (k > 0 && x < 0 ) { 13 | x = -x; 14 | k--; 15 | } 16 | min_value = min(min_value,x); 17 | sum+=x; 18 | } 19 | if (k >0) { 20 | k = k%2; 21 | } 22 | if(k>0) { 23 | sum = sum-(2*min_value); 24 | } 25 | return sum; 26 | } 27 | 28 | int Solution::solve(vector &A, int B) 29 | { 30 | 31 | return GetMaxSumAfterNegate(A, B); 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Strings/ImplementStrStr.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/implement-strstr/ 2 | 3 | int Solution::strStr(const string A, const string B) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | if(B.length() == 0) 9 | return -1; 10 | if(A.length() < B.length()) 11 | { 12 | return -1; 13 | } 14 | for(int i=0;i<=(A.length()-B.length());i++) 15 | { 16 | string temp = A.substr(i,B.size()); 17 | if(temp == B) 18 | { 19 | return i; 20 | } 21 | } 22 | return -1; 23 | } -------------------------------------------------------------------------------- /Math/TrailingZeroesInFactorial.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/trailing-zeros-in-factorial/ 2 | 3 | int num(int i){ 4 | int j = 1; 5 | int num = 1; 6 | while(j <= i){ 7 | num = num*5; 8 | j++; 9 | } 10 | return num; 11 | } 12 | 13 | int Solution::trailingZeroes(int A) { 14 | // Do not write main() function. 15 | // Do not read input, instead use the arguments to the function. 16 | // Do not print the output, instead return values as specified 17 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 18 | int count = 0; 19 | int i = 1; 20 | while(num(i) <= A){ 21 | count = count + (A/num(i)); 22 | i++; 23 | } 24 | 25 | return count; 26 | } 27 | -------------------------------------------------------------------------------- /Bit Manipulation/SUBARRAY OR.cpp: -------------------------------------------------------------------------------- 1 | int mod = 1000000007; 2 | 3 | int Solution::solve(vector &A) { 4 | 5 | int n = A.size(); 6 | vector p(n); 7 | vector> v (32,p); 8 | int index=n; 9 | for(int i=0; i<32; i++) { 10 | index=n; 11 | for(int j=n-1; j>=0; j--) { 12 | int t = A[j]&(1<<(i)); 13 | if(t!=0) { 14 | index=j; 15 | } 16 | v[i][j]=index; 17 | } 18 | } 19 | 20 | long long sum=0; 21 | for(int i=0; i<32; i++) { 22 | long long s=0; 23 | for(int j=0; j rev; 9 | 10 | for(int i = 0; i < A.size(); i++){ 11 | rev.push(A[i]); 12 | } 13 | 14 | string ans = ""; 15 | 16 | int height = rev.size(); 17 | 18 | 19 | for(int i = height-1; i >= 0; i--){ 20 | ans = ans + rev.top(); 21 | rev.pop(); 22 | } 23 | 24 | return ans; 25 | } 26 | -------------------------------------------------------------------------------- /Dynamic Programming/BestTimeToBuyAndSellStocks-I.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/best-time-to-buy-and-sell-stocks-i/ 2 | 3 | int Solution::maxProfit(const vector &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | if(A.size() == 0){ 10 | return 0; 11 | } 12 | 13 | int sol = 0, min_p = A[0]; 14 | 15 | for(int i = 1; i < A.size(); i++){ 16 | if(A[i] < min_p){ 17 | min_p = A[i]; 18 | } 19 | sol = max(sol, A[i] - min_p); 20 | } 21 | 22 | return sol; 23 | } 24 | -------------------------------------------------------------------------------- /Heaps and Maps/Connect ropes with minimum length.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &arr) 2 | { 3 | 4 | int n = arr.size(); 5 | 6 | priority_queue, greater > pq(arr.begin(), arr.end()); 7 | 8 | // Initialize result 9 | int res = 0; 10 | 11 | // While size of priority queue is more than 1 12 | while (pq.size() > 1) { 13 | // Extract shortest two ropes from pq 14 | int first = pq.top(); 15 | pq.pop(); 16 | int second = pq.top(); 17 | pq.pop(); 18 | 19 | // Connect the ropes: update result and 20 | // insert the new rope to pq 21 | res += first + second; 22 | pq.push(first + second); 23 | } 24 | 25 | return res; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Linked Lists/Reverse Alternate K Nodes.cpp: -------------------------------------------------------------------------------- 1 | ListNode* Solution::solve(ListNode* A, int B) { 2 | ListNode* start = A; 3 | ListNode* end = A; 4 | int n = 1,c = 1; 5 | while(start && end){ 6 | stack st; 7 | n = B; 8 | if(c % 2 == 1){ 9 | while(n--){ 10 | st.push(end->val); 11 | end = end->next; 12 | } 13 | while(!st.empty()){ 14 | start->val = st.top(); 15 | st.pop(); 16 | start = start->next; 17 | } 18 | } 19 | else{ 20 | while(n--){ 21 | start = start->next; 22 | end = end->next; 23 | } 24 | } 25 | c++; 26 | } 27 | return A; 28 | } -------------------------------------------------------------------------------- /Math/Number of Hosts per Subnet.cpp: -------------------------------------------------------------------------------- 1 | int checkunset(int x){ 2 | int notset=0; 3 | for(int i=0; i<8; ++i) 4 | if(x&(1< H; 14 | while(A[i]!='\0') 15 | { 16 | j=i; 17 | c=0; 18 | while(A[j]!='\0') 19 | { 20 | if(A[i]>A[j]) 21 | c++; 22 | j++; 23 | } 24 | H.push_back(c); 25 | i++; 26 | } 27 | c=0; 28 | i=H.size()-1; 29 | j=0; 30 | while(i>=0) 31 | { 32 | ans+=H[i]*factorial(j); 33 | ans=ans%1000003; 34 | j++; 35 | i--; 36 | } 37 | return ans+1; 38 | } -------------------------------------------------------------------------------- /Binary Search/Aggressive cows.cpp: -------------------------------------------------------------------------------- 1 | typedef unsigned long long ull; 2 | typedef long long int ll; 3 | typedef vector vi; 4 | typedef pair ii; 5 | typedef vector vii; 6 | 7 | int Solution::solve(vector &a, int B) 8 | { 9 | 10 | ll n,c; 11 | n = a.size(); 12 | c = B; 13 | sort(a.begin(),a.end()); 14 | ll i=1,j=1000000001,ans=0,l=0; 15 | while(i<=j) 16 | { 17 | ll mid=((j+i)/2); 18 | int fi=a[0],temp=1; 19 | for(int k=1;k=mid) 22 | temp++,fi=a[k]; 23 | } 24 | if(temp>=1; 10 | } 11 | return r; 12 | } 13 | 14 | int solveit(vector &a){ 15 | int n=a.size(); 16 | long long multiple=modexp(2LL,1LL*(n-1)); 17 | long long ans=0; 18 | for(auto &it:a){ 19 | assert(it>=1&&it<=INT_MAX); 20 | long long p=1LL*it*it; 21 | p%=mod; 22 | long long temp=(1LL*p*multiple)%mod; 23 | ans=(ans+temp); 24 | while(ans>=mod) 25 | ans-=mod; 26 | } 27 | return (int)(ans); 28 | } 29 | 30 | int Solution::solve(vector &A){ 31 | return solveit(A); 32 | } -------------------------------------------------------------------------------- /Math/ALL GCD PAIR.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &A) 2 | { 3 | int n = A.size(); 4 | sort(A.begin(), A.end()); 5 | reverse(A.begin(), A.end()); 6 | vector freq(A[0] + 1, 0); 7 | for (int i=0;i B(n, 0); 14 | int x, l = 0; 15 | 16 | for (int i = 0; i < n; i++) { 17 | if (freq[A[i]] != 0) { 18 | 19 | B[l] = A[i]; 20 | 21 | freq[B[l]]--; 22 | l++; 23 | for (int j = 0; j < l; j++) { 24 | if (i != j) { 25 | 26 | x = __gcd(A[i], B[j]); 27 | 28 | freq[x] -= 2; 29 | } 30 | } 31 | } 32 | } 33 | return B; 34 | } -------------------------------------------------------------------------------- /Two Pointers/RemoveDuplicatesFromSortedArrayI.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/remove-duplicates-from-sorted-array/ 2 | 3 | int Solution::removeDuplicates(vector &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | if(A.size() == 0){ 10 | return A.size(); 11 | } 12 | 13 | int k = 0; 14 | for(int i = 1; i < A.size(); i++){ 15 | if(A[k] != A[i]){ 16 | A[k+1] = A[i]; 17 | k++; 18 | } 19 | } 20 | 21 | A.erase(A.begin()+k+1, A.end()); 22 | return k+1; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Arrays/Maximum Difference.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) 2 | { 3 | 4 | int total = 0; 5 | 6 | for(int i=0; i &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | vector temp(A.size(), 0); 10 | 11 | int buy = A[0], flag = 0, i = 1, max_sell = INT_MIN; 12 | int sol = 0; 13 | while(i < A.size()){ 14 | int diff = A[i] - A[i-1]; 15 | if(diff > 0){ 16 | sol = sol + diff; 17 | } 18 | i++; 19 | } 20 | 21 | return sol; 22 | } 23 | -------------------------------------------------------------------------------- /Math/Rectangle Area.cpp: -------------------------------------------------------------------------------- 1 | bool isOverlap(int A, int B, int C, int D, int E, int F, int G, int H) 2 | { 3 | 4 | // If one rectangle is on left side of other 5 | if (A >= G || E >= C) 6 | return false; 7 | 8 | // If one rectangle is above other 9 | if (B >= H || F >= D) 10 | return false; 11 | 12 | return true; 13 | 14 | } 15 | 16 | int Solution::solve(int A, int B, int C, int D, int E, int F, int G, int H) 17 | { 18 | 19 | if(isOverlap(A, B, C, D, E, F, G, H)) 20 | { 21 | 22 | int areaI = (min(C, G) - max(A, E)) * (min(D, H) - max(B, F)); 23 | 24 | return areaI; 25 | 26 | } 27 | 28 | else 29 | { 30 | 31 | return 0; 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Time Complexity/Move all zeroes to end of the array.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &arr) 2 | { 3 | 4 | int count = 0; // Count of non-zero elements 5 | int n = arr.size(); 6 | // Traverse the array. If element encountered is non- 7 | // zero, then replace the element at index 'count' 8 | // with this element 9 | for (int i = 0; i < n; i++) 10 | if (arr[i] != 0) 11 | arr[count++] = arr[i]; // here count is 12 | // incremented 13 | 14 | // Now all non-zero elements have been shifted to 15 | // front and 'count' is set as index of first 0. 16 | // Make all elements 0 from count to end. 17 | while (count < n) 18 | arr[count++] = 0; 19 | 20 | return arr; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Codersbit/Scores.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &A, vector &B) { 2 | paira[10004]; 3 | int n=A.size(); 4 | int m=B.size(); 5 | for(int i=0;imx-my) 26 | { 27 | mx=x; 28 | my=y; 29 | } 30 | } 31 | vectorans; 32 | ans.push_back(mx); 33 | ans.push_back(my); 34 | return ans; 35 | } -------------------------------------------------------------------------------- /Dynamic Programming/Increasing Path in Matrix.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector > &A) { 2 | int n=A.size(); 3 | int m=A[0].size(); 4 | vector>dp(n,vector(m,-1)); 5 | dp[0][0]=1; 6 | for(int i=1;iA[0][i-1]) 9 | dp[0][i]=1+dp[0][i-1]; 10 | } 11 | for(int i=1;iA[i-1][0]) 14 | dp[i][0]=1+dp[i-1][0]; 15 | } 16 | for(int i=1;iA[i-1][j]||A[i][j]>A[i][j-1]) 23 | dp[i][j]=1+max(dp[i-1][j],dp[i][j-1]); 24 | } 25 | } 26 | if(dp[n-1][m-1]==0) 27 | return -1; 28 | return dp[n-1][m-1]; 29 | } -------------------------------------------------------------------------------- /Dynamic Programming/TusharBirthdayBombs.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(int A, vector &B) { 2 | 3 | vector ans(0); 4 | if(B.size() == 0) 5 | return ans; 6 | vector mn(B.size()); 7 | int curr_min = INT_MAX; 8 | 9 | for(int i=B.size()-1;i>=0;i--) 10 | { 11 | if(B[i]= (rem_shots-1)*mn[j] ) 24 | { 25 | ans.push_back(j); 26 | rem_shots--; 27 | A -= B[j]; 28 | } 29 | else 30 | j++; 31 | } 32 | return ans; 33 | } -------------------------------------------------------------------------------- /Bit Manipulation/SingleNumber-II.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/single-number-ii/ 2 | 3 | int Solution::singleNumber(const vector &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | if(A.size() == 0){ 9 | return 0; 10 | } 11 | 12 | int first = 0, second = 0; 13 | for(int i = 0; i < A.size(); i++){ 14 | second = second | (first & A[i]); 15 | first = first ^ A[i]; 16 | int check = ~(first & second); 17 | first = first & check; 18 | second = second & check; 19 | } 20 | 21 | return first; 22 | } 23 | -------------------------------------------------------------------------------- /Dynamic Programming/JumpGameArray.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/jump-game-array/ 2 | 3 | int Solution::canJump(vector &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | if(A.size() == 0 || A.size() == 1){ 10 | return 1; 11 | } 12 | 13 | vector temp(A.size(), 0); 14 | 15 | int closest = A.size()-1; 16 | 17 | for(int i = temp.size()-2; i >= 0; i--){ 18 | if(A[i] - closest + i >= 0){ 19 | closest = i; 20 | temp[i] = 1; 21 | } 22 | } 23 | 24 | return temp[0]; 25 | } 26 | -------------------------------------------------------------------------------- /Greedy/MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/majority-element/ 2 | 3 | int Solution::majorityElement(const vector &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | int maj = A[0], maj_count = 1; 10 | 11 | for(int i = 1; i < A.size(); i++){ 12 | if(A[i] == maj){ 13 | maj_count++; 14 | } 15 | else{ 16 | maj_count--; 17 | if(maj_count == 0){ 18 | maj = A[i]; 19 | maj_count = 1; 20 | } 21 | } 22 | } 23 | 24 | return maj; 25 | } 26 | -------------------------------------------------------------------------------- /Math/Sum of all Submatrices.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector > &arr) 2 | { 3 | 4 | // Varialbe to store 5 | // the required sum 6 | 7 | int n = arr.size(); 8 | 9 | int sum = 0; 10 | 11 | // Nested loop to find the number 12 | // of submatrices, each number belongs to 13 | for (int i = 0; i < n; i++) 14 | for (int j = 0; j < n; j++) { 15 | 16 | // Number of ways to choose 17 | // from top-left elements 18 | int top_left = (i + 1) * (j + 1); 19 | 20 | // Number of ways to choose 21 | // from bottom-right elements 22 | int bottom_right = (n - i) * (n - j); 23 | sum += (top_left * bottom_right * arr[i][j]); 24 | } 25 | 26 | return sum; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Arrays/KthRowOfPascalTriangle.cpp: -------------------------------------------------------------------------------- 1 | //https://www.interviewbit.com/problems/kth-row-of-pascals-triangle/ 2 | 3 | int C(int line, int i){ 4 | if(i == 0){ 5 | return 1; 6 | } 7 | return C(line, i-1)*(line-i+1)/i; 8 | } 9 | 10 | vector Solution::getRow(int A) { 11 | // Do not write main() function. 12 | // Do not read input, instead use the arguments to the function. 13 | // Do not print the output, instead return values as specified 14 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 15 | 16 | vector sol; 17 | 18 | if(A == 0){ 19 | sol.push_back(1); 20 | return sol; 21 | } 22 | 23 | for(int i = 0; i <= A; i++){ 24 | sol.push_back(C(A, i)); 25 | } 26 | 27 | return sol; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Graphs/Roads and Libraries.cpp: -------------------------------------------------------------------------------- 1 | int Rank[100001],dsu[100001]; 2 | int find(int x) 3 | { 4 | while(x!=dsu[x]) 5 | x=dsu[x]; 6 | return x; 7 | } 8 | void un_ion(int a,int b) 9 | { 10 | int x=find(a),y=find(b); 11 | if(find(a)==find(b)) 12 | return; 13 | if(Rank[x]Rank[y]) 16 | dsu[y]=x; 17 | else 18 | dsu[x]=y,Rank[y]++; 19 | } 20 | int solveit(int A,vector>B,int C,int D) 21 | { 22 | for(int i=0;i<=A;i++) 23 | dsu[i]=i,Rank[i]=1; 24 | for(auto i:B) 25 | un_ion(i[0],i[1]); 26 | 27 | int NOC=0; 28 | for(int i=1;i<=A;i++) 29 | if(dsu[i]==i) 30 | NOC+=1; 31 | return NOC*D + (A-NOC)*min(C,D); 32 | } 33 | 34 | int Solution::solve(int A, vector > &B, int C, int D) 35 | { 36 | 37 | return solveit(A, B, C, D); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Two Pointers/MinimizeTheAbsoluteDifference.cpp: -------------------------------------------------------------------------------- 1 | inline int getmax(int q, int w, int e){ 2 | return max(max(q, w), e); 3 | } 4 | 5 | inline int getmin(int q, int w, int e){ 6 | return min(min(q, w), e); 7 | } 8 | 9 | inline int eval(int q, int w, int e){ 10 | return abs (getmax(q, w, e) - getmin(q, w, e)); 11 | } 12 | 13 | int Solution::solve(vector &Q, vector &W, vector &E) { 14 | int q,w,e; q=w=e=0; 15 | int qs=Q.size(), ws=W.size(), es=E.size(); 16 | int res = eval(Q[0], W[0], E[0]); 17 | while(q &C, vector &D) 2 | { 3 | int n = C.size(); 4 | 5 | vector> stations(n, vector(2)); 6 | 7 | for(int i=0; ipq; 19 | while(1){ 20 | while(p<(int)stations.size()&&stations[p][0]<=nowpos){ 21 | pq.push(stations[p][1]); 22 | p++; 23 | } 24 | if(nowpos>=target)return counter; 25 | if(pq.empty())return -1; 26 | nowpos+=pq.top();pq.pop(); 27 | counter++; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Strings/Convert to Palindrome.cpp: -------------------------------------------------------------------------------- 1 | bool palindrome(string ::iterator itr,string :: iterator itr1) 2 | { 3 | while(itr=0; i--){ 10 | char c = A[i]; 11 | if(isspace(c)){ 12 | if(length != 0){ 13 | return length; 14 | } 15 | else{ 16 | length = 0; 17 | } 18 | } 19 | else{ 20 | length++; 21 | } 22 | } 23 | 24 | return length; 25 | } 26 | -------------------------------------------------------------------------------- /Trees/Check for BST with exactly one child of each internal nodes.cpp: -------------------------------------------------------------------------------- 1 | string Solution::solve(vector &pre) 2 | { 3 | 4 | // Initialize min and max using last two elements 5 | int min, max, size = pre.size(); 6 | if (pre[size-1] > pre[size-2]) 7 | { 8 | max = pre[size-1]; 9 | min = pre[size-2]; 10 | } 11 | else 12 | { 13 | max = pre[size-2]; 14 | min = pre[size-1]; 15 | } 16 | 17 | 18 | // Every element must be either smaller than min or 19 | // greater than max 20 | for (int i=size-3; i>=0; i--) 21 | { 22 | if (pre[i] < min) 23 | min = pre[i]; 24 | else if (pre[i] > max) 25 | max = pre[i]; 26 | else 27 | return "NO"; 28 | } 29 | return "YES"; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Backtracking/GrayCode.cpp: -------------------------------------------------------------------------------- 1 | void solveForResult(vector &toreturn,int A,int curr) 2 | { 3 | if(curr == A) 4 | { 5 | return; 6 | } 7 | int ind = toreturn.size()-1; 8 | for(int i=ind;i>=0;i--) 9 | { 10 | toreturn.push_back((1< Solution::grayCode(int A) { 16 | // Do not write main() function. 17 | // Do not read input, instead use the arguments to the function. 18 | // Do not print the output, instead return values as specified 19 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 20 | vector toreturn; 21 | toreturn.push_back(0); 22 | toreturn.push_back(1); 23 | solveForResult(toreturn,A,1); 24 | 25 | return toreturn; 26 | } 27 | -------------------------------------------------------------------------------- /Dynamic Programming/Length of Longest Fibonacci Subsequence.cpp: -------------------------------------------------------------------------------- 1 | int lenLongestFibSubseq(vector& A) { 2 | int N = A.size(); 3 | unordered_map index; 4 | for (int i = 0; i < N; ++i) 5 | index[A[i]] = i; 6 | 7 | unordered_map longest; 8 | int ans = 0; 9 | for (int k = 0; k < N; ++k) 10 | for (int j = 0; j < k; ++j) { 11 | if (A[k] - A[j] < A[j] && index.count(A[k] - A[j])) { 12 | int i = index[A[k] - A[j]]; 13 | longest[j * N + k] = longest[i * N + j] + 1; 14 | ans = max(ans, longest[j * N + k] + 2); 15 | } 16 | } 17 | 18 | return (ans >= 3) ? ans : 0; 19 | } 20 | 21 | int Solution::solve(vector &A) { 22 | return lenLongestFibSubseq(A); 23 | } -------------------------------------------------------------------------------- /Math/AllFactors.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/all-factors/ 2 | 3 | vector Solution::allFactors(int A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | vector sol; 9 | int count_st = 0; 10 | int count_end = 0; 11 | 12 | for(int i = 1; i <= sqrt(A); i++){ 13 | if(A%i == 0){ 14 | sol.insert(sol.begin()+count_st, i); 15 | count_st++; 16 | if(i != sqrt(A)){ 17 | sol.insert(sol.end()-count_end, A/i); 18 | count_end++; 19 | } 20 | } 21 | } 22 | 23 | return sol; 24 | } 25 | -------------------------------------------------------------------------------- /Hashing/Parity Queries.cpp: -------------------------------------------------------------------------------- 1 | const int maxn=262144+5; 2 | int num[maxn]; 3 | 4 | vector Solution::solve(vector &A, vector &B) 5 | { 6 | 7 | memset(num,0,sizeof(num)); 8 | 9 | int t = A.size(); 10 | 11 | int j = 0; 12 | 13 | vector ans; 14 | 15 | while(t--) 16 | { 17 | long long int num_1 = stoll(B[j]); 18 | long long int num_2=0; 19 | for(int i=0;i<18;i++) 20 | { 21 | num_2=num_2*2+num_1%2; 22 | num_1=num_1/10; 23 | } 24 | if(A[j]=='+') 25 | num[num_2]++; 26 | else if(A[j]=='-') 27 | num[num_2]--; 28 | else if(A[j]=='?') 29 | ans.push_back(num[num_2]); 30 | 31 | j++; 32 | 33 | } 34 | 35 | return ans; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Arrays/Count of Range Sum.cpp: -------------------------------------------------------------------------------- 1 | int mergeSort(vector& sum, int lower, int upper, int low, int high) 2 | { 3 | if(high-low <= 1) return 0; 4 | int mid = (low+high)/2, m = mid, n = mid, count =0; 5 | count =mergeSort(sum,lower,upper,low,mid) +mergeSort(sum,lower,upper,mid,high); 6 | for(int i =low; i< mid; i++) 7 | { 8 | while(m < high && sum[m] - sum[i] < lower) m++; 9 | while(n < high && sum[n] - sum[i] <= upper) n++; 10 | count += n - m; 11 | } 12 | inplace_merge(sum.begin()+low, sum.begin()+mid, sum.begin()+high); 13 | return count; 14 | } 15 | 16 | int Solution::solve(vector &nums, int lower, int upper) 17 | { 18 | 19 | int len = nums.size(); 20 | vector sum(len + 1, 0); 21 | for(int i =0; i< len; i++) sum[i+1] = sum[i]+nums[i]; 22 | return mergeSort(sum, lower, upper, 0, len+1); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Arrays/PascalTriangleRows.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/pascal-triangle-rows/ 2 | 3 | int compute(int line, int index){ 4 | if(index == 0){ 5 | return 1; 6 | } 7 | else{ 8 | return compute(line, index-1)*(line-index+1)/index; 9 | } 10 | } 11 | 12 | vector > Solution::generate(int A) { 13 | // Do not write main() function. 14 | // Do not read input, instead use the arguments to the function. 15 | // Do not print the output, instead return values as specified 16 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 17 | vector > tri(A); 18 | 19 | for(int i = 0; i < A; i++){ 20 | for(int j = 0; j <= i; j++){ 21 | tri[i].push_back(compute(i, j)); 22 | } 23 | } 24 | 25 | return tri; 26 | } 27 | -------------------------------------------------------------------------------- /Dynamic Programming/NdigitNumberWithSumS.cpp: -------------------------------------------------------------------------------- 1 | #define MOD 1000000007 2 | 3 | using ulli = unsigned long long int; 4 | 5 | vector< vector > table; 6 | 7 | // leading zeros leading technology 8 | int leading_zeros(int N, int S){ 9 | if(!N) return !S; 10 | if(table[N][S] != -1) return table[N][S]; 11 | 12 | ulli res = 0; 13 | for(int i=0 ; i<10 ; ++i){ 14 | if(S-i >= 0) res = (res + leading_zeros(N-1, S-i))%MOD; 15 | } 16 | return table[N][S] = res; 17 | } 18 | 19 | // we have to call this since numbers don't have leading zeros 20 | int el_jevab(int N, int S) { 21 | ulli res=0; 22 | for(int i=1 ; i<10 ; ++i){ 23 | if(S-i >= 0) res = (res + leading_zeros(N-1, S-i))%MOD; 24 | } 25 | return res; 26 | } 27 | 28 | int Solution::solve(int N, int S) { 29 | table = vector< vector >(N+1, vector(S+1, -1)); 30 | return el_jevab(N, S); 31 | } -------------------------------------------------------------------------------- /Time Complexity/Count Palindromic Subsequences.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(string A) { 2 | long long mod = 1000000007; 3 | int n; 4 | n = A.length(); 5 | if(n==1) 6 | { 7 | return 1; 8 | } 9 | long long dp[n+1][n+1]; 10 | for(int i=0;i<=n;i++) 11 | { 12 | for(int j=0;j<=n;j++) 13 | { 14 | dp[i][j] = 0; 15 | } 16 | } 17 | for(int i = 0; ileft), 1 + depth(root->right)); 17 | } 18 | 19 | int Solution::maxDepth(TreeNode* A) { 20 | // Do not write main() function. 21 | // Do not read input, instead use the arguments to the function. 22 | // Do not print the output, instead return values as specified 23 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 24 | 25 | return depth(A); 26 | } 27 | -------------------------------------------------------------------------------- /Dynamic Programming/MaxSumWithoutAdjacentElements.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/max-sum-without-adjacent-elements/ 2 | 3 | int Solution::adjacent(vector > &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | 10 | if(A.size() == 0){ 11 | return 0; 12 | } 13 | 14 | int inc = 0, exc = 0; 15 | 16 | for(int i = 0; i < A[0].size(); i++){ 17 | int num = max(A[0][i], A[1][i]); 18 | 19 | int temp = max(exc, inc); 20 | 21 | inc = exc + num; 22 | exc = temp; 23 | } 24 | 25 | 26 | return max(inc, exc); 27 | } 28 | -------------------------------------------------------------------------------- /Greedy/GasStation.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/gas-station/ 2 | 3 | int Solution::canCompleteCircuit(const vector &gas, const vector &cost) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | int fuel = 0, start_i = 0, sum = 0; 10 | 11 | for(int i = 0; i < gas.size(); i++){ 12 | sum = sum + (gas[i] - cost[i]); 13 | fuel = fuel + (gas[i] - cost[i]); 14 | if(fuel < 0){ 15 | fuel = 0; 16 | start_i = i+1; 17 | } 18 | } 19 | 20 | if(sum >= 0){ 21 | return start_i%(gas.size()); 22 | } 23 | 24 | return -1; 25 | } 26 | -------------------------------------------------------------------------------- /Trees/BinaryTreeFromInorderAndPostorder.cpp: -------------------------------------------------------------------------------- 1 | int findIndex(vector& inorder, int i, int j, int val) 2 | { 3 | for (auto b = i; b<=j; ++b) 4 | if (inorder[b] == val) 5 | return b; 6 | } 7 | 8 | TreeNode* makeTree(vector &inorder, vector &postorder, int i, int j, int& p) 9 | { 10 | if (i>j) 11 | return NULL; 12 | TreeNode* node = new TreeNode(postorder[p--]); 13 | if (i==j) 14 | return node; 15 | int in = findIndex(inorder, i, j, node->val); 16 | node->right = makeTree(inorder, postorder, in+1, j, p); 17 | node->left = makeTree(inorder, postorder, i, in-1, p); 18 | return node; 19 | } 20 | TreeNode* Solution::buildTree(vector &inorder, vector &postorder) { 21 | int p = postorder.size()-1; 22 | return inorder.empty() ? NULL : makeTree(inorder, postorder, 0, inorder.size()-1, p); 23 | } -------------------------------------------------------------------------------- /Arrays/Count of Smaller Numbers After Self.cpp: -------------------------------------------------------------------------------- 1 | void merge_sort(vector>::iterator begin, vector>::iterator end, vector &ret) { 2 | if (end - begin <= 1) return; 3 | auto mid = begin + (end - begin) / 2; 4 | merge_sort(begin, mid, ret); 5 | merge_sort(mid, end, ret); 6 | auto r = mid; 7 | for (auto l = begin; l != mid; l++) { // combine 8 | while (r != end && l->first > r->first) r++; 9 | ret[l->second] += r - mid; 10 | } 11 | inplace_merge(begin, mid, end); // inplace merge 12 | } 13 | 14 | vector Solution::solve(vector &nums) 15 | { 16 | 17 | int n = nums.size(); 18 | vector> ps; 19 | vector ret(n, 0); 20 | for (int i = 0; i < n; i++) 21 | ps.push_back(make_pair(nums[i], i)); 22 | merge_sort(ps.begin(), ps.end(), ret); 23 | return ret; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Arrays/Multiplication of previous and next.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &arr) 2 | { 3 | 4 | // Nothing to do when array size is 1 5 | 6 | int n = arr.size(); 7 | 8 | if (n <= 1) 9 | return arr; 10 | 11 | // store current value of arr[0] and update it 12 | int prev = arr[0]; 13 | arr[0] = arr[0] * arr[1]; 14 | 15 | // Update rest of the array elements 16 | for (int i=1; i &A,int l,int r){ 2 | 3 | int pivot=A[r]; 4 | int i=l-1; 5 | 6 | for(int j=l;j<=r;j++){ 7 | 8 | if(A[j] &A,int l,int r, int ind){ 20 | 21 | if(l>r) return ; 22 | int pivot=partition(A,l,r); 23 | 24 | if(pivot < ind) f(A,pivot+1,r,ind); 25 | else if(pivot > ind) f(A,l,pivot-1,ind); 26 | } 27 | 28 | vector Solution::solve(vector &A, int k) { 29 | 30 | int n=A.size(); 31 | f(A,0,n-1,n-k); 32 | vector ans; 33 | for(int i=n-k;i > ans; 12 | 13 | void allBinaryTreepath(TreeNode *root,vector &v){ 14 | if(root==NULL) 15 | return; 16 | if(root->left==NULL&&root->right==NULL){ 17 | v.push_back(root->val); 18 | ans.push_back(v); 19 | v.pop_back(); 20 | return; 21 | } 22 | v.push_back(root->val); 23 | allBinaryTreepath(root->left,v); 24 | allBinaryTreepath(root->right,v); 25 | v.pop_back(); 26 | } 27 | 28 | vector > Solution::solve(TreeNode* A) { 29 | ans.clear(); 30 | vector v; 31 | allBinaryTreepath(A,v); 32 | return ans; 33 | } -------------------------------------------------------------------------------- /Binary Search/Search in Bitonic Array!.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, int B) { 2 | int n=A.size(); 3 | int i; 4 | int start, end; 5 | // finding pivot point; 6 | for(i=0;iA[i+1]) break; 8 | } 9 | if(B == A[i]) return i; 10 | 11 | start=i+1; 12 | end=n-1; 13 | //searching first half 14 | while(start <= end){ 15 | int mid=(start+end)/2; 16 | if(B== A[mid]) return mid; 17 | else if(B &A, vector &B) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | if(A.size() == 0){ 10 | return 0; 11 | } 12 | 13 | sort(A.begin(), A.end()); 14 | sort(B.begin(), B.end()); 15 | 16 | int i = 0, j = 0; 17 | int sol = INT_MIN; 18 | 19 | while(i != A.size()){ 20 | sol = max(abs(A[i]-B[j]), sol); 21 | i++; 22 | j++; 23 | if(j == B.size()){ 24 | j--; 25 | } 26 | } 27 | 28 | return sol; 29 | } 30 | -------------------------------------------------------------------------------- /Strings/EDIBLE STRINGS.cpp: -------------------------------------------------------------------------------- 1 | const int N=100005; 2 | 3 | int p[N]; 4 | int tc=0; 5 | void pre(){ 6 | if(tc) 7 | return; 8 | p[1]=1; 9 | tc=1; 10 | for(int i=4; i='a'&&it<='z'); 26 | assert(A.size()>=1&&A.size()<=100000); 27 | int y=1; 28 | for(int i=1; i& prices,int k) { 2 | if(k==0 || prices.size() == 0) 3 | return 0; 4 | int max_profit = 0; 5 | if(k >= prices.size()/2) { 6 | for(int i = 1;i < prices.size();i++) { 7 | max_profit += max(prices[i] - prices[i-1], 0); 8 | } 9 | return max_profit; 10 | } 11 | vector> dp(k+1, vector(prices.size() + 1, 0)); 12 | 13 | for(int i=1;i<=k;i++) { 14 | int maxDiff = -prices[0]; 15 | for(int j = 2;j <= prices.size();j++) { 16 | dp[i][j] = max(dp[i][j-1], prices[j-1] + maxDiff); 17 | maxDiff = max(maxDiff, dp[i-1][j] - prices[j-1]); 18 | } 19 | } 20 | return dp[k][prices.size()]; 21 | } 22 | 23 | int Solution::solve(vector &A, int B) { 24 | return maxProfit(A,B); 25 | } -------------------------------------------------------------------------------- /Dynamic Programming/Longest Common Subsequence.cpp: -------------------------------------------------------------------------------- 1 | int lcs( string X, string Y, int m, int n ) 2 | { 3 | int L[m+1][n+1]; 4 | int i, j; 5 | 6 | /* Following steps build L[m+1][n+1] in bottom up fashion. Note 7 | that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ 8 | for (i=0; i<=m; i++) 9 | { 10 | for (j=0; j<=n; j++) 11 | { 12 | if (i == 0 || j == 0) 13 | L[i][j] = 0; 14 | 15 | else if (X[i-1] == Y[j-1]) 16 | L[i][j] = L[i-1][j-1] + 1; 17 | 18 | else 19 | L[i][j] = max(L[i-1][j], L[i][j-1]); 20 | } 21 | } 22 | 23 | /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ 24 | return L[m][n]; 25 | } 26 | 27 | 28 | int Solution::solve(string A, string B) 29 | { 30 | 31 | return lcs(A, B, A.length(), B.length()); 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Math/Compute nCr % m.cpp: -------------------------------------------------------------------------------- 1 | // Returns nCr % p 2 | int nCrModp(int n, int r, int p) 3 | { 4 | // The array C is going to store last row of 5 | // pascal triangle at the end. And last entry 6 | // of last row is nCr 7 | int C[r+1]; 8 | memset(C, 0, sizeof(C)); 9 | 10 | C[0] = 1; // Top row of Pascal Triangle 11 | 12 | // One by constructs remaining rows of Pascal 13 | // Triangle from top to bottom 14 | for (int i = 1; i <= n; i++) 15 | { 16 | // Fill entries of current row using previous 17 | // row values 18 | for (int j = min(i, r); j > 0; j--) 19 | 20 | // nCj = (n-1)Cj + (n-1)C(j-1); 21 | C[j] = (C[j] + C[j-1])%p; 22 | } 23 | return C[r]; 24 | } 25 | 26 | int Solution::solve(int A, int B, int C) 27 | { 28 | 29 | return nCrModp(A, B, C); 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Graphs/WordLadder-I.cpp: -------------------------------------------------------------------------------- 1 | struct e{ 2 | string w; // word 3 | int d; //distance 4 | e(string _w, int _d): w(_w), d(_d) {} 5 | }; 6 | 7 | bool neighbor(const string &q, const string &p){ 8 | int diff=0, size=q.size(); 9 | for(int i=0 ; i &dictV) { 18 | unordered_map mark; 19 | queue Q; 20 | 21 | Q.push(e{start, 1}); mark[start] = 1; 22 | while(Q.size()){ 23 | e fro = Q.front(); Q.pop(); //<<--- notice 24 | if(fro.w == end) return fro.d; 25 | 26 | for(const string &word : dictV){ 27 | if(neighbor(fro.w, word) and !mark[word]){ 28 | Q.push(e{word, fro.d + 1}); 29 | mark[word]=1; 30 | } 31 | } 32 | } 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Trees/ConstructBinaryTreeFromInorderAndPreorder.cpp: -------------------------------------------------------------------------------- 1 | int findIndex(vector &inorder, int i, int j, int val) 2 | { 3 | for (auto b = i; b<=j; ++b) 4 | if (inorder[b]==val) 5 | return b; 6 | } 7 | TreeNode* makeTree(vector &preorder, vector &inorder, int i, int j, int& p) 8 | { 9 | if (i>j) 10 | return NULL; 11 | TreeNode* node = new TreeNode(preorder[p++]); 12 | if (i==j) 13 | return node; 14 | int in = findIndex(inorder, i, j, node->val); 15 | node->left = makeTree(preorder, inorder, i, in-1, p); 16 | node->right = makeTree(preorder, inorder, in+1, j, p); 17 | return node; 18 | } 19 | TreeNode* Solution::buildTree(vector &preorder, vector &inorder) { 20 | if (preorder.empty() || inorder.empty()) 21 | return NULL; 22 | int p = 0; 23 | return makeTree(preorder, inorder, 0, inorder.size()-1, p); 24 | } -------------------------------------------------------------------------------- /Arrays/Elements which have at-least two greater elements.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &arr) 2 | { 3 | 4 | vector ans; 5 | 6 | int n = arr.size(); 7 | 8 | int first = INT_MIN, 9 | second = INT_MIN; 10 | for (int i = 0; i < n; i++) 11 | { 12 | /* If current element is smaller 13 | than first then update both first 14 | and second */ 15 | if (arr[i] > first) 16 | { 17 | second = first; 18 | first = arr[i]; 19 | } 20 | 21 | /* If arr[i] is in between first 22 | and second then update second */ 23 | else if (arr[i] > second) 24 | second = arr[i]; 25 | } 26 | 27 | for (int i = 0; i < n; i++) 28 | if (arr[i] < second) 29 | ans.push_back(arr[i]); 30 | 31 | return ans; 32 | } 33 | -------------------------------------------------------------------------------- /Two Pointers/IntersectionOfSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/intersection-of-sorted-arrays/ 2 | 3 | vector Solution::intersect(const vector &A, const vector &B) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | int i = 0; 9 | int j = 0; 10 | vector sol; 11 | 12 | while((i < A.size()) && (j < B.size())){ 13 | if(A[i] > B[j]){ 14 | j++; 15 | } 16 | else if(A[i] < B[j]){ 17 | i++; 18 | } 19 | else{ 20 | sol.push_back(A[i]); 21 | i++; 22 | j++; 23 | } 24 | } 25 | 26 | return sol; 27 | } 28 | -------------------------------------------------------------------------------- /Two Pointers/Good Subarrays.cpp: -------------------------------------------------------------------------------- 1 | const int N = 1e5 + 10; 2 | int f[N]; 3 | 4 | vector Solution::solve(vector &A, int B) { 5 | 6 | vector< int > res; 7 | int j = 0, cnt = 0, n = A.size(); 8 | 9 | assert(1 <= n); 10 | assert(n <= 100000); 11 | assert(1 <= B); 12 | assert(B <= n); 13 | 14 | res.resize(n); 15 | memset(f, 0, sizeof(f)); 16 | 17 | for(int i = 0; i < n; i++) { 18 | assert(A[i] >= 1); 19 | assert(A[i] <= 100000); 20 | while( j < n && cnt + !f[A[j]] <= B ) { 21 | cnt += !f[A[j]]; 22 | f[A[j]]++; 23 | j++; 24 | } 25 | 26 | res[j-i-1]++; 27 | 28 | f[A[i]]--; 29 | if( f[A[i]] == 0 ) cnt--; 30 | } 31 | 32 | 33 | 34 | for( int i = n-2; i >= 0; i-- ) 35 | res[i] += res[i+1]; 36 | 37 | return res; 38 | 39 | } -------------------------------------------------------------------------------- /Two Pointers/MergeTwoSortedLists.cpp: -------------------------------------------------------------------------------- 1 | bool checkGreater(int A, int B){ 2 | if(A > B){ 3 | return true; 4 | } 5 | return false; 6 | } 7 | 8 | void Solution::merge(vector &A, vector &B) { 9 | // Do not write main() function. 10 | // Do not read input, instead use the arguments to the function. 11 | // Do not print the output, instead return values as specified 12 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 13 | int i = 0, j = 0; 14 | while((i < A.size()) && (j < B.size())){ 15 | bool a = checkGreater(A[i], B[j]); 16 | if(a){ 17 | A.insert(A.begin()+i, B[j]); 18 | i++; 19 | j++; 20 | } 21 | else{ 22 | i++; 23 | } 24 | } 25 | while(j != B.size()){ 26 | A.push_back(B[j]); 27 | j++; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Heaps and Maps/KEEP SWAPPING.cpp: -------------------------------------------------------------------------------- 1 | #define mxn 100005 2 | #define mxnn 200005 3 | #define mod (ll)10000000 4 | #define ll long long 5 | int a[mxn]; 6 | unordered_map m; 7 | string Solution::solve(string A,int B, int C) 8 | { 9 | m.clear(); 10 | int n =A.length(),total = n; 11 | string ans = A; 12 | for(int i=0;ival == x) 4 | return 0; 5 | else if (root->val > x) 6 | return 1 + distanceFromRoot(root->left, x); 7 | return 1 + distanceFromRoot(root->right, x); 8 | } 9 | 10 | 11 | int distanceBetween2(TreeNode* root, int a, int b) 12 | { 13 | if (!root) 14 | return 0; 15 | 16 | if (root->val > a && root->val > b) 17 | return distanceBetween2(root->left, a, b); 18 | 19 | 20 | if (root->val < a && root->val < b) 21 | return distanceBetween2(root->right, a, b); 22 | 23 | 24 | if (root->val >= a && root->val <= b) 25 | return distanceFromRoot(root, a) + 26 | distanceFromRoot(root, b); 27 | } 28 | int Solution::solve(TreeNode *A, int B, int C) 29 | { 30 | if (B > C) 31 | swap(B, C); 32 | return distanceBetween2(A, B, C); 33 | } -------------------------------------------------------------------------------- /Dynamic Programming/Grid Unique Paths II.cpp: -------------------------------------------------------------------------------- 1 | long long dp[505][505]; 2 | const int MOD = 1000000007; 3 | 4 | int uniquePathsII(vector>& A) { 5 | int n=A.size(); 6 | if(n==0) 7 | return 0; 8 | int m=A[0].size(); 9 | if(m==0) 10 | return 0; 11 | if(A[n-1][m-1]||A[0][0]) 12 | return 0; 13 | for(int i=0; i > &A) { 30 | return uniquePathsII(A); 31 | } -------------------------------------------------------------------------------- /Graphs/Path in Directed Graph.cpp: -------------------------------------------------------------------------------- 1 | const int maxn = 100009; 2 | vector < int > adj[maxn]; 3 | int visited[maxn]; 4 | void ini() { 5 | for (int i = 0; i < maxn; i++) adj[i].clear(); 6 | memset(visited, 0, sizeof(visited)); 7 | } 8 | bool isReachable(int s, int d) { 9 | if (s == d) return true; 10 | queue < int > q; 11 | q.push(s); 12 | visited[s] = 1; 13 | while (q.empty() == false) { 14 | int s = q.front(); 15 | q.pop(); 16 | for (auto v: adj[s]) { 17 | if (v == d) return true; 18 | if (visited[v] == 0) { 19 | visited[v] = 1; 20 | q.push(v); 21 | } 22 | } 23 | } 24 | return false; 25 | } 26 | int Solution::solve(int A, vector < vector < int > > & B) { 27 | assert(A >= 2 && A <= 100000); 28 | assert(B.size() <= 200000); 29 | ini(); 30 | for (auto & it: B) adj[it[0]].push_back(it[1]); 31 | if (isReachable(1, A)) return 1; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Two Pointers/SortByColor.cpp: -------------------------------------------------------------------------------- 1 | void Solution::sortColors(vector &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | int c0=0,c1=0,c2=0; 7 | for(int i=0;i st; 11 | st.push(-1); 12 | 13 | while(i < A.size()){ 14 | if(A[i] == '('){ 15 | st.push(i); 16 | } 17 | else{ 18 | st.pop(); 19 | if(!st.empty()){ 20 | sol = max(i-st.top(), sol); 21 | } 22 | else{ 23 | st.push(i); 24 | } 25 | } 26 | i++; 27 | } 28 | 29 | 30 | return sol; 31 | } 32 | -------------------------------------------------------------------------------- /Hashing/Sort an array according to the order defined by another array.cpp: -------------------------------------------------------------------------------- 1 | vector solveit(vector &a,vector &b){ 2 | unordered_map mp; 3 | vector > notInB; 4 | unordered_map::iterator it1; 5 | int i=0; 6 | for(auto &it:a) 7 | ++mp[it]; 8 | for(auto &it:b){ 9 | it1=mp.find(it); 10 | if(it1!=mp.end()){ 11 | int y=mp[it]; 12 | while(y--) 13 | a[i++]=it; 14 | mp.erase(it1); 15 | } 16 | } 17 | for(auto &it:mp) 18 | notInB.push_back({it.first,it.second}); 19 | sort(notInB.begin(),notInB.end()); 20 | for(auto &it:notInB){ 21 | int x=it.first; 22 | int y=it.second; 23 | while(y--) 24 | a[i++]=x; 25 | } 26 | return a; 27 | } 28 | 29 | vector Solution::solve(vector &A, vector &B) { 30 | return solveit(A,B); 31 | } -------------------------------------------------------------------------------- /Trees/BST nodes in a range.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | int countbstnodesingivenrange(TreeNode *root, int low, int high) { 12 | if (root==NULL) 13 | return 0; 14 | if (root->val == high && root->val == low) 15 | return 1; 16 | if (root->val <= high && root->val >= low) 17 | return 1 + countbstnodesingivenrange(root->left, low, high) + countbstnodesingivenrange(root->right, low, high); 18 | else if (root->val < low) 19 | return countbstnodesingivenrange(root->right, low, high); 20 | else 21 | return countbstnodesingivenrange(root->left, low, high); 22 | return 0; 23 | } 24 | int Solution::solve(TreeNode* A, int B, int C) { 25 | return countbstnodesingivenrange(A,B,C); 26 | } -------------------------------------------------------------------------------- /Trees/LeastCommonAncestor.cpp: -------------------------------------------------------------------------------- 1 | bool find(TreeNode* root, int val) 2 | { 3 | if (!root) 4 | return false; 5 | if (root->val == val) 6 | return true; 7 | if ((root->left && find(root->left, val)) || 8 | (root->right && find(root->right, val))) 9 | return true; 10 | return false; 11 | } 12 | 13 | TreeNode* LCA(TreeNode* root, int val1, int val2) 14 | { 15 | if (!root || root->val == val1 || root->val == val2) 16 | return root; 17 | 18 | auto L = LCA(root->left, val1, val2); 19 | auto R = LCA(root->right, val1, val2); 20 | 21 | if (L && R) 22 | return root; 23 | return L ? L : R; 24 | } 25 | 26 | int Solution::lca(TreeNode* A, int val1, int val2) { 27 | if (!find(A, val1) || !find(A, val2)) 28 | return -1; 29 | auto ancestor = LCA(A, val1, val2); 30 | if (ancestor) 31 | return ancestor->val; 32 | return -1; 33 | } -------------------------------------------------------------------------------- /Backtracking/ModularExpression.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/modular-expression/ 2 | 3 | long long int calMod(int A, int B, int C){ 4 | if(B == 0){ 5 | return 1; 6 | } 7 | else if(B%2 == 0){ 8 | long long int y = calMod(A, B/2, C); 9 | return (y*y)%C; 10 | } 11 | else{ 12 | return ((A%C)*calMod(A,B-1,C))%C; 13 | } 14 | } 15 | 16 | int Solution::Mod(int A, int B, int C) { 17 | // Do not write main() function. 18 | // Do not read input, instead use the arguments to the function. 19 | // Do not print the output, instead return values as specified 20 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 21 | 22 | if(A == 0){ 23 | return 0; 24 | } 25 | 26 | if(calMod(A, B, C) < 0){ 27 | return C+(int)calMod(A, B, C); 28 | } 29 | return (int)calMod(A, B, C); 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Time Complexity/Floyd Warshall Algorithm.cpp: -------------------------------------------------------------------------------- 1 | vector < vector > Solution::solve(vector < vector > &A) 2 | { 3 | int n=A.size(); 4 | for(int i=0;i Solution::solve(vector &A) 2 | { 3 | 4 | int size = A.size(); 5 | int posStartIndex = 0, i, j, temp; 6 | 7 | for (i = 0; i < size; i++) 8 | { 9 | if (A[i] < 0) 10 | { 11 | int temp = A[i]; 12 | for (j = i; j > posStartIndex; j--) 13 | { 14 | A[j] = A[j-1]; 15 | } 16 | A[posStartIndex] = temp; 17 | posStartIndex++; 18 | } 19 | } 20 | 21 | int pos = posStartIndex, neg = 1; 22 | 23 | while (pos < size && neg < pos && A[neg] < 0) 24 | { 25 | i = pos; 26 | temp = A[i]; 27 | while(i > neg) 28 | { 29 | A[i] = A[i-1]; 30 | i--; 31 | } 32 | A[neg] = temp; 33 | 34 | neg += 2; 35 | pos++; 36 | } 37 | return A; 38 | } 39 | -------------------------------------------------------------------------------- /Dynamic Programming/Maximum coin in a tree.cpp: -------------------------------------------------------------------------------- 1 | std::vector gr[50001]; 2 | int ans[2][50001],vis[50001]; 3 | 4 | void dfs(int n,vector &B) 5 | { 6 | if(vis[n]) 7 | return; 8 | vis[n]=1; 9 | ans[0][n]=B[n-1]; 10 | for(int v:gr[n]) 11 | { 12 | if(vis[v]==0) 13 | { 14 | dfs(v,B); 15 | ans[0][n]+=ans[1][v]; 16 | ans[1][n]+=max(ans[0][v],ans[1][v]); 17 | } 18 | } 19 | } 20 | 21 | int solveit(vector &A, vector &B) 22 | { 23 | int n=A.size(); 24 | for(int i=0;i<=n;i++) 25 | gr[i].clear(); 26 | for(int i=1;i &A, vector &B) { 37 | return solveit(A,B); 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Math/Next Similar Number.cpp: -------------------------------------------------------------------------------- 1 | int num(char c) 2 | { 3 | return c - '0'; 4 | } 5 | void reverse(string& A,int i,int j) 6 | { 7 | while(i=0;i--) 19 | { 20 | if(num(A[i])i;j--) 31 | { 32 | if(num(A[j])>num(A[i])) 33 | break; 34 | } 35 | // swap with this number 36 | swap(A[j],A[i]); 37 | 38 | // remaining numbers from A[i+1] to A[j] // all are greater than 3 and sholud ber reversed 39 | reverse(A,i+1,n-1); 40 | return A; 41 | } -------------------------------------------------------------------------------- /Strings/MultiplyStrings.cpp: -------------------------------------------------------------------------------- 1 | string Solution::multiply(string A, string B) { 2 | int n= A.length(), m=B.length(); 3 | string out=""; 4 | vector total(n+m); 5 | if(n==0 || m==0) return "0"; 6 | 7 | int i_n=0, i_m=0; 8 | for(int i=n-1;i>=0;i--){ 9 | int num1= A[i]- '0'; 10 | int carry=0; 11 | i_m=0; 12 | for(int j=m-1;j>=0;j--){ 13 | int num2= B[j]-'0'; 14 | int sum= num1*num2+ carry+ total[i_n+i_m]; 15 | carry= sum/10; 16 | total[i_n+i_m]= sum%10; 17 | i_m++; 18 | } 19 | if(carry!=0){ 20 | total[i_n+i_m]+=carry; 21 | carry=0; 22 | } 23 | i_n++; 24 | } 25 | 26 | int ind=0; 27 | for(int i=0;i=0;i--){ 31 | out+= to_string(total[i]); 32 | } 33 | return out; 34 | } -------------------------------------------------------------------------------- /Graphs/Path with good nodes!.cpp: -------------------------------------------------------------------------------- 1 | vector> adj; 2 | 3 | int dfs(int u,int p,int c,vector &A){ 4 | int ans=0; 5 | int children=0; 6 | for(int v: adj[u]){ 7 | if(v!=p){ 8 | if(A[u-1]==0){ 9 | ans+=dfs(v,u,c,A); 10 | }else{ 11 | ans+=dfs(v,u,c-1,A); 12 | } 13 | children++; 14 | } 15 | } 16 | 17 | if(children==0){ 18 | if(c>=1 || (c==0 && A[u-1]==0))return 1; 19 | else return 0; 20 | } 21 | 22 | return ans; 23 | 24 | } 25 | 26 | int Solution::solve(vector &A, vector > &B, int C) { 27 | adj.assign(100005,vector()); 28 | 29 | int n=A.size(); 30 | for(int i=0;i factorial(100001); 4 | int flag = 0; 5 | void Factorial(void) 6 | { 7 | flag = 1; 8 | factorial[0] = 1; 9 | factorial[1] = 1; 10 | long long Fact = 1LL; 11 | for(int i = 2; i <= 100000; i++){ 12 | Fact = (Fact*i)%mod; 13 | factorial[i] = Fact; 14 | } 15 | } 16 | 17 | long long Inverse(int n, int deg) 18 | { 19 | long long res = 1LL, curr = n; 20 | while(deg){ 21 | if(deg%2 != 0) 22 | res = (res*curr)%mod; 23 | deg/=2; 24 | curr = (curr*curr)%mod; 25 | } 26 | return res%mod; 27 | } 28 | 29 | int Solution::solve(int A, int B) { 30 | if(B < A) 31 | return 0; 32 | 33 | if(flag == 0) 34 | Factorial(); 35 | 36 | if(A == B) 37 | return factorial[B]; 38 | 39 | return (factorial[B]*Inverse(factorial[B-A],mod-2))%mod; 40 | } 41 | -------------------------------------------------------------------------------- /Dynamic Programming/LongestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/longest-increasing-subsequence/ 2 | 3 | int Solution::lis(const vector &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | if(A.size() == 0){ 10 | return 0; 11 | } 12 | 13 | vector val(A.size(), 1); 14 | 15 | int sol = 1; 16 | 17 | for(int i = 1; i < A.size(); i++){ 18 | for(int j = 0; j < i; j++){ 19 | if(A[i] > A[j]){ 20 | val[i] = max(val[j]+1, val[i]); 21 | if(val[i] > sol){ 22 | sol = val[i]; 23 | } 24 | } 25 | } 26 | } 27 | 28 | return sol; 29 | } 30 | -------------------------------------------------------------------------------- /Heaps and Maps/NMaxPairCombinations.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::solve(vector &A, vector &B) { 2 | priority_queue > > hp; 3 | set > S; 4 | int n = A.size(); 5 | sort(A.begin(), A.end()); 6 | sort(B.begin(), B.end()); 7 | 8 | hp.push(make_pair(A[n-1]+B[n-1], make_pair(n-1, n-1))); 9 | S.insert(make_pair(n-1, n-1)); 10 | 11 | vector ans; 12 | int k=n; 13 | while(k--){ 14 | pair > top = hp.top(); 15 | hp.pop(); 16 | ans.push_back(top.first); 17 | int L = top.second.first; 18 | int R = top.second.second; 19 | 20 | if( R>0 && L>=0 && S.find(make_pair(L,R-1)) == S.end() ){ 21 | hp.push(make_pair(A[L]+B[R-1], make_pair(L,R-1))); 22 | S.insert(make_pair(L,R-1)); 23 | } 24 | if( R>=0 && L>0 && S.find(make_pair(L-1, R))==S.end()){ 25 | hp.push(make_pair(A[L-1]+B[R], make_pair(L-1,R))); 26 | S.insert(make_pair(L-1, R)); 27 | } 28 | } 29 | return ans; 30 | } 31 | -------------------------------------------------------------------------------- /Linked Lists/ReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/reverse-linked-list/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | ListNode* Solution::reverseList(ListNode* A) { 12 | // Do not write main() function. 13 | // Do not read input, instead use the arguments to the function. 14 | // Do not print the output, instead return values as specified 15 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 16 | struct ListNode* next; 17 | struct ListNode* prev; 18 | struct ListNode* curr; 19 | 20 | curr = A; 21 | prev = NULL; 22 | 23 | while(curr != NULL){ 24 | next = curr->next; 25 | curr->next = prev; 26 | prev = curr; 27 | curr = next; 28 | } 29 | 30 | return prev; 31 | } 32 | -------------------------------------------------------------------------------- /Math/ExcelColumnNumber.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/excel-column-number/ 2 | 3 | int Solution::titleToNumber(string A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | int length = A.size(); 10 | int index, solution = 0; 11 | 12 | if(length == 0){ 13 | solution = 0; 14 | } 15 | else if(length == 1){ 16 | solution = ((int)A[length-1])%64; 17 | } 18 | else{ 19 | for(index = 0; index < length-1; index++){ 20 | solution = solution + pow(26,index+1); 21 | solution = solution + (((int)A[index])%64-1)*pow(26, length-index-1); 22 | } 23 | solution = solution + (((int)A[length-1])%64); 24 | } 25 | return solution; 26 | } 27 | -------------------------------------------------------------------------------- /Two Pointers/ContainerWithMostWater.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/container-with-most-water/ 2 | 3 | int Solution::maxArea(vector &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | int i = 0; 10 | int j = A.size()-1; 11 | int ans = 0; 12 | 13 | while(i < A.size()){ 14 | int curr = 0; 15 | if(A[i] <= A[j]){ 16 | curr = (j-i)*A[i]; 17 | i++; 18 | } 19 | else{ 20 | curr = (j-i)*A[j]; 21 | j--; 22 | } 23 | if(curr > ans){ 24 | ans = curr; 25 | } 26 | if(i == j){ 27 | break; 28 | } 29 | } 30 | 31 | return ans; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Two Pointers/DEVICE CROSSOVER.cpp: -------------------------------------------------------------------------------- 1 | int Solution::solve(vector &A, vector &B) 2 | { 3 | int n = A.size(); 4 | int m = B.size(); 5 | int ptr1 = 0,ptr2 = 0; 6 | int ans = 0,last = 0; 7 | while(ptr1 &A, int B) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | int i = 1, j = 0; 10 | 11 | if(A.size() == 0 || A.size() == 1){ 12 | return 0; 13 | } 14 | 15 | LOOP:while((i != A.size()) && (j != A.size())){ 16 | if(j == i){ 17 | i++; 18 | goto LOOP; 19 | } 20 | int diff = A[i] - A[j]; 21 | if(diff == B){ 22 | return 1; 23 | } 24 | else if(diff < B){ 25 | i++; 26 | } 27 | else if(diff > B){ 28 | j++; 29 | } 30 | } 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Backtracking/Combinations.cpp: -------------------------------------------------------------------------------- 1 | void make(vector temp, int curr, int n, int k, vector >& ans){ 2 | if(temp.size() == k){ 3 | ans.push_back(temp); 4 | return; 5 | } 6 | else if(curr > n){ 7 | return; 8 | } 9 | 10 | for(int i = curr; i <= n; i++){ 11 | vector t(temp); 12 | t.push_back(i); 13 | make(t, i+1, n, k, ans); 14 | } 15 | } 16 | 17 | vector > Solution::combine(int n, int k) { 18 | // Do not write main() function. 19 | // Do not read input, instead use the arguments to the function. 20 | // Do not print the output, instead return values as specified 21 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 22 | 23 | vector > ans; 24 | 25 | for(int i = 1; i <= n; i++){ 26 | vector temp(1, i); 27 | make(temp, i+1, n, k, ans); 28 | } 29 | 30 | return ans; 31 | } 32 | -------------------------------------------------------------------------------- /Dynamic Programming/MinSumPathInTriangle.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/min-sum-path-in-triangle/ 2 | 3 | int Solution::minimumTotal(vector > &A) { 4 | // Do not write main() function. 5 | // Do not read input, instead use the arguments to the function. 6 | // Do not print the output, instead return values as specified 7 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 8 | 9 | if(A.size() == 0){ 10 | return 0; 11 | } 12 | 13 | int total[A.size()]; 14 | 15 | int l = A.size() - 1; 16 | 17 | for (int i = 0; i < A[l].size(); i++) 18 | { 19 | total[i] = A[l][i]; 20 | } 21 | 22 | for (int i = A.size() - 2; i >= 0; i--) 23 | { 24 | for (int j = 0; j < A[i + 1].size() - 1; j++) 25 | { 26 | total[j] = A[i][j] + min(total[j], total[j + 1]); 27 | } 28 | } 29 | 30 | return total[0]; 31 | } 32 | -------------------------------------------------------------------------------- /Two Pointers/MergeTwoSortedListsII.cpp: -------------------------------------------------------------------------------- 1 | // https://www.interviewbit.com/problems/merge-two-sorted-lists-ii/ 2 | 3 | bool checkGreater(int A, int B){ 4 | if(A > B){ 5 | return true; 6 | } 7 | return false; 8 | } 9 | 10 | void Solution::merge(vector &A, vector &B) { 11 | // Do not write main() function. 12 | // Do not read input, instead use the arguments to the function. 13 | // Do not print the output, instead return values as specified 14 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 15 | int i = 0, j = 0; 16 | while((i < A.size()) && (j < B.size())){ 17 | bool a = checkGreater(A[i], B[j]); 18 | if(a){ 19 | A.insert(A.begin()+i, B[j]); 20 | i++; 21 | j++; 22 | } 23 | else{ 24 | i++; 25 | } 26 | } 27 | while(j != B.size()){ 28 | A.push_back(B[j]); 29 | j++; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Arrays/Bob and Queries.cpp: -------------------------------------------------------------------------------- 1 | int pre[500010]; 2 | int val[500010]; 3 | 4 | void ini(){ 5 | for(int i=0;i<500010;++i) pre[i]=0; 6 | for(int i=0;i<500010;++i) val[i]=0; 7 | } 8 | 9 | void update(int idx,int x){ 10 | for(;idx<500010;idx+=(idx&-idx)) 11 | pre[idx]+=x; 12 | } 13 | 14 | long long query(int idx){ 15 | long long res=0; 16 | for(;idx>0;idx-=(idx&-idx)){ 17 | res += pre[idx]; 18 | } 19 | return res; 20 | } 21 | 22 | vector Solution::solve(int A, vector > &B) { 23 | int q= B.size(); 24 | ini(); 25 | vector ans; 26 | for(int i=0;i