├── Arrays ├── AddOneToNumber.cpp ├── AntiDiagonals.cpp ├── FindDuplicateinArray.cpp ├── FindPermutation.cpp ├── FirstMissingInteger.cpp ├── Flip.cpp ├── HotelBookingsPossible.cpp ├── KthRowofPascal'sTriangle.cpp ├── LargestNumber.cpp ├── MAXSPPROD.cpp ├── MaxDistance.cpp ├── MaxNonNegativeSubArray.cpp ├── MaxSumContiguousSubarray.cpp ├── MaximumAbsoluteDifference.cpp ├── MaximumConsecutiveGap.cpp ├── MaximumUnsortedSubarray.cpp ├── MergeIntervals.cpp ├── MergeOverlappingIntervals.cpp ├── MinStepsinInfiniteGrid.cpp ├── N3RepeatNumber.cpp ├── NextPermutation.cpp ├── NobleInteger.cpp ├── PascalTriangle.cpp ├── RepeatandMissingNumberArray.cpp ├── RotateMatrix.cpp ├── SetMatrixZeros.cpp ├── SpiralOrderMatrixII.cpp ├── TripletsWithSumBetweenGivenRange.cpp └── WaveArray.cpp ├── Backtracking ├── CombinationSum.cpp ├── CombinationSumII.cpp ├── Combinations.cpp ├── GenerateallParenthesesII.cpp ├── GrayCode.cpp ├── KthPermutationSequence.cpp ├── LetterPhone.cpp ├── NQueens.cpp ├── PalindromePartitioning.cpp ├── Permutations.cpp ├── Subset.cpp ├── SubsetsII.cpp └── Sudoku.cpp ├── BinarySearch ├── AllocateBooks.cpp ├── ImplementPowerFunction.cpp ├── MatrixMedian.cpp ├── MatrixSearch.cpp ├── MedianofArray.cpp ├── Painter'sPartitionProblem.cpp ├── RotatedSortedArraySearch.cpp ├── SearchforaRange.cpp ├── SortedInsertPosition.cpp └── SquareRootofInteger.cpp ├── BitManipulation ├── DifferentBitsSumPairwise.cpp ├── DivideIntegers.cpp ├── MinXORvalue.cpp ├── Numberof1Bits.cpp ├── ReverseBits.cpp ├── SingleNumber.cpp └── SingleNumberII.cpp ├── DynamicProgramming ├── ArrangeII.cpp ├── BestTimeToBuyAndSellStocksI.cpp ├── BestTimeToBuyAndSellStocksII.cpp ├── BestTimeToBuyAndSellStocksIII.cpp ├── CoinSumInfinite.cpp ├── CoinsInALine.cpp ├── CountPermutationsOfBST.cpp ├── DistinctSubsequences.cpp ├── DungeonPrincess.cpp ├── EditDistance.cpp ├── EqualAveragePartition.cpp ├── EvaluateExpressionToTrue.cpp ├── FlipArray.cpp ├── InterleavingStrings.cpp ├── IntersectingChordsInACircle.cpp ├── JumpGameArray.cpp ├── KthManhattanDistanceNeighbourhood.cpp ├── LargestAreaOfRectangleWithPermutations.cpp ├── LengthofLongestSubsequence.cpp ├── LongestArithmeticProgression.cpp ├── LongestIncreasingSubsequence.cpp ├── LongestValidParentheses.cpp ├── MaxProductSubarray.cpp ├── MaxRectangleInBinaryMatrix.cpp ├── MaxSumPathInBinaryTree.cpp ├── MaxSumWithoutAdjacentElements.cpp ├── MinJumpsArray.cpp ├── MinSumPathInMatrix.cpp ├── MinSumPathInTriangle.cpp ├── NDigitNumbersWithDigitSumS.cpp ├── PalindromePartitioningII.cpp ├── QueenAttack.cpp ├── RegularExpressionII.cpp ├── RegularExpressionMatch.cpp ├── RepeatingSub-Sequence.cpp ├── RodCutting.cpp ├── ScrambleString.cpp ├── ShortestCommonSuperstring.cpp ├── Stairs.cpp ├── SubMatricesWithSumZero.cpp ├── Tushar'sBirthdayBombs.cpp ├── Tushar'sBirthdayParty.cpp ├── UniqueBinarySearchTreesII.cpp ├── UniquePathsInAGrid.cpp ├── WaysToColorA3xNBoard.cpp ├── WaystoDecode.cpp ├── WordBreak.cpp └── WordBreakII.cpp ├── GraphDataStructure&Algorithms ├── BlackShapes.cpp ├── CaptureRegionsOnBoard.cpp ├── CloneGraph.cpp ├── CommutableIslands.cpp ├── ConvertSortedListToBinarySearchTree.cpp ├── KnightOnChessBoard.cpp ├── LargestDistanceBetweenNodesOfATree.cpp ├── LevelOrder.cpp ├── PossibilityOfFinishingAllCoursesGivenPreRequisites.cpp ├── SmallestMultipleWith0And1.cpp ├── SmallestSequenceWithGivenPrimes.cpp ├── SteppingNumbers.cpp ├── SumOfFibonacciNumbers.cpp ├── ValidPath.cpp ├── WordLadderI.cpp ├── WordLadderII.cpp └── WordSearchBoard.cpp ├── Greedy ├── AssignMiceToHoles.cpp ├── Bulbs.cpp ├── DistributeCandy.cpp ├── GasStation.cpp ├── HighestProduct.cpp ├── MajorityElement.cpp └── Seats.cpp ├── Hashing ├── 2Sum.cpp ├── 4Sum.cpp ├── Anagrams.cpp ├── ColorfulNumber.cpp ├── CopyList.cpp ├── DiffkII.cpp ├── Equal.cpp ├── Fraction.cpp ├── LargestContinuousSequenceZeroSum.cpp ├── LongestSubstringWithoutRepeat.cpp ├── PointsontheStraightLine.cpp ├── SubstringConcatenation.cpp ├── ValidSudoku.cpp └── WindowString.cpp ├── HeapsAndMaps ├── DistinctNumbersInWindow.cpp ├── LRUCache.cpp ├── MagicianAndChocolates.cpp ├── MergeKSortedLists.cpp ├── NMaxPairCombinations.cpp └── WaysToFormMaxHeap.cpp ├── LinkedLists ├── AddTwoNumbersasLists.cpp ├── InsertionSortList.cpp ├── Kreverselinkedlist.cpp ├── ListCycle.cpp ├── MergeTwoSortedLists.cpp ├── PalindromeList.cpp ├── PartitionList.cpp ├── RemoveDuplicatesfromSortedList.cpp ├── RemoveDuplicatesfromSortedListII.cpp ├── RemoveNthNodefromListEnd.cpp ├── ReorderList.cpp ├── ReverseLinkListII.cpp ├── RotateList.cpp ├── SortList.cpp └── SwapListNodesinpairs.cpp ├── Math ├── ExcelColumnNumber.cpp ├── ExcelColumnTitle.cpp ├── FizzBuzz.cpp ├── GreatestCommonDivisor.cpp ├── GridUniquePaths.cpp ├── LargestCoprimeDivisor.cpp ├── NumbersoflengthNandvaluelessthanK.cpp ├── PalindromeInteger.cpp ├── PowerOfTwoIntegers.cpp ├── PrimeSum.cpp ├── RearrangeArray.cpp ├── ReverseInteger.cpp ├── SortedPermutationRank.cpp ├── SortedPermutationRankwithRepeats.py ├── SumofpairwiseHammingDistance.cpp └── TrailingZerosinFactorial.cpp ├── README.md ├── StacksAndQueues ├── EvaluateExpression.cpp ├── LargestRectangleinHistogram.cpp ├── MinStack.cpp ├── NearestSmallerElement.cpp ├── RainWaterTrapped.cpp ├── RedundantBraces.cpp ├── SimplifyDirectoryPath.cpp └── SlidingWindowMaximum.cpp ├── Strings ├── AddBinaryStrings.cpp ├── AmazingSubarrays.cpp ├── Atoi.cpp ├── CompareVersionNumbers.cpp ├── CountAndSay.cpp ├── ImplementStrStr.cpp ├── IntegerToRoman.cpp ├── JustifiedText.cpp ├── LengthofLastWord.cpp ├── LongestCommonPrefix.cpp ├── LongestPalindromicSubstring.cpp ├── MinimumCharactersrequiredtomakeaStringPalindromic.cpp ├── MultiplyStrings.cpp ├── PalindromeString.cpp ├── Powerof2.cpp ├── PrettyJson.cpp ├── ReversetheString.cpp ├── RomanToInteger.cpp ├── Stringoholics.cpp ├── ValidIpAddresses.cpp ├── ValidNumber.cpp └── ZigzagString.cpp ├── TreeDataStructure ├── 2-SumBinaryTree.cpp ├── BSTIterator.cpp ├── BalancedBinaryTree.cpp ├── BinaryTreeFromInorderAndPostorder.cpp ├── ConstructBinaryTreeFromInorderAndPreorder.cpp ├── FlattenBinaryTreetoLinkedList.cpp ├── HotelReviews.cpp ├── IdenticalBinaryTrees.cpp ├── InorderTraversal.cpp ├── InorderTraversalofCartesianTree.cpp ├── InvertTheBinaryTree.cpp ├── KthSmallestElementInTree.cpp ├── LeastCommonAncestor.cpp ├── MaxDepthofBinaryTree.cpp ├── MinDepthofBinaryTree.cpp ├── OrderofPeopleHeights.cpp ├── PathSum.cpp ├── PopulateNextRightPointersTree.cpp ├── PostorderTraversal.cpp ├── PreorderTraversal.cpp ├── RecoverBinarySearchTree.cpp ├── RootToLeafPathsWithSum.cpp ├── ShortestUniquePrefix.cpp ├── SortedArrayToBalancedBST.cpp ├── SumRootToLeafNumbers.cpp ├── SymmetricBinaryTree.cpp ├── VerticalOrderTraversalofBinaryTree.cpp └── ZigZagLevelOrderTraversalBT.cpp └── TwoPointers ├── 3Sum.cpp ├── 3SumZero.cpp ├── Array3Pointers.cpp ├── ContainerWithMostWater.cpp ├── CountingTriangles.cpp ├── Diffk.cpp ├── IntersectionOfSortedArrays.cpp ├── MaxContinuousSeriesof1s.cpp ├── MergeTwoSortedListsII.cpp ├── Minimizetheabsolutedifference.cpp ├── RemoveDuplicatesfromSortedArray.cpp ├── RemoveDuplicatesfromSortedArrayII.cpp ├── RemoveElementfromArray.cpp └── SortbyColor.cpp /Arrays/AddOneToNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-negative number represented as an array of digits, 3 | 4 | add 1 to the number ( increment the number represented by the digits ). 5 | 6 | The digits are stored such that the most significant digit is at the head of the list. 7 | 8 | Example: 9 | 10 | If the vector has [1, 2, 3] 11 | 12 | the returned vector should be [1, 2, 4] 13 | 14 | as 123 + 1 = 124. 15 | 16 | LINK: https://www.interviewbit.com/problems/add-one-to-number/ 17 | */ 18 | 19 | vector Solution::plusOne(vector &A) 20 | { 21 | int c=1; 22 | 23 | for(int i=A.size()-1;i>=0;i--) 24 | { 25 | int num = A[i]+c; 26 | c = num/10; 27 | A[i] = num%10; 28 | } 29 | 30 | vector v; 31 | if(c==1) 32 | { 33 | v.push_back(1); 34 | for(int i=0;i > Solution::diagonal(vector > &A) 40 | { 41 | vector> v; 42 | 43 | int n = A.size(); 44 | 45 | for(int i=0;i vv; 48 | for(int j=i,k=0;k<=i;j--,k++) 49 | vv.push_back(A[k][j]); 50 | v.push_back(vv); 51 | } 52 | 53 | for(int i=1;i vv; 56 | for(int j=n-1,k=i;k Solution::findPerm(const string s, int n) 24 | { 25 | vector v(n); 26 | int len = s.length(); 27 | 28 | int k=1; 29 | 30 | for(int i=0;i=0;i--) 42 | { 43 | if(s[i]=='D') 44 | { 45 | v[i] = k; 46 | k++; 47 | } 48 | } 49 | 50 | return v; 51 | } -------------------------------------------------------------------------------- /Arrays/FirstMissingInteger.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted integer array, find the first missing positive integer. 3 | 4 | Example: 5 | 6 | Given [1,2,0] return 3, 7 | 8 | [3,4,-1,1] return 2, 9 | 10 | [-8, -7, -6] returns 1 11 | 12 | Your algorithm should run in O(n) time and use constant space. 13 | 14 | LINK: https://www.interviewbit.com/problems/first-missing-integer/ 15 | */ 16 | 17 | int Solution::firstMissingPositive(vector &A) 18 | { 19 | int n = A.size(); 20 | 21 | int j=0; 22 | 23 | for(int i=0;i0) 37 | A[abs(A[i])-1+j] = -A[abs(A[i])-1+j]; 38 | } 39 | 40 | for(int i=j;i0) 42 | return (i-j+1); 43 | 44 | return (n-j+1); 45 | } -------------------------------------------------------------------------------- /Arrays/KthRowofPascal'sTriangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an index k, return the kth row of the Pascal’s triangle. 3 | 4 | Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1. 5 | 6 | Example: 7 | 8 | Input : k = 3 9 | 10 | Return : [1,3,3,1] 11 | NOTE : k is 0 based. k = 0, corresponds to the row [1]. 12 | Note:Could you optimize your algorithm to use only O(k) extra space? 13 | 14 | LINK: https://www.interviewbit.com/problems/kth-row-of-pascals-triangle/ 15 | */ 16 | 17 | vector Solution::getRow(int n) 18 | { 19 | vector v; 20 | v.push_back(1); 21 | 22 | for(int i=0;i &A) 25 | { 26 | int len = A.size(); 27 | vector v(len); 28 | 29 | for(int i=0;i=0;i--) 39 | { 40 | s+=to_string(v[i]); 41 | if(v[i]==0) 42 | cnt++; 43 | } 44 | 45 | if(cnt==len) 46 | s="0"; 47 | 48 | return s; 49 | } -------------------------------------------------------------------------------- /Arrays/MaxDistance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j]. 3 | 4 | If there is no solution possible, return -1. 5 | 6 | Example : 7 | 8 | A : [3 5 4 2] 9 | 10 | Output : 2 11 | for the pair (3, 4) 12 | 13 | LINK: https://www.interviewbit.com/problems/max-distance/ 14 | */ 15 | 16 | int Solution::maximumGap(const vector &A) 17 | { 18 | int n = A.size(); 19 | vector> v(n); 20 | 21 | for(int i=0;i=0;i--) 36 | mx[i] = max(mx[i+1],v[i].second); 37 | 38 | int ans=-1; 39 | 40 | for(int i=0;i &A) 16 | { 17 | int mx = INT_MIN, mxt = 0; 18 | 19 | for(int i=0;i &A) 20 | { 21 | int max1,max2,min1,min2; 22 | max1=max2=INT_MIN; 23 | min1=min2=INT_MAX; 24 | 25 | for(int i=0;i Solution::merge(vector &A) 31 | { 32 | // Do not write main() function. 33 | // Do not read input, instead use the arguments to the function. 34 | // Do not print the output, instead return values as specified 35 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 36 | 37 | vector v; 38 | 39 | sort(A.begin(), A.end(), comp); 40 | 41 | int len = A.size(); 42 | 43 | for(int i=0;i temp.end) 54 | break; 55 | 56 | temp.end = max(temp.end, A[j].end); 57 | } 58 | 59 | i = j-1; 60 | 61 | v.push_back(temp); 62 | } 63 | 64 | return v; 65 | } -------------------------------------------------------------------------------- /Arrays/MinStepsinInfiniteGrid.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are in an infinite 2D grid where you can move in any of the 8 directions : 3 | 4 | (x,y) to 5 | (x+1, y), 6 | (x - 1, y), 7 | (x, y+1), 8 | (x, y-1), 9 | (x-1, y-1), 10 | (x+1,y+1), 11 | (x-1,y+1), 12 | (x+1,y-1) 13 | You are given a sequence of points and the order in which you need to cover the points. Give the minimum number of steps in which you can achieve it. You start from the first point. 14 | 15 | Input : 16 | 17 | Given two integer arrays A and B, where A[i] is x coordinate and B[i] is y coordinate of ith point respectively. 18 | Output : 19 | 20 | Return an Integer, i.e minimum number of steps. 21 | Example : 22 | 23 | Input : [(0, 0), (1, 1), (1, 2)] 24 | Output : 2 25 | It takes 1 step to move from (0, 0) to (1, 1). It takes one more step to move from (1, 1) to (1, 2). 26 | 27 | This question is intentionally left slightly vague. Clarify the question by trying out a few cases in the “See Expected Output” section. 28 | 29 | LINK: https://www.interviewbit.com/problems/min-steps-in-infinite-grid/ 30 | */ 31 | 32 | int Solution::coverPoints(vector &A, vector &B) 33 | { 34 | int x=A[0], y=B[0]; 35 | int cnt = 0; 36 | for(int i=1;i &A) 9 | { 10 | sort(A.begin(),A.end()); 11 | 12 | int len = A.size(); 13 | 14 | for(int i=0;i=0) 17 | { 18 | if(i > Solution::generate(int n) 24 | { 25 | vector> v; 26 | 27 | for(int i=0;i vv; 30 | for(int j=0;j<=i;j++) 31 | { 32 | if(j==0 || j==i) 33 | vv.push_back(1); 34 | else 35 | vv.push_back(v[i-1][j] + v[i-1][j-1]); 36 | } 37 | v.push_back(vv); 38 | } 39 | return v; 40 | } -------------------------------------------------------------------------------- /Arrays/RepeatandMissingNumberArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a read only array of n integers from 1 to n. 3 | 4 | Each integer appears exactly once except A which appears twice and B which is missing. 5 | 6 | Return A and B. 7 | 8 | Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 9 | 10 | Note that in your output A should precede B. 11 | 12 | Example: 13 | 14 | Input:[3 1 2 5 3] 15 | 16 | Output:[3, 4] 17 | 18 | A = 3, B = 4 19 | 20 | LINK: https://www.interviewbit.com/problems/repeat-and-missing-number-array/ 21 | */ 22 | 23 | vector Solution::repeatedNumber(const vector &A) 24 | { 25 | long long int s1=0,s2=0; 26 | for(long long int i=0;i v = {a,b}; 38 | 39 | return v; 40 | } -------------------------------------------------------------------------------- /Arrays/RotateMatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an n x n 2D matrix representing an image. 3 | 4 | Rotate the image by 90 degrees (clockwise). 5 | 6 | You need to do this in place. 7 | 8 | Note that if you end up using an additional array, you will only receive partial score. 9 | 10 | Example: 11 | 12 | If the array is 13 | 14 | [ 15 | [1, 2], 16 | [3, 4] 17 | ] 18 | Then the rotated array becomes: 19 | 20 | [ 21 | [3, 1], 22 | [4, 2] 23 | ] 24 | 25 | LINK: https://www.interviewbit.com/problems/rotate-matrix/ 26 | */ 27 | 28 | void Solution::rotate(vector > &A) 29 | { 30 | // Do not write main() function. 31 | // Do not read input, instead use the arguments to the function. 32 | // Do not print the output, instead return values as specified 33 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 34 | 35 | int n=A.size(); 36 | 37 | int l=0,h=n-1; 38 | 39 | while(l > &A) { 24 | // Do not write main() function. 25 | // Do not read input, instead use the arguments to the function. 26 | // Do not print the output, instead return values as specified 27 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 28 | 29 | int m=A.size(); 30 | int n=A[0].size(); 31 | 32 | int r[m],c[n]; 33 | 34 | for(int i=0;i > Solution::generateMatrix(int A) 20 | { 21 | vector> v(A, vector(A)); 22 | 23 | int t=0,b=A-1,l=0,r=A-1,dir=0; 24 | 25 | int num = 1; 26 | 27 | while(l<=r && t<=b) 28 | { 29 | if(dir==0) 30 | { 31 | for(int i=l;i<=r;i++) 32 | { 33 | v[t][i] = num; 34 | num++; 35 | } 36 | t++; 37 | } 38 | else 39 | if(dir==1) 40 | { 41 | for(int i=t;i<=b;i++) 42 | { 43 | v[i][r] = num; 44 | num++; 45 | } 46 | r--; 47 | } 48 | else 49 | if(dir==2) 50 | { 51 | for(int i=r;i>=l;i--) 52 | { 53 | v[b][i] = num; 54 | num++; 55 | } 56 | b--; 57 | } 58 | else 59 | if(dir==3) 60 | { 61 | for(int i=b;i>=t;i--) 62 | { 63 | v[i][l] = num; 64 | num++; 65 | } 66 | l++; 67 | } 68 | dir = (dir+1)%4; 69 | } 70 | return v; 71 | } -------------------------------------------------------------------------------- /Arrays/WaveArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, sort the array into a wave like array and return it, 3 | In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... 4 | 5 | Example 6 | 7 | Given [1, 2, 3, 4] 8 | 9 | One possible answer : [2, 1, 4, 3] 10 | Another possible answer : [4, 1, 3, 2] 11 | NOTE : If there are multiple answers possible, return the one thats lexicographically smallest. 12 | So, in example case, you will return [2, 1, 4, 3] 13 | 14 | LINK: https://www.interviewbit.com/problems/wave-array/ 15 | */ 16 | 17 | vector Solution::wave(vector &A) 18 | { 19 | sort(A.begin(),A.end()); 20 | 21 | for(int i=0;i > comb; 25 | 26 | void backtrack(vector &A, int i, int sum, int B, vector &temp) 27 | { 28 | if(sum>=B) 29 | return; 30 | for(;i > Solution::combinationSum(vector &A, int B) 43 | { 44 | sort(A.begin(), A.end()); 45 | comb.clear(); 46 | vector temp; 47 | 48 | backtrack(A, 0, 0, B, temp); 49 | 50 | vector > res; 51 | set >::iterator it = comb.begin(); 52 | 53 | for(;it!=comb.end();it++) 54 | res.push_back(*it); 55 | 56 | return res; 57 | } -------------------------------------------------------------------------------- /Backtracking/Combinations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 2 3 ... n. 3 | 4 | Make sure the combinations are sorted. 5 | 6 | To elaborate, 7 | 8 | Within every entry, elements should be sorted. [1, 4] is a valid entry while [4, 1] is not. 9 | Entries should be sorted within themselves. 10 | Example : 11 | If n = 4 and k = 2, a solution is: 12 | 13 | [ 14 | [1,2], 15 | [1,3], 16 | [1,4], 17 | [2,3], 18 | [2,4], 19 | [3,4], 20 | ] 21 | 22 | LINK: https://www.interviewbit.com/problems/combinations/ 23 | */ 24 | 25 | vector > comb; 26 | 27 | void backtrack(int A, int i, int k, int B, vector &temp) 28 | { 29 | for(;i<=A;i++) 30 | { 31 | temp.push_back(i); 32 | k++; 33 | if(k==B) 34 | comb.push_back(temp); 35 | backtrack(A, i+1, k, B, temp); 36 | temp.pop_back(); 37 | k--; 38 | } 39 | } 40 | 41 | vector > Solution::combine(int A, int B) 42 | { 43 | comb.clear(); 44 | vector temp; 45 | 46 | backtrack(A, 1, 0, B, temp); 47 | 48 | return comb; 49 | } -------------------------------------------------------------------------------- /Backtracking/GenerateallParenthesesII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*n. 3 | 4 | For example, given n = 3, a solution set is: 5 | 6 | "((()))", "(()())", "(())()", "()(())", "()()()" 7 | Make sure the returned list of strings are sorted. 8 | 9 | LINK: https://www.interviewbit.com/problems/generate-all-parentheses-ii/ 10 | */ 11 | 12 | vector res; 13 | 14 | void getParenth(int n, int bal, string &temp) 15 | { 16 | if(temp.length()==2*n) 17 | { 18 | if(bal==0) 19 | res.push_back(temp); 20 | return; 21 | } 22 | 23 | if(bal0) 30 | { 31 | temp.push_back(')'); 32 | getParenth(n,bal-1,temp); 33 | temp.pop_back(); 34 | } 35 | } 36 | 37 | vector Solution::generateParenthesis(int A) 38 | { 39 | // Do not write main() function. 40 | // Do not read input, instead use the arguments to the function. 41 | // Do not print the output, instead return values as specified 42 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 43 | 44 | res.clear(); 45 | string temp = ""; 46 | 47 | getParenth(A, 0, temp); 48 | 49 | return res; 50 | } -------------------------------------------------------------------------------- /Backtracking/GrayCode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The gray code is a binary numeral system where two successive values differ in only one bit. 3 | 4 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 5 | 6 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 7 | 8 | 00 - 0 9 | 01 - 1 10 | 11 - 3 11 | 10 - 2 12 | There might be multiple gray code sequences possible for a given n. 13 | Return any such sequence. 14 | 15 | LINK: https://www.interviewbit.com/problems/gray-code/ 16 | */ 17 | 18 | vector Solution::grayCode(int A) 19 | { 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 | int n = pow(2,A); 26 | vector ans(n); 27 | 28 | if(n>1) 29 | { 30 | int mxb = pow(2,A-1); 31 | vector temp = grayCode(A-1); 32 | 33 | for(int i=0;i12) 31 | return INT_MAX; 32 | int f = 1; 33 | for(int i=1;i<=n;i++) 34 | f *= i; 35 | return f; 36 | } 37 | 38 | string getPer(int k, vector v) 39 | { 40 | int n = v.size(); 41 | 42 | if(n==0 || k>fact(n)) 43 | return ""; 44 | 45 | int f = fact(n-1); 46 | int pos = k/f; 47 | k %= f; 48 | string ch = to_string(v[pos]); 49 | v.erase(v.begin()+pos); 50 | return ch + getPer(k, v); 51 | } 52 | 53 | string Solution::getPermutation(int A, int B) 54 | { 55 | vector v; 56 | for(int i=1;i<=A;i++) 57 | v.push_back(i); 58 | 59 | return getPer(B-1, v); 60 | } 61 | -------------------------------------------------------------------------------- /Backtracking/LetterPhone.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a digit string, return all possible letter combinations that the number could represent. 3 | 4 | A mapping of digit to letters (just like on the telephone buttons) is given below. 5 | 6 | 7 | 8 | The digit 0 maps to 0 itself. 9 | The digit 1 maps to 1 itself. 10 | 11 | Input: Digit string "23" 12 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 13 | Make sure the returned strings are lexicographically sorted. 14 | 15 | LINK: https://www.interviewbit.com/problems/letter-phone/ 16 | */ 17 | 18 | vector res; 19 | string phone[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 20 | 21 | void getLetters(string A, int i, string temp) 22 | { 23 | if(i==A.length()) 24 | { 25 | res.push_back(temp); 26 | return; 27 | } 28 | 29 | int ind = A[i]-'0'; 30 | int len = phone[ind].length(); 31 | 32 | for(int j=0;j Solution::letterCombinations(string A) 41 | { 42 | res.clear(); 43 | string temp; 44 | 45 | getLetters(A, 0, temp); 46 | 47 | return res; 48 | } -------------------------------------------------------------------------------- /Backtracking/Permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of numbers, return all possible permutations. 3 | 4 | Example: 5 | 6 | [1,2,3] will have the following permutations: 7 | 8 | [1,2,3] 9 | [1,3,2] 10 | [2,1,3] 11 | [2,3,1] 12 | [3,1,2] 13 | [3,2,1] 14 | NOTE 15 | No two entries in the permutation sequence should be the same. 16 | For the purpose of this problem, assume that all the numbers in the collection are unique. 17 | 18 | LINK: https://www.interviewbit.com/problems/permutations/ 19 | */ 20 | 21 | vector > res; 22 | 23 | void getPerm(vector &A, vector &used, vector &temp, int n) 24 | { 25 | if(n==0) 26 | { 27 | res.push_back(temp); 28 | return; 29 | } 30 | 31 | for(int i=0;i > Solution::permute(vector &A) 45 | { 46 | res.clear(); 47 | int n = A.size(); 48 | vector used(n,false); 49 | vector temp; 50 | 51 | getPerm(A, used, temp, n); 52 | 53 | return res; 54 | } -------------------------------------------------------------------------------- /Backtracking/Subset.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of distinct integers, S, return all possible subsets. 3 | 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | Also, the subsets should be sorted in ascending ( lexicographic ) order. 8 | The list is not necessarily sorted. 9 | Example : 10 | 11 | If S = [1,2,3], a solution is: 12 | 13 | [ 14 | [], 15 | [1], 16 | [1, 2], 17 | [1, 2, 3], 18 | [1, 3], 19 | [2], 20 | [2, 3], 21 | [3], 22 | ] 23 | 24 | LINK: https://www.interviewbit.com/problems/subset/ 25 | */ 26 | 27 | vector > sets; 28 | 29 | void backtrack(vector &A, int i, vector temp) 30 | { 31 | for(;i subset = temp; 34 | subset.push_back(A[i]); 35 | sets.push_back(subset); 36 | backtrack(A, i+1, subset); 37 | } 38 | } 39 | 40 | vector > Solution::subsets(vector &A) 41 | { 42 | sets.clear(); 43 | sort(A.begin(),A.end()); 44 | 45 | vector temp; 46 | 47 | sets.push_back(temp); 48 | 49 | backtrack(A, 0, temp); 50 | 51 | return sets; 52 | } -------------------------------------------------------------------------------- /Backtracking/SubsetsII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of integers that might contain duplicates, S, return all possible subsets. 3 | 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | The subsets must be sorted lexicographically. 8 | Example : 9 | If S = [1,2,2], the solution is: 10 | 11 | [ 12 | [], 13 | [1], 14 | [1,2], 15 | [1,2,2], 16 | [2], 17 | [2, 2] 18 | ] 19 | 20 | LINK: https://www.interviewbit.com/problems/subsets-ii/ 21 | */ 22 | 23 | set > sets; 24 | 25 | void backtrack(vector &A, int i, vector temp) 26 | { 27 | for(;i subset = temp; 30 | subset.push_back(A[i]); 31 | sets.insert(subset); 32 | backtrack(A, i+1, subset); 33 | } 34 | } 35 | 36 | vector > Solution::subsetsWithDup(vector &A) 37 | { 38 | sets.clear(); 39 | sort(A.begin(),A.end()); 40 | 41 | vector temp; 42 | 43 | sets.insert(temp); 44 | 45 | backtrack(A, 0, temp); 46 | 47 | vector > res; 48 | 49 | set >::iterator it = sets.begin(); 50 | 51 | for(;it!=sets.end();it++) 52 | res.push_back(*it); 53 | 54 | return res; 55 | } -------------------------------------------------------------------------------- /BinarySearch/ImplementPowerFunction.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement pow(x, n) % d. 3 | 4 | In other words, given x, n and d, 5 | 6 | find (xn % d) 7 | 8 | Note that remainders on division cannot be negative. 9 | In other words, make sure the answer you return is non negative. 10 | 11 | Input : x = 2, n = 3, d = 3 12 | Output : 2 13 | 14 | 2^3 % 3 = 8 % 3 = 2. 15 | 16 | LINK: https://www.interviewbit.com/problems/implement-power-function/ 17 | */ 18 | 19 | int Solution::pow(int x, int n, int d) 20 | { 21 | // Do not write main() function. 22 | // Do not read input, instead use the arguments to the function. 23 | // Do not print the output, instead return values as specified 24 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 25 | 26 | if(x==0) 27 | return 0; 28 | if(n==0) 29 | return 1; 30 | 31 | long long int a = x%d; 32 | if(a<0) 33 | a+=d; 34 | long long int res = 1; 35 | 36 | 37 | while(n) 38 | { 39 | if(n&1) 40 | res = (res*a)%d; 41 | a = (a*a)%d; 42 | if(a<0) 43 | a+=d; 44 | n = n>>1; 45 | } 46 | return int(res); 47 | } -------------------------------------------------------------------------------- /BinarySearch/MatrixMedian.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a N cross M matrix in which each row is sorted, find the overall median of the matrix. Assume N*M is odd. 3 | 4 | For example, 5 | 6 | Matrix= 7 | [1, 3, 5] 8 | [2, 6, 9] 9 | [3, 6, 9] 10 | 11 | A = [1, 2, 3, 3, 5, 6, 6, 9, 9] 12 | 13 | Median is 5. So, we return 5. 14 | Note: No extra memory is allowed. 15 | 16 | LINK: https://www.interviewbit.com/problems/matrix-median/ 17 | */ 18 | 19 | int Solution::findMedian(vector > &A) 20 | { 21 | int mx = INT_MIN, mn = INT_MAX; 22 | int r = A.size(), c = A[0].size(); 23 | 24 | for(int i=0;i &v, int l, int h, int x) 19 | { 20 | if(l>h) 21 | return -1; 22 | 23 | int mid = l + (h-l)/2; 24 | 25 | if(v[mid] == x) 26 | return mid; 27 | 28 | if(v[l] <= v[mid]) 29 | { 30 | if(x >= v[l] && x <= v[mid]) 31 | return b_search(v, l, mid-1, x); 32 | return b_search(v, mid+1, h, x); 33 | } 34 | 35 | if(x >= v[mid] && x <= v[h]) 36 | return b_search(v, mid+1, h, x); 37 | return b_search(v, l, mid-1, x); 38 | } 39 | 40 | int Solution::search(const vector &A, int B) 41 | { 42 | // Do not write main() function. 43 | // Do not read input, instead use the arguments to the function. 44 | // Do not print the output, instead return values as specified 45 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 46 | 47 | return b_search(A,0,A.size()-1,B); 48 | } -------------------------------------------------------------------------------- /BinarySearch/SearchforaRange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array of integers, find the starting and ending position of a given target value. 3 | 4 | Your algorithm’s runtime complexity must be in the order of O(log n). 5 | 6 | If the target is not found in the array, return [-1, -1]. 7 | 8 | Example: 9 | 10 | Given [5, 7, 7, 8, 8, 10] 11 | 12 | and target value 8, 13 | 14 | return [3, 4]. 15 | 16 | LINK: https://www.interviewbit.com/problems/search-for-a-range/ 17 | */ 18 | 19 | int b_search(const vector &A, int n, int x, bool flag) 20 | { 21 | int low = 0, high = n-1, result = -1; 22 | 23 | while(low<=high) 24 | { 25 | int mid = (low+high)/2; 26 | if(A[mid]==x) 27 | { 28 | result = mid; 29 | if(flag) 30 | high = mid-1; 31 | else 32 | low = mid+1; 33 | } 34 | else 35 | if(x Solution::searchRange(const vector &A, int B) 44 | { 45 | // Do not write main() function. 46 | // Do not read input, instead use the arguments to the function. 47 | // Do not print the output, instead return values as specified 48 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 49 | 50 | int fi = b_search(A,A.size(),B,true); 51 | int li = b_search(A,A.size(),B,false); 52 | 53 | vector v = {fi,li}; 54 | return v; 55 | } -------------------------------------------------------------------------------- /BinarySearch/SortedInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 3 | 4 | You may assume no duplicates in the array. 5 | 6 | Here are few examples. 7 | 8 | [1,3,5,6], 5 → 2 9 | [1,3,5,6], 2 → 1 10 | [1,3,5,6], 7 → 4 11 | [1,3,5,6], 0 → 0 12 | 13 | LINK: https://www.interviewbit.com/problems/sorted-insert-position/ 14 | */ 15 | 16 | int Solution::searchInsert(vector &A, int B) 17 | { 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 | return upper_bound(A.begin(), A.end(),B-1) - A.begin(); 24 | } -------------------------------------------------------------------------------- /BinarySearch/SquareRootofInteger.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement int sqrt(int x). 3 | 4 | Compute and return the square root of x. 5 | 6 | If x is not a perfect square, return floor(sqrt(x)) 7 | 8 | Example : 9 | 10 | Input : 11 11 | Output : 3 12 | DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY 13 | 14 | LINK: https://www.interviewbit.com/problems/square-root-of-integer/ 15 | */ 16 | 17 | int Solution::sqrt(int x) 18 | { 19 | // Do not write main() function. 20 | // Do not read input, instead use the arguments to the function. 21 | // Do not print the output, instead return values as specified 22 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 23 | 24 | if(x==0 || x==1) 25 | return x; 26 | 27 | long long int low = 0, high = x,ans = -1; 28 | 29 | while(low<=high) 30 | { 31 | long long int mid = (low+high)/2; 32 | 33 | if(mid*mid == x) 34 | return mid; 35 | 36 | if(mid*mid < x) 37 | { 38 | low = mid + 1; 39 | ans = mid; 40 | } 41 | else 42 | high = mid - 1; 43 | } 44 | return ans; 45 | } -------------------------------------------------------------------------------- /BitManipulation/DifferentBitsSumPairwise.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We define f(X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f(2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f(2, 7) = 2. 3 | 4 | You are given an array of N positive integers, A1, A2 ,…, AN. Find sum of f(Ai, Aj) for all pairs (i, j) such that 1 ≤ i, j ≤ N. Return the answer modulo 109+7. 5 | 6 | For example, 7 | 8 | A=[1, 3, 5] 9 | 10 | We return 11 | 12 | f(1, 1) + f(1, 3) + f(1, 5) + 13 | f(3, 1) + f(3, 3) + f(3, 5) + 14 | f(5, 1) + f(5, 3) + f(5, 5) = 15 | 16 | 0 + 1 + 1 + 17 | 1 + 0 + 2 + 18 | 1 + 2 + 0 = 8 19 | 20 | LINK: https://www.interviewbit.com/problems/different-bits-sum-pairwise/ 21 | */ 22 | 23 | #define MOD 1000000007 24 | 25 | int Solution::cntBits(vector &A) 26 | { 27 | int n=A.size(); 28 | int bit[32]; 29 | memset(bit,0,sizeof(bit)); 30 | 31 | for(int i=0;i>j)&1) 36 | bit[j]++; 37 | } 38 | } 39 | 40 | long long int ans = 0; 41 | 42 | for(int i=0;i<31;i++) 43 | { 44 | long long int a = bit[i], b = n-bit[i]; 45 | ans += ((a%MOD)*(b%MOD))%MOD; 46 | } 47 | ans = (ans*2)%MOD; 48 | 49 | return ans; 50 | } -------------------------------------------------------------------------------- /BitManipulation/DivideIntegers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Divide two integers without using multiplication, division and mod operator. 3 | 4 | Return the floor of the result of the division. 5 | 6 | Example: 7 | 8 | 5 / 2 = 2 9 | Also, consider if there can be overflow cases. For overflow case, return INT_MAX. 10 | 11 | LINK: https://www.interviewbit.com/problems/divide-integers/ 12 | */ 13 | 14 | int Solution::divide(int A, int B) 15 | { 16 | int sign = ((A<0)^(B<0))?-1:1; 17 | long long int x=abs(1LL*A), y=abs(1LL*B), q=0, temp=0; 18 | 19 | for(int i=31;i>=0;i--) 20 | { 21 | if(temp+(y<=INT_MAX && sign==-1) 28 | return INT_MIN; 29 | if(q>=INT_MAX) 30 | return INT_MAX; 31 | return int(sign*q); 32 | } 33 | -------------------------------------------------------------------------------- /BitManipulation/MinXORvalue.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of N integers, find the pair of integers in the array which have minimum XOR value. Report the minimum XOR value. 3 | 4 | Examples : 5 | Input 6 | 0 2 5 7 7 | Output 8 | 2 (0 XOR 2) 9 | Input 10 | 0 4 7 9 11 | Output 12 | 3 (4 XOR 7) 13 | 14 | Constraints: 15 | 2 <= N <= 100 000 16 | 0 <= A[i] <= 1 000 000 000 17 | 18 | LINK: https://www.interviewbit.com/problems/min-xor-value/ 19 | */ 20 | 21 | int Solution::findMinXor(vector &A) 22 | { 23 | sort(A.begin(), A.end()); 24 | int mn = INT_MAX; 25 | 26 | for(int i=1;i 00000000000000000000000000000000 10 | return 0 11 | 12 | Example 2: 13 | 14 | x = 3, 15 | 16 | 00000000000000000000000000000011 17 | => 11000000000000000000000000000000 18 | return 3221225472 19 | 20 | Since java does not have unsigned int, use long 21 | 22 | LINK: https://www.interviewbit.com/problems/reverse-bits/ 23 | */ 24 | 25 | unsigned int Solution::reverse(unsigned int A) 26 | { 27 | // Do not write main() function. 28 | // Do not read input, instead use the arguments to the function. 29 | // Do not print the output, instead return values as specified 30 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 31 | 32 | int cnt=32, rev = 0; 33 | while(A) 34 | { 35 | rev <<= 1; 36 | rev |= (A&1); 37 | A >>= 1; 38 | cnt--; 39 | } 40 | rev <<= cnt; 41 | return rev; 42 | } -------------------------------------------------------------------------------- /BitManipulation/SingleNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears twice except for one. Find that single one. 3 | 4 | Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 5 | 6 | Example : 7 | 8 | Input : [1 2 2 3 1] 9 | Output : 3 10 | 11 | LINK: https://www.interviewbit.com/problems/single-number/ 12 | */ 13 | 14 | int Solution::singleNumber(const vector &A) 15 | { 16 | int n= A.size(); 17 | int res = A[0]; 18 | 19 | for(int i=1;i &A) 19 | { 20 | int res = 0; 21 | int x, n = A.size(); 22 | for(int i=0;i<32;i++) 23 | { 24 | int cnt = 0; 25 | x = (1< &A) 15 | { 16 | int res = 0; 17 | int n = A.size(); 18 | if(n==0) 19 | return res; 20 | 21 | int min_ele = A[0]; 22 | 23 | for(int i=1;i A[i]) 26 | min_ele = A[i]; 27 | 28 | res = max(res, A[i] - min_ele); 29 | } 30 | return res; 31 | } -------------------------------------------------------------------------------- /DynamicProgramming/BestTimeToBuyAndSellStocksII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 5 | 6 | Example : 7 | 8 | Input : [1 2 3] 9 | Return : 2 10 | 11 | LINK: https://www.interviewbit.com/problems/best-time-to-buy-and-sell-stocks-ii/ 12 | */ 13 | 14 | int Solution::maxProfit(const vector &A) 15 | { 16 | int n = A.size(); 17 | int res = 0; 18 | 19 | int i = 0; 20 | 21 | while(i=A[i]) 32 | i++; 33 | 34 | res += (A[i] - A[j]); 35 | i++; 36 | } 37 | return res; 38 | } -------------------------------------------------------------------------------- /DynamicProgramming/BestTimeToBuyAndSellStocksIII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | 6 | Note: 7 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 8 | 9 | Example : 10 | 11 | Input : [1 2 1 2] 12 | Output : 2 13 | 14 | Explanation : 15 | Day 1 : Buy 16 | Day 2 : Sell 17 | Day 3 : Buy 18 | Day 4 : Sell 19 | 20 | LINK: https://www.interviewbit.com/problems/best-time-to-buy-and-sell-stocks-iii/ 21 | */ 22 | 23 | int Solution::maxProfit(const vector &A) 24 | { 25 | int n = A.size(); 26 | if(n==0) 27 | return 0; 28 | int dp[n]; 29 | memset(dp,0,sizeof(dp)); 30 | 31 | int max_ele = A[n-1]; 32 | 33 | for(int i=n-2;i>=0;i--) 34 | { 35 | if(A[i] > max_ele) 36 | max_ele = A[i]; 37 | 38 | dp[i] = max(dp[i+1], max_ele - A[i]); 39 | } 40 | 41 | int min_ele = A[0]; 42 | 43 | for(int i=1;i &A, int B) 27 | { 28 | int n = A.size(); 29 | 30 | int dp[B+1]; 31 | memset(dp,0,sizeof(dp)); 32 | 33 | dp[0] = 1; 34 | 35 | for(int i=0;i > dp; 25 | 26 | ll solve(vector &A, int i, int j) 27 | { 28 | if(i==j) 29 | return A[i]; 30 | if(i+1==j) 31 | return dp[i][j] = max(A[i],A[j]); 32 | 33 | if(dp[i][j]!=-1) 34 | return dp[i][j]; 35 | 36 | dp[i][j] = max(A[i] + min(solve(A,i+2,j), solve(A,i+1,j-1)), A[j] + min(solve(A,i,j-2), solve(A,i+1,j-1))); 37 | return dp[i][j]; 38 | } 39 | 40 | int Solution::maxcoin(vector &A) 41 | { 42 | int n = A.size(); 43 | 44 | if(n==0) 45 | return 0; 46 | 47 | dp.clear(); 48 | dp.resize(n,vector(n,-1)); 49 | 50 | return solve(A,0,n-1); 51 | } -------------------------------------------------------------------------------- /DynamicProgramming/DistinctSubsequences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sequences S, T, count number of unique ways in sequence S, to form a subsequence that is identical to the sequence T. 3 | 4 | Subsequence : A subsequence of a string is a new string which is formed from the original string by deleting some (can be none ) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 5 | Example : 6 | 7 | S = "rabbbit" 8 | T = "rabbit" 9 | Return 3. And the formations as follows: 10 | 11 | S1= "ra_bbit" 12 | S2= "rab_bit" 13 | S3="rabb_it" 14 | "_" marks the removed character. 15 | 16 | LINK: https://www.interviewbit.com/problems/distinct-subsequences/ 17 | */ 18 | 19 | int Solution::numDistinct(string A, string B) 20 | { 21 | int na = A.length(); 22 | int nb = B.length(); 23 | int dp[na+1][nb+1]; 24 | memset(dp,0,sizeof(dp)); 25 | 26 | for(int i=0;i &A) 23 | { 24 | int n = A.size(); 25 | 26 | if(n==0 || n==1) 27 | return 0; 28 | 29 | if(n==2) 30 | return 1; 31 | 32 | int sum = 0; 33 | 34 | for(int i=0;i=A[i-1]) 50 | dp[i][j] = min(dp[i-1][j], 1 + dp[i-1][j-A[i-1]]); 51 | else 52 | dp[i][j] = dp[i-1][j]; 53 | } 54 | } 55 | 56 | return dp[n][sum]; 57 | } -------------------------------------------------------------------------------- /DynamicProgramming/InterleavingStrings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 3 | 4 | Example, 5 | Given: 6 | 7 | s1 = "aabcc", 8 | s2 = "dbbca", 9 | When s3 = "aadbbcbcac", return true. 10 | When s3 = "aadbbbaccc", return false. 11 | 12 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 13 | 14 | LINK: https://www.interviewbit.com/problems/interleaving-strings/ 15 | */ 16 | 17 | int Solution::isInterleave(string A, string B, string C) 18 | { 19 | int na = A.length(); 20 | int nb = B.length(); 21 | 22 | if(na+nb != C.length()) 23 | return 0; 24 | 25 | int dp[nb+1]; 26 | memset(dp,0,sizeof(dp)); 27 | 28 | for(int i=0;i<=na;i++) 29 | { 30 | for(int j=0;j<=nb;j++) 31 | { 32 | if(i==0 && j==0) 33 | dp[j] = 1; 34 | else 35 | if(i==0) 36 | dp[j] = dp[j-1] && B[j-1]==C[i+j-1]; 37 | else 38 | if(j==0) 39 | dp[j] = dp[j] && A[i-1]==C[i+j-1]; 40 | else 41 | { 42 | dp[j] = (dp[j] && A[i-1]==C[i+j-1]) || (dp[j-1] && B[j-1]==C[i+j-1]); 43 | } 44 | } 45 | } 46 | return dp[nb]; 47 | } -------------------------------------------------------------------------------- /DynamicProgramming/IntersectingChordsInACircle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a number N, return number of ways you can draw N chords in a circle with 2*N points such that no 2 chords intersect. 3 | Two ways are different if there exists a chord which is present in one way and not in other. 4 | 5 | For example, 6 | 7 | N=2 8 | If points are numbered 1 to 4 in clockwise direction, then different ways to draw chords are: 9 | {(1-2), (3-4)} and {(1-4), (2-3)} 10 | 11 | So, we return 2. 12 | Notes: 13 | 14 | 1 ≤ N ≤ 1000 15 | Return answer modulo 109+7. 16 | 17 | LINK: https://www.interviewbit.com/problems/intersecting-chords-in-a-circle/ 18 | */ 19 | 20 | #define MOD 1000000007 21 | 22 | int Solution::chordCnt(int n) 23 | { 24 | long long int dp[n+1]; 25 | 26 | dp[0] = dp[1] = 1; 27 | 28 | for(int i=2;i<=n;i++) 29 | { 30 | dp[i]=0; 31 | 32 | for(int j=0;j &A) 19 | { 20 | int n = A.size(); 21 | int minIndexToReach = n-1; 22 | 23 | for(int i=n-2;i>=0;i--) 24 | { 25 | if(i+A[i] >= minIndexToReach) 26 | minIndexToReach = i; 27 | } 28 | 29 | if(minIndexToReach==0) 30 | return 1; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /DynamicProgramming/LengthofLongestSubsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, find the length of longest subsequence which is first increasing then decreasing. 3 | 4 | **Example: ** 5 | 6 | For the given array [1 11 2 10 4 5 2 1] 7 | 8 | Longest subsequence is [1 2 10 4 2 1] 9 | 10 | Return value 6 11 | 12 | LINK: https://www.interviewbit.com/problems/length-of-longest-subsequence/ 13 | */ 14 | 15 | int Solution::longestSubsequenceLength(const vector &A) 16 | { 17 | int n = A.size(); 18 | 19 | int lis[n],lds[n]; 20 | 21 | for(int i=0;iA[j] && lis[j]+1>=lis[i]) 29 | lis[i] = lis[j]+1; 30 | } 31 | } 32 | 33 | for(int i=n-2;i>=0;i--) 34 | { 35 | for(int j=n-1;j>i;j--) 36 | { 37 | if(A[i]>A[j] && lds[j]+1>=lds[i]) 38 | lds[i] = lds[j]+1; 39 | } 40 | } 41 | 42 | int ans = 0; 43 | 44 | for(int i=0;i &A) 18 | { 19 | int n = A.size(); 20 | int lis[n]; 21 | 22 | int ans = 1; 23 | 24 | for(int i=0;i A[j]) 30 | { 31 | lis[i] = max(lis[i], lis[j]+1); 32 | ans = max(ans, lis[i]); 33 | } 34 | } 35 | } 36 | return ans; 37 | } -------------------------------------------------------------------------------- /DynamicProgramming/LongestValidParentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 3 | 4 | For "(()", the longest valid parentheses substring is "()", which has length = 2. 5 | 6 | Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 7 | 8 | LINK: https://www.interviewbit.com/problems/longest-valid-parentheses/ 9 | */ 10 | 11 | int Solution::longestValidParentheses(string A) 12 | { 13 | int n = A.length(); 14 | 15 | stack st; 16 | st.push(-1); 17 | 18 | int res = 0; 19 | 20 | for(int i=0;i &A) 16 | { 17 | int n = A.size(); 18 | if(n==0) 19 | return 0; 20 | 21 | int curMax, curMin, preMax, preMin, ans; 22 | ans = preMax = preMin = A[0]; 23 | 24 | for(int i=1;ileft); 36 | int rightSum = findMaxPathSum(root->right); 37 | 38 | int maxRoot = max(root->val, root->val + max(leftSum, rightSum)); 39 | 40 | ans = max(ans, max(maxRoot, leftSum + root->val + rightSum)); 41 | 42 | return maxRoot; 43 | } 44 | 45 | int Solution::maxPathSum(TreeNode* A) 46 | { 47 | ans = INT_MIN; 48 | findMaxPathSum(A); 49 | return ans; 50 | } -------------------------------------------------------------------------------- /DynamicProgramming/MaxSumWithoutAdjacentElements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2 * N Grid of numbers, choose numbers such that the sum of the numbers 3 | is maximum and no two chosen numbers are adjacent horizontally, vertically or diagonally, and return it. 4 | 5 | Example: 6 | 7 | Grid: 8 | 1 2 3 4 9 | 2 3 4 5 10 | so we will choose 11 | 3 and 5 so sum will be 3 + 5 = 8 12 | 13 | 14 | Note that you can choose more than 2 numbers 15 | 16 | LINK: https://www.interviewbit.com/problems/max-sum-without-adjacent-elements/ 17 | */ 18 | 19 | int Solution::adjacent(vector > &A) 20 | { 21 | int n = A[0].size(); 22 | if(n==0) 23 | return 0; 24 | 25 | int prevInc = max(A[0][0], A[1][0]); 26 | int prevExc = 0; 27 | 28 | for(int i=1;i &A) 19 | { 20 | int n = A.size(); 21 | 22 | if(n<=1) 23 | return 0; 24 | if(A[0]==0) 25 | return -1; 26 | 27 | int maxInd = A[0]; 28 | int stepsLeft = A[0]; 29 | int jumps = 1; 30 | 31 | for(int i=1;i=maxInd) 41 | return -1; 42 | stepsLeft = maxInd-i; 43 | } 44 | } 45 | return jumps; 46 | } -------------------------------------------------------------------------------- /DynamicProgramming/MinSumPathInMatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 3 | 4 | Note: You can only move either down or right at any point in time. 5 | Example : 6 | 7 | Input : 8 | 9 | [ 1 3 2 10 | 4 3 1 11 | 5 6 1 12 | ] 13 | 14 | Output : 8 15 | 1 -> 3 -> 2 -> 1 -> 1 16 | 17 | LINK: https://www.interviewbit.com/problems/min-sum-path-in-matrix/ 18 | */ 19 | 20 | int Solution::minPathSum(vector > &A) 21 | { 22 | int m = A.size(); 23 | int n = A[0].size(); 24 | 25 | for(int i=1;i > &A) 21 | { 22 | // Do not write main() function. 23 | // Do not read input, instead use the arguments to the function. 24 | // Do not print the output, instead return values as specified 25 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 26 | 27 | int n = A.size(); 28 | 29 | for(int i=1;i > dp; 19 | 20 | int count(int n, int s) 21 | { 22 | if(n==0) 23 | return s==0; 24 | 25 | if(dp[n][s]!=-1) 26 | return dp[n][s]; 27 | 28 | ll ans = 0; 29 | 30 | for(int i=0;i<10;i++) 31 | if(s-i>=0) 32 | ans = (ans + count(n-1,s-i))%MOD; 33 | 34 | return dp[n][s] = ans; 35 | } 36 | 37 | int Solution::solve(int A, int B) 38 | { 39 | if(A==0) 40 | return 0; 41 | if(A==1 && B==0) 42 | return 1; 43 | 44 | dp.clear(); 45 | dp.resize(A,vector(B,-1)); 46 | 47 | ll ans = 0; 48 | 49 | for(int i=1;i<10;i++) 50 | if(B-i>=0) 51 | ans = (ans + count(A-1,B-i))%MOD; 52 | 53 | return ans; 54 | } -------------------------------------------------------------------------------- /DynamicProgramming/PalindromePartitioningII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return the minimum cuts needed for a palindrome partitioning of s. 5 | 6 | Example : 7 | Given 8 | s = "aab", 9 | Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. 10 | 11 | LINK: https://www.interviewbit.com/problems/palindrome-partitioning-ii/ 12 | */ 13 | 14 | int Solution::minCut(string A) 15 | { 16 | int n = A.length(); 17 | 18 | if(n==0) 19 | return 0; 20 | 21 | int dp[n]; 22 | bool palin[n][n]; 23 | 24 | for(int i=0;i(dp[j-1]+1)) 49 | dp[i] = dp[j-1] + 1; 50 | } 51 | } 52 | return dp[n-1]; 53 | } -------------------------------------------------------------------------------- /DynamicProgramming/RegularExpressionII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement regular expression matching with support for '.' and '*'. 3 | 4 | '.' Matches any single character. 5 | '*' Matches zero or more of the preceding element. 6 | 7 | The matching should cover the entire input string (not partial). 8 | 9 | The function prototype should be: 10 | 11 | int isMatch(const char *s, const char *p) 12 | Some examples: 13 | 14 | isMatch("aa","a") → 0 15 | isMatch("aa","aa") → 1 16 | isMatch("aaa","aa") → 0 17 | isMatch("aa", "a*") → 1 18 | isMatch("aa", ".*") → 1 19 | isMatch("ab", ".*") → 1 20 | isMatch("aab", "c*a*b") → 1 21 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 22 | 23 | LINK: https://www.interviewbit.com/problems/regular-expression-ii/ 24 | */ 25 | 26 | int Solution::isMatch(const string A, const string B) 27 | { 28 | int na = A.length(); 29 | int nb = B.length(); 30 | 31 | bool dp[na+1][nb+1]; 32 | memset(dp,false,sizeof(dp)); 33 | 34 | dp[na][nb] = true; 35 | 36 | for(int i=na;i>=0;i--) 37 | { 38 | for(int j=nb-1;j>=0;j--) 39 | { 40 | bool match = (i No 12 | 1 -> Yes 13 | Example: 14 | 15 | abab ------> yes, ab is repeated. So, return 1. 16 | abba ------> No, a and b follow different order. So, return 0. 17 | NOTE : sub-sequence length should be greater than or equal to 2 18 | 19 | LINK: https://www.interviewbit.com/problems/repeating-subsequence/ 20 | */ 21 | 22 | int Solution::anytwo(string A) 23 | { 24 | int n = A.length(); 25 | int dp[n+1][n+1]; 26 | memset(dp,0,sizeof(dp)); 27 | 28 | for(int i=1;i<=n;i++) 29 | { 30 | for(int j=1;j<=n;j++) 31 | { 32 | if(A[i-1]==A[j-1] && i!=j) 33 | dp[i][j] = dp[i-1][j-1] + 1; 34 | else 35 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 36 | if(dp[i][j]>1) 37 | return 1; 38 | } 39 | } 40 | return 0; 41 | } -------------------------------------------------------------------------------- /DynamicProgramming/Stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | 6 | Example : 7 | 8 | Input : 3 9 | Return : 3 10 | 11 | Steps : [1 1 1], [1 2], [2 1] 12 | 13 | LINK: https://www.interviewbit.com/problems/stairs/ 14 | */ 15 | 16 | int Solution::climbStairs(int A) 17 | { 18 | if(A==0 || A==1) 19 | return A; 20 | 21 | int a = 1; 22 | int b = 2; 23 | 24 | for(int i=3;i<=A;i++) 25 | { 26 | int s = a+b; 27 | a = b; 28 | b = s; 29 | } 30 | 31 | return b; 32 | } -------------------------------------------------------------------------------- /DynamicProgramming/SubMatricesWithSumZero.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D matrix, find the number non-empty sub matrices, such that the sum of the elements inside the sub matrix is equal to 0. (note: elements might be negative). 3 | 4 | Example: 5 | 6 | Input 7 | 8 | -8 5 7 9 | 3 7 -8 10 | 5 -8 9 11 | Output 12 | 2 13 | 14 | Explanation 15 | -8 5 7 16 | 3 7 -8 17 | 5 -8 9 18 | 19 | -8 5 7 20 | 3 7 -8 21 | 5 -8 9 22 | 23 | LINK: https://www.interviewbit.com/problems/sub-matrices-with-sum-zero/ 24 | */ 25 | 26 | int res; 27 | 28 | void maxZero(int temp[], int n) 29 | { 30 | unordered_map mp; 31 | mp[0] = 1; 32 | int sum = 0; 33 | 34 | for(int i=0;i > &A) 51 | { 52 | res = 0; 53 | 54 | int r = A.size(); 55 | if(r==0) 56 | return res; 57 | 58 | int c = A[0].size(); 59 | if(c==0) 60 | return res; 61 | 62 | int temp[r]; 63 | 64 | for(int i=0;i dp; 19 | 20 | int solve(int n) 21 | { 22 | if(dp[n]!=-1) 23 | return dp[n]; 24 | 25 | int ans = 0; 26 | 27 | for(int k=0;k > &A) 23 | { 24 | int m = A.size(); 25 | int n = A[0].size(); 26 | 27 | int dp[m][n]; 28 | memset(dp,0,sizeof(dp)); 29 | 30 | if(A[0][0]==0) 31 | dp[0][0] = 1; 32 | 33 | for(int i=1;i1) 23 | { 24 | ll temp = c3; 25 | c3 = (11*c3 + 10*c2)%MOD; 26 | c2 = (5*temp + 7*c2)%MOD; 27 | A--; 28 | } 29 | 30 | return (c2 + c3)%MOD; 31 | } -------------------------------------------------------------------------------- /DynamicProgramming/WaystoDecode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 4 | 'A' -> 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | Example : 11 | 12 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 13 | 14 | The number of ways decoding "12" is 2. 15 | 16 | LINK: https://www.interviewbit.com/problems/ways-to-decode/ 17 | */ 18 | 19 | int Solution::numDecodings(string A) 20 | { 21 | int n = A.length(); 22 | 23 | long long int dp[n+1]; 24 | memset(dp,0,sizeof(dp)); 25 | dp[0] = dp[1] = 1; 26 | if(A[0]=='0') 27 | dp[1] = 0; 28 | 29 | for(int i=2;i<=n;i++) 30 | { 31 | if(A[i-1]!='0') 32 | dp[i] = dp[i-1]; 33 | 34 | if(A[i-2]=='0') 35 | continue; 36 | 37 | int val = (A[i-2]-'0')*10 + (A[i-1]-'0'); 38 | 39 | if(val<=26 && val>0) 40 | dp[i] += dp[i-2]; 41 | else 42 | if(A[i-1]=='0') 43 | dp[i] = 0; 44 | 45 | } 46 | return dp[n]; 47 | } -------------------------------------------------------------------------------- /DynamicProgramming/WordBreak.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 3 | 4 | For example, given 5 | 6 | s = "myinterviewtrainer", 7 | dict = ["trainer", "my", "interview"]. 8 | Return 1 ( corresponding to true ) because "myinterviewtrainer" can be segmented as "my interview trainer". 9 | 10 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 11 | 12 | LINK: https://www.interviewbit.com/problems/word-break/ 13 | */ 14 | 15 | vector dp; 16 | unordered_set st; 17 | 18 | int check(int ind, int n, string &s) 19 | { 20 | if(ind>=n) 21 | return 1; 22 | 23 | if(dp[ind]!=-1) 24 | return dp[ind]; 25 | 26 | bool res = false; 27 | string temp = ""; 28 | 29 | for(int i=ind;i &B) 39 | { 40 | int n = A.length(); 41 | if(n==0) 42 | return 0; 43 | 44 | dp.clear(); 45 | dp.resize(n,-1); 46 | st.clear(); 47 | 48 | for(int i=0;i dp; 22 | unordered_set st; 23 | vector ans; 24 | 25 | int check(int ind, int n, string &s, string str) 26 | { 27 | if(ind>=n) 28 | { 29 | ans.push_back(str); 30 | return 1; 31 | } 32 | 33 | if(dp[ind]!=-1 && dp[ind]==0) 34 | return dp[ind]; 35 | 36 | bool res = false; 37 | string temp = ""; 38 | 39 | for(int i=ind;i Solution::wordBreak(string A, vector &B) 54 | { 55 | ans.clear(); 56 | int n = A.length(); 57 | if(n==0) 58 | return ans; 59 | 60 | dp.clear(); 61 | dp.resize(n,-1); 62 | st.clear(); 63 | 64 | for(int i=0;i &A) 36 | { 37 | A[x][y] = 'O'; 38 | 39 | for(int i=0;i<4;i++) 40 | { 41 | int newx = x+X[i]; 42 | int newy = y+Y[i]; 43 | 44 | if(newx>=0 && newx=0 && newy &A) 50 | { 51 | n = A.size(); 52 | m = A[0].size(); 53 | 54 | int ans = 0; 55 | 56 | for(int i=0;i neighbors; 12 | * UndirectedGraphNode(int x) : label(x) {}; 13 | * }; 14 | */ 15 | UndirectedGraphNode *Solution::cloneGraph(UndirectedGraphNode *node) 16 | { 17 | if(node == NULL) 18 | return node; 19 | 20 | unordered_map mp; 21 | queue q; 22 | 23 | UndirectedGraphNode* src = new UndirectedGraphNode(node->label); 24 | mp[node] = src; 25 | 26 | q.push(node); 27 | 28 | while(!q.empty()) 29 | { 30 | UndirectedGraphNode* u = q.front(); 31 | q.pop(); 32 | 33 | vector v = u->neighbors; 34 | int n = v.size(); 35 | 36 | for(int i=0;ilabel); 41 | mp[v[i]] = temp; 42 | q.push(v[i]); 43 | } 44 | 45 | mp[u]->neighbors.push_back(mp[v[i]]); 46 | } 47 | } 48 | 49 | return src; 50 | } -------------------------------------------------------------------------------- /GraphDataStructure&Algorithms/LevelOrder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). 3 | 4 | Example : 5 | Given binary tree 6 | 7 | 3 8 | / \ 9 | 9 20 10 | / \ 11 | 15 7 12 | return its level order traversal as: 13 | 14 | [ 15 | [3], 16 | [9,20], 17 | [15,7] 18 | ] 19 | Also think about a version of the question where you are asked to do a level order traversal of the tree when depth of the tree is much greater than number of nodes on a level. 20 | 21 | LINK: https://www.interviewbit.com/problems/level-order/ 22 | */ 23 | 24 | /** 25 | * Definition for binary tree 26 | * struct TreeNode { 27 | * int val; 28 | * TreeNode *left; 29 | * TreeNode *right; 30 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 31 | * }; 32 | */ 33 | 34 | map > mp; 35 | 36 | void traverse(TreeNode* root, int d) 37 | { 38 | if(!root) 39 | return; 40 | 41 | mp[d].push_back(root->val); 42 | 43 | traverse(root->left, d+1); 44 | traverse(root->right, d+1); 45 | } 46 | 47 | vector > Solution::levelOrder(TreeNode* A) 48 | { 49 | mp.clear(); 50 | 51 | traverse(A, 0); 52 | 53 | vector > res; 54 | 55 | for(auto x : mp) 56 | res.push_back(x.second); 57 | 58 | return res; 59 | } -------------------------------------------------------------------------------- /GraphDataStructure&Algorithms/SmallestSequenceWithGivenPrimes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given three prime number(p1, p2, p3) and an integer k. Find the first(smallest) k integers which have only p1, p2, p3 or a combination of them as their prime factors. 3 | 4 | Example: 5 | 6 | Input : 7 | Prime numbers : [2,3,5] 8 | k : 5 9 | 10 | If primes are given as p1=2, p2=3 and p3=5 and k is given as 5, then the sequence of first 5 integers will be: 11 | 12 | Output: 13 | {2,3,4,5,6} 14 | 15 | Explanation : 16 | 4 = p1 * p1 ( 2 * 2 ) 17 | 6 = p1 * p2 ( 2 * 3 ) 18 | 19 | Note: The sequence should be sorted in ascending order 20 | 21 | LINK: https://www.interviewbit.com/problems/smallest-sequence-with-given-primes/ 22 | */ 23 | 24 | vector Solution::solve(int A, int B, int C, int D) 25 | { 26 | vector res; 27 | if(D==0) 28 | return res; 29 | 30 | int ia = 0, ib = 0, ic = 0; 31 | int nexta = A, nextb = B, nextc = C; 32 | 33 | for(int i=0;i res; 21 | int a; 22 | int b; 23 | 24 | void solve(ll num) 25 | { 26 | if(num>b) 27 | return; 28 | 29 | if(num>=a) 30 | res.push_back(num); 31 | 32 | int lastDig = num%10; 33 | 34 | if(lastDig == 0) 35 | solve(num*10 + 1); 36 | else 37 | if(lastDig == 9) 38 | solve(num*10 + 8); 39 | else 40 | { 41 | solve(num*10 + lastDig - 1); 42 | solve(num*10 + lastDig + 1); 43 | } 44 | } 45 | 46 | vector Solution::stepnum(int A, int B) 47 | { 48 | res.clear(); 49 | a = A; 50 | b = B; 51 | 52 | if(A>B) 53 | return res; 54 | 55 | if(A==0) 56 | res.push_back(0); 57 | 58 | for(int i=1;i<=9;i++) 59 | solve(i); 60 | 61 | if(!res.empty()) 62 | sort(res.begin(), res.end()); 63 | 64 | return res; 65 | } -------------------------------------------------------------------------------- /GraphDataStructure&Algorithms/SumOfFibonacciNumbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | How many minimum numbers from fibonacci series are required such that sum of numbers should be equal to a given Number N? 3 | Note : repetition of number is allowed. 4 | 5 | Example: 6 | 7 | N = 4 8 | Fibonacci numbers : 1 1 2 3 5 .... so on 9 | here 2 + 2 = 4 10 | so minimum numbers will be 2 11 | 12 | LINK: https://www.interviewbit.com/problems/sum-of-fibonacci-numbers/ 13 | */ 14 | 15 | int Solution::fibsum(int A) 16 | { 17 | if(A==0) 18 | return 0; 19 | 20 | vector fibb = {1,2}; 21 | 22 | int i = 1; 23 | 24 | while(1) 25 | { 26 | if(fibb[i] > A-fibb[i-1]) 27 | break; 28 | 29 | fibb.push_back(fibb[i] + fibb[i-1]); 30 | i++; 31 | } 32 | 33 | int n = fibb.size(); 34 | int cnt = 0; 35 | i = n-1; 36 | 37 | while(A) 38 | { 39 | cnt += A/fibb[i]; 40 | A = A%fibb[i]; 41 | i--; 42 | } 43 | return cnt; 44 | } -------------------------------------------------------------------------------- /Greedy/AssignMiceToHoles.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There are N Mice and N holes are placed in a straight line. 3 | Each hole can accomodate only 1 mouse. 4 | A mouse can stay at his position, move one step right from x to x + 1, or move one step left from x to x − 1. Any of these moves consumes 1 minute. 5 | Assign mice to holes so that the time when the last mouse gets inside a hole is minimized. 6 | 7 | Example: 8 | 9 | positions of mice are: 10 | 4 -4 2 11 | positions of holes are: 12 | 4 0 5 13 | 14 | Assign mouse at position x=4 to hole at position x=4 : Time taken is 0 minutes 15 | Assign mouse at position x=-4 to hole at position x=0 : Time taken is 4 minutes 16 | Assign mouse at position x=2 to hole at position x=5 : Time taken is 3 minutes 17 | After 4 minutes all of the mice are in the holes. 18 | 19 | Since, there is no combination possible where the last mouse's time is less than 4, 20 | answer = 4. 21 | Input: 22 | 23 | A : list of positions of mice 24 | B : list of positions of holes 25 | Output: 26 | 27 | single integer value 28 | NOTE: The final answer will fit in a 32 bit signed integer. 29 | 30 | LINK: https://www.interviewbit.com/problems/assign-mice-to-holes/ 31 | */ 32 | 33 | int Solution::mice(vector &A, vector &B) 34 | { 35 | int n = A.size(); 36 | 37 | sort(A.begin(), A.end()); 38 | sort(B.begin(), B.end()); 39 | 40 | int ans = -1; 41 | 42 | for(int i=0;i &A) 21 | { 22 | int n = A.size(); 23 | int sum = 0; 24 | int temp = 1; 25 | 26 | for(int i=0;i &A) 21 | { 22 | int n = A.size(); 23 | 24 | vector l(n,1), r(n,1); 25 | 26 | for(int i=1;i A[i-1]) 28 | l[i] = l[i-1] + 1; 29 | 30 | for(int i=n-2;i>=0;i--) 31 | if(A[i] > A[i+1]) 32 | r[i] = r[i+1] + 1; 33 | 34 | int ans = 0; 35 | 36 | for(int i=0;i 70*50*100 = 350000 13 | 14 | LINK: https://www.interviewbit.com/problems/highest-product/ 15 | */ 16 | 17 | int Solution::maxp3(vector &A) 18 | { 19 | int n = A.size(); 20 | 21 | sort(A.begin(), A.end()); 22 | 23 | return max(A[n-1]*A[n-2]*A[n-3], A[n-1]*A[0]*A[1]); 24 | } 25 | -------------------------------------------------------------------------------- /Greedy/MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of size n, find the majority element. The majority element is the element that appears more than floor(n/2) times. 3 | 4 | You may assume that the array is non-empty and the majority element always exist in the array. 5 | 6 | Example : 7 | 8 | Input : [2, 1, 2] 9 | Return : 2 which occurs 2 times which is greater than 3/2. 10 | 11 | LINK: https://www.interviewbit.com/problems/majority-element/ 12 | */ 13 | 14 | int Solution::majorityElement(const vector &A) 15 | { 16 | int n = A.size(); 17 | int cnt = 1; 18 | int majInd = 0; 19 | 20 | for(int i=1;i Solution::twoSum(const vector &A, int B) 16 | { 17 | unordered_map hash; 18 | 19 | int n = A.size(); 20 | vector res; 21 | 22 | for(int i=0;i > Solution::anagrams(const vector &A) 20 | { 21 | vector > res; 22 | vector v; 23 | int n = A.size(); 24 | 25 | for(int i=0;i > mp; 33 | 34 | for(int i=0;isecond); 39 | return res; 40 | } 41 | -------------------------------------------------------------------------------- /Hashing/ColorfulNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | For Given Number N find if its COLORFUL number or not 3 | 4 | Return 0/1 5 | 6 | COLORFUL number: 7 | 8 | A number can be broken into different contiguous sub-subsequence parts. 9 | Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. 10 | And this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different 11 | Example: 12 | 13 | N = 23 14 | 2 3 23 15 | 2 -> 2 16 | 3 -> 3 17 | 23 -> 6 18 | this number is a COLORFUL number since product of every digit of a sub-sequence are different. 19 | 20 | Output : 1 21 | 22 | LINK: https://www.interviewbit.com/problems/colorful-number/ 23 | */ 24 | 25 | int Solution::colorful(int A) 26 | { 27 | unordered_map hash; 28 | char s[20]; 29 | int len = sprintf(s,"%d",A); 30 | 31 | for(int i=0;i &A, int B) 21 | { 22 | unordered_map hash; 23 | 24 | int n=A.size(); 25 | 26 | for(int i=0;i mp; 36 | 37 | while(rem) 38 | { 39 | if(mp.find(rem)!=mp.end()) 40 | { 41 | res.insert(mp[rem],"("); 42 | res.push_back(')'); 43 | break; 44 | } 45 | 46 | mp[rem] = res.length(); 47 | rem *= 10; 48 | res.push_back(rem/b+'0'); 49 | rem %= b; 50 | } 51 | return res; 52 | } -------------------------------------------------------------------------------- /Hashing/LargestContinuousSequenceZeroSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the largest continuous sequence in a array which sums to zero. 3 | 4 | Example: 5 | 6 | 7 | Input: {1 ,2 ,-2 ,4 ,-4} 8 | Output: {2 ,-2 ,4 ,-4} 9 | 10 | NOTE : If there are multiple correct answers, return the sequence which occurs first in the array. 11 | 12 | LINK: https://www.interviewbit.com/problems/largest-continuous-sequence-zero-sum/ 13 | */ 14 | 15 | vector Solution::lszero(vector &A) 16 | { 17 | unordered_map hash; 18 | 19 | int n = A.size(); 20 | int sum=0; 21 | int st = INT_MAX, len = 0; 22 | 23 | for(int i=0;i len) 41 | { 42 | st = hash[sum]+1; 43 | len = i-hash[sum]; 44 | } 45 | } 46 | else 47 | hash[sum]=i; 48 | } 49 | 50 | vector res; 51 | 52 | for(int i=st;i mp; 17 | int res = 0, cnt = 0, i = 0; 18 | int n = A.size(); 19 | 20 | while(i Solution::findSubstring(string A, const vector &B) 17 | { 18 | int wrd_size = B[0].length(); 19 | int B_size = B.size(); 20 | int tlen = wrd_size*B_size; 21 | int n = A.length(); 22 | 23 | vector res; 24 | 25 | if(tlen>n) 26 | return res; 27 | 28 | unordered_map mp; 29 | 30 | for(int i=0;i temp = mp; 36 | int j = i; 37 | while(j < i+tlen) 38 | { 39 | string s = A.substr(j,wrd_size); 40 | 41 | if(temp.find(s)==temp.end()) 42 | break; 43 | else 44 | temp[s]--; 45 | j += wrd_size; 46 | } 47 | 48 | bool flag = true; 49 | for(auto it=temp.begin();it!=temp.end();it++) 50 | if(it->second>0) 51 | flag=false; 52 | 53 | if(flag) 54 | res.push_back(i); 55 | } 56 | return res; 57 | } -------------------------------------------------------------------------------- /HeapsAndMaps/DistinctNumbersInWindow.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array of N integers, A1, A2 ,…, AN and an integer K. Return the of count of distinct numbers in all windows of size K. 3 | 4 | Formally, return an array of size N-K+1 where i’th element in this array contains number of distinct elements in sequence Ai, Ai+1 ,…, Ai+k-1. 5 | 6 | Note: 7 | 8 | If K > N, return empty array. 9 | For example, 10 | 11 | A=[1, 2, 1, 3, 4, 3] and K = 3 12 | 13 | All windows of size K are 14 | 15 | [1, 2, 1] 16 | [2, 1, 3] 17 | [1, 3, 4] 18 | [3, 4, 3] 19 | 20 | So, we return an array [2, 3, 3, 2]. 21 | 22 | LINK: https://www.interviewbit.com/problems/distinct-numbers-in-window/ 23 | */ 24 | 25 | vector Solution::dNums(vector &A, int B) 26 | { 27 | vector res; 28 | 29 | int n = A.size(); 30 | if(B>n) 31 | return res; 32 | 33 | unordered_map mp; 34 | 35 | for(int i=0;i &B) 26 | { 27 | long long int ans = 0; 28 | int n = B.size(); 29 | priority_queue pq; 30 | 31 | for(int i=0;i Solution::solve(vector &A, vector &B) 24 | { 25 | vector res; 26 | 27 | sort(A.begin(), A.end()); 28 | sort(B.begin(), B.end()); 29 | 30 | int n = A.size(); 31 | 32 | priority_queue > > pq; 33 | set > st; 34 | 35 | pq.push({A[n-1]+B[n-1], {n-1, n-1}}); 36 | st.insert({n-1, n-1}); 37 | 38 | for(int k=0;k > pi = pq.top(); 41 | pq.pop(); 42 | 43 | res.push_back(pi.first); 44 | int i = pi.second.first; 45 | int j = pi.second.second; 46 | 47 | if(st.find({i-1, j})==st.end()) 48 | { 49 | st.insert({i-1, j}); 50 | pq.push({A[i-1]+B[j], {i-1, j}}); 51 | } 52 | if(st.find({i, j-1})==st.end()) 53 | { 54 | st.insert({i, j-1}); 55 | pq.push({A[i]+B[j-1], {i, j-1}}); 56 | } 57 | } 58 | return res; 59 | } -------------------------------------------------------------------------------- /LinkedLists/InsertionSortList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort a linked list using insertion sort. 3 | 4 | We have explained Insertion Sort at Slide 7 of Arrays 5 | 6 | Insertion Sort Wiki has some details on Insertion Sort as well. 7 | 8 | Example : 9 | 10 | Input : 1 -> 3 -> 2 11 | 12 | Return 1 -> 2 -> 3 13 | 14 | LINK: https://www.interviewbit.com/problems/insertion-sort-list/ 15 | */ 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * struct ListNode { 20 | * int val; 21 | * ListNode *next; 22 | * ListNode(int x) : val(x), next(NULL) {} 23 | * }; 24 | */ 25 | ListNode* Solution::insertionSortList(ListNode* A) 26 | { 27 | ListNode *head = NULL; 28 | ListNode *temp = A; 29 | 30 | while(temp) 31 | { 32 | ListNode *nxt = temp->next; 33 | if(head == NULL || head->val>=temp->val) 34 | { 35 | temp->next = head; 36 | head = temp; 37 | } 38 | else 39 | { 40 | ListNode *curr = head; 41 | while(curr->next!=NULL && curr->next->val < temp->val) 42 | curr = curr->next; 43 | temp->next = curr->next; 44 | curr->next = temp; 45 | } 46 | temp = nxt; 47 | } 48 | return head; 49 | } 50 | -------------------------------------------------------------------------------- /LinkedLists/Kreverselinkedlist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a singly linked list and an integer K, reverses the nodes of the 3 | 4 | list K at a time and returns modified linked list. 5 | 6 | NOTE : The length of the list is divisible by K 7 | Example : 8 | 9 | Given linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 and K=2, 10 | 11 | You should return 2 -> 1 -> 4 -> 3 -> 6 -> 5 12 | 13 | Try to solve the problem using constant extra space. 14 | 15 | LINK: https://www.interviewbit.com/problems/k-reverse-linked-list/ 16 | */ 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * struct ListNode { 21 | * int val; 22 | * ListNode *next; 23 | * ListNode(int x) : val(x), next(NULL) {} 24 | * }; 25 | */ 26 | ListNode* Solution::reverseList(ListNode* head, int k) 27 | { 28 | ListNode *prev,*curr,*next,*templ,*tempr; 29 | curr = templ = head; 30 | prev = tempr = NULL; 31 | int i=1,flag=0; 32 | 33 | while(curr!=NULL) 34 | { 35 | next = curr->next; 36 | curr->next = prev; 37 | prev = curr; 38 | curr = next; 39 | 40 | if(i==k) 41 | { 42 | if(flag==0) 43 | { 44 | head = prev; 45 | tempr = curr; 46 | flag = 1; 47 | } 48 | else 49 | { 50 | templ->next = prev; 51 | templ = tempr; 52 | tempr = curr; 53 | } 54 | i=0; 55 | prev = NULL; 56 | } 57 | i++; 58 | } 59 | 60 | return head; 61 | } 62 | -------------------------------------------------------------------------------- /LinkedLists/ListCycle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 3 | 4 | Try solving it using constant additional space. 5 | 6 | Example : 7 | 8 | Input : 9 | 10 | ______ 11 | | | 12 | \/ | 13 | 1 -> 2 -> 3 -> 4 14 | 15 | Return the node corresponding to node 3. 16 | 17 | LINK: https://www.interviewbit.com/problems/list-cycle/ 18 | */ 19 | 20 | /** 21 | * Definition for singly-linked list. 22 | * struct ListNode { 23 | * int val; 24 | * ListNode *next; 25 | * ListNode(int x) : val(x), next(NULL) {} 26 | * }; 27 | */ 28 | ListNode* Solution::detectCycle(ListNode* A) 29 | { 30 | // Do not write main() function. 31 | // Do not read input, instead use the arguments to the function. 32 | // Do not print the output, instead return values as specified 33 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 34 | 35 | if(A==NULL || A->next==NULL) 36 | return NULL; 37 | 38 | ListNode *slow,*fast; 39 | slow = A->next; 40 | fast = A->next->next; 41 | 42 | while(fast && fast->next) 43 | { 44 | if(slow == fast) 45 | break; 46 | slow = slow->next; 47 | fast = fast->next->next; 48 | } 49 | 50 | if(slow==fast) 51 | { 52 | slow = A; 53 | while(slow != fast) 54 | { 55 | slow = slow->next; 56 | fast = fast->next; 57 | } 58 | return slow; 59 | } 60 | else 61 | return NULL; 62 | } -------------------------------------------------------------------------------- /LinkedLists/MergeTwoSortedLists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Merge two sorted linked lists and return it as a new list. 3 | The new list should be made by splicing together the nodes of the first two lists, and should also be sorted. 4 | 5 | For example, given following linked lists : 6 | 7 | 5 -> 8 -> 20 8 | 4 -> 11 -> 15 9 | The merged list should be : 10 | 11 | 4 -> 5 -> 8 -> 11 -> 15 -> 20 12 | 13 | LINK: https://www.interviewbit.com/problems/merge-two-sorted-lists/ 14 | */ 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * struct ListNode { 19 | * int val; 20 | * ListNode *next; 21 | * ListNode(int x) : val(x), next(NULL) {} 22 | * }; 23 | */ 24 | ListNode* Solution::mergeTwoLists(ListNode* A, ListNode* B) 25 | { 26 | if(A==NULL) 27 | return B; 28 | if(B==NULL) 29 | return A; 30 | 31 | ListNode *tempA = A, *tempB = B, *head=NULL; 32 | 33 | if(A->valval) 34 | { 35 | head = A; 36 | tempA = tempA->next; 37 | } 38 | else 39 | { 40 | head = B; 41 | tempB = tempB->next; 42 | } 43 | 44 | ListNode *temp = head; 45 | 46 | while(tempA!=NULL && tempB!=NULL) 47 | { 48 | if(tempA->val < tempB->val) 49 | { 50 | temp->next = tempA; 51 | temp = tempA; 52 | tempA = tempA->next; 53 | } 54 | else 55 | { 56 | temp->next = tempB; 57 | temp = tempB; 58 | tempB = tempB->next; 59 | } 60 | } 61 | 62 | if(tempA!=NULL) 63 | temp->next=tempA; 64 | if(tempB!=NULL) 65 | temp->next=tempB; 66 | 67 | return head; 68 | } -------------------------------------------------------------------------------- /LinkedLists/PalindromeList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a singly linked list, determine if its a palindrome. Return 1 or 0 denoting if its a palindrome or not, respectively. 3 | 4 | Notes: 5 | 6 | Expected solution is linear in time and constant in space. 7 | For example, 8 | 9 | List 1-->2-->1 is a palindrome. 10 | List 1-->2-->3 is not a palindrome. 11 | 12 | LINK: https://www.interviewbit.com/problems/palindrome-list/ 13 | */ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode(int x) : val(x), next(NULL) {} 21 | * }; 22 | */ 23 | 24 | int ispalin(ListNode **left, ListNode *right) 25 | { 26 | if(right==NULL) 27 | return 1; 28 | 29 | int ck = ispalin(left, right->next); 30 | if(ck==0) 31 | return 0; 32 | 33 | int ckn = 0; 34 | if(((*left)->val) == (right->val)) 35 | ckn=1; 36 | 37 | *left = (*left)->next; 38 | return ckn; 39 | } 40 | 41 | int Solution::lPalin(ListNode* head) 42 | { 43 | return ispalin(&head, head); 44 | } -------------------------------------------------------------------------------- /LinkedLists/PartitionList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 3 | 4 | You should preserve the original relative order of the nodes in each of the two partitions. 5 | 6 | For example, 7 | Given 1->4->3->2->5->2 and x = 3, 8 | return 1->2->2->4->3->5. 9 | 10 | LINK: https://www.interviewbit.com/problems/partition-list/ 11 | */ 12 | 13 | /** 14 | * Definition for singly-linked list. 15 | * struct ListNode { 16 | * int val; 17 | * ListNode *next; 18 | * ListNode(int x) : val(x), next(NULL) {} 19 | * }; 20 | */ 21 | ListNode* Solution::partition(ListNode* A, int B) 22 | { 23 | ListNode *lhead = NULL, *rhead = NULL; 24 | ListNode *templ = NULL, *tempr = NULL; 25 | ListNode *temp = A; 26 | 27 | while(temp) 28 | { 29 | if(temp->val < B) 30 | { 31 | if(templ==NULL) 32 | lhead = templ = temp; 33 | else 34 | { 35 | templ->next = temp; 36 | templ = temp; 37 | } 38 | } 39 | else 40 | { 41 | if(tempr==NULL) 42 | rhead = tempr = temp; 43 | else 44 | { 45 | tempr->next = temp; 46 | tempr = temp; 47 | } 48 | } 49 | temp = temp->next; 50 | } 51 | 52 | if(lhead==NULL) 53 | return rhead; 54 | if(rhead==NULL) 55 | return lhead; 56 | templ->next = rhead; 57 | tempr->next = NULL; 58 | return lhead; 59 | } -------------------------------------------------------------------------------- /LinkedLists/RemoveDuplicatesfromSortedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted linked list, delete all duplicates such that each element appear only once. 3 | 4 | For example, 5 | Given 1->1->2, return 1->2. 6 | Given 1->1->2->3->3, return 1->2->3. 7 | 8 | LINK: https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list/ 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | * int val; 15 | * ListNode *next; 16 | * ListNode(int x) : val(x), next(NULL) {} 17 | * }; 18 | */ 19 | ListNode* Solution::deleteDuplicates(ListNode* head) 20 | { 21 | if(head==NULL) 22 | return head; 23 | 24 | int pval = head->val; 25 | ListNode *temp = head->next, *ptemp = head; 26 | 27 | while(temp!=NULL) 28 | { 29 | if(temp->val == pval) 30 | { 31 | temp = temp->next; 32 | } 33 | else 34 | { 35 | ptemp->next = temp; 36 | ptemp = temp; 37 | pval = ptemp->val; 38 | temp = temp->next; 39 | } 40 | } 41 | 42 | ptemp->next = temp; 43 | return head; 44 | } -------------------------------------------------------------------------------- /LinkedLists/RemoveNthNodefromListEnd.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, remove the nth node from the end of list and return its head. 3 | 4 | For example, 5 | Given linked list: 1->2->3->4->5, and n = 2. 6 | After removing the second node from the end, the linked list becomes 1->2->3->5. 7 | 8 | Note: 9 | If n is greater than the size of the list, remove the first node of the list. 10 | Try doing it using constant additional space. 11 | 12 | LINK: https://www.interviewbit.com/problems/remove-nth-node-from-list-end/ 13 | */ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode(int x) : val(x), next(NULL) {} 21 | * }; 22 | */ 23 | ListNode* Solution::removeNthFromEnd(ListNode* A, int B) 24 | { 25 | if(A==NULL) 26 | return A; 27 | 28 | ListNode *temp = A; 29 | int cnt=0; 30 | while(temp) 31 | { 32 | temp = temp->next; 33 | cnt++; 34 | } 35 | 36 | int n=cnt-B; 37 | if(n<=0) 38 | { 39 | A = A->next; 40 | return A; 41 | } 42 | temp = A; 43 | 44 | for(int i=0;inext; 46 | temp->next = temp->next->next; 47 | 48 | return A; 49 | } 50 | -------------------------------------------------------------------------------- /LinkedLists/ReorderList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a singly linked list 3 | 4 | L: L0 → L1 → … → Ln-1 → Ln, 5 | reorder it to: 6 | 7 | L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → … 8 | You must do this in-place without altering the nodes’ values. 9 | 10 | For example, 11 | Given {1,2,3,4}, reorder it to {1,4,2,3}. 12 | 13 | LINK: https://www.interviewbit.com/problems/reorder-list/ 14 | */ 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * struct ListNode { 19 | * int val; 20 | * ListNode *next; 21 | * ListNode(int x) : val(x), next(NULL) {} 22 | * }; 23 | */ 24 | 25 | ListNode* reverseList(ListNode* head) 26 | { 27 | ListNode *prev,*curr,*next; 28 | curr = head; 29 | prev = NULL; 30 | while(curr!=NULL) 31 | { 32 | next = curr->next; 33 | curr->next = prev; 34 | prev = curr; 35 | curr = next; 36 | } 37 | head = prev; 38 | return head; 39 | } 40 | 41 | ListNode* Solution::reorderList(ListNode* A) 42 | { 43 | ListNode *slow = A, *fast = A->next; 44 | while(fast && fast->next) 45 | { 46 | slow = slow->next; 47 | fast = fast->next->next; 48 | } 49 | 50 | ListNode *head1 = A; 51 | ListNode *head2 = slow->next; 52 | slow->next = NULL; 53 | 54 | head2 = reverseList(head2); 55 | 56 | while(head1 && head2) 57 | { 58 | ListNode *next1 = head1->next, *next2 = head2->next; 59 | 60 | head1->next = head2; 61 | head2->next = next1; 62 | head1 = next1; 63 | head2 = next2; 64 | } 65 | 66 | if(head2) 67 | head1->next = head2; 68 | 69 | return A; 70 | } -------------------------------------------------------------------------------- /LinkedLists/ReverseLinkListII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 6 | 7 | return 1->4->3->2->5->NULL. 8 | 9 | Note: 10 | Given m, n satisfy the following condition: 11 | 1 ≤ m ≤ n ≤ length of list. Note 2: 12 | Usually the version often seen in the interviews is reversing the whole linked list which is obviously an easier version of this question. 13 | 14 | LINK: https://www.interviewbit.com/problems/reverse-link-list-ii/ 15 | */ 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * struct ListNode { 20 | * int val; 21 | * ListNode *next; 22 | * ListNode(int x) : val(x), next(NULL) {} 23 | * }; 24 | */ 25 | ListNode* Solution::reverseBetween(ListNode* A, int m, int n) 26 | { 27 | if(m==n) 28 | return A; 29 | ListNode *temp = A; 30 | int i=1; 31 | while(inext; 34 | i++; 35 | } 36 | ListNode *prev = temp->next, *cur = temp->next->next, *next=NULL; 37 | if(m==1) 38 | { 39 | prev = temp; 40 | cur = temp->next; 41 | n++; 42 | } 43 | 44 | while(inext; 47 | cur->next = prev; 48 | prev = cur; 49 | cur = next; 50 | i++; 51 | } 52 | 53 | if(m==1) 54 | { 55 | A->next = cur; 56 | A = prev; 57 | } 58 | else 59 | { 60 | temp->next->next = cur; 61 | temp->next = prev; 62 | } 63 | return A; 64 | } -------------------------------------------------------------------------------- /LinkedLists/RotateList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a list, rotate the list to the right by k places, where k is non-negative. 3 | 4 | For example: 5 | 6 | Given 1->2->3->4->5->NULL and k = 2, 7 | return 4->5->1->2->3->NULL. 8 | 9 | LINK: https://www.interviewbit.com/problems/rotate-list/ 10 | */ 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * struct ListNode { 15 | * int val; 16 | * ListNode *next; 17 | * ListNode(int x) : val(x), next(NULL) {} 18 | * }; 19 | */ 20 | ListNode* Solution::rotateRight(ListNode* A, int B) 21 | { 22 | if(A==NULL) 23 | return A; 24 | 25 | ListNode *temp = A, *head = A; 26 | int cnt=0; 27 | while(temp) 28 | { 29 | temp = temp->next; 30 | cnt++; 31 | } 32 | 33 | B = B%cnt; 34 | if(B==0) 35 | return A; 36 | B = cnt-B; 37 | 38 | temp = A; 39 | for(int i=0;inext; 41 | 42 | head = temp->next; 43 | temp->next = NULL; 44 | temp = head; 45 | while(temp->next) 46 | temp = temp->next; 47 | temp->next = A; 48 | 49 | return head; 50 | } -------------------------------------------------------------------------------- /LinkedLists/SwapListNodesinpairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | For example, 5 | Given 1->2->3->4, you should return the list as 2->1->4->3. 6 | 7 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 8 | 9 | LINK: https://www.interviewbit.com/problems/swap-list-nodes-in-pairs/ 10 | */ 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * struct ListNode { 15 | * int val; 16 | * ListNode *next; 17 | * ListNode(int x) : val(x), next(NULL) {} 18 | * }; 19 | */ 20 | ListNode* Solution::swapPairs(ListNode* head) 21 | { 22 | if(!head || !head->next) 23 | return head; 24 | 25 | ListNode *fst = head, *sec = head->next; 26 | fst->next = swapPairs(sec->next); 27 | sec->next = fst; 28 | head = sec; 29 | return head; 30 | } 31 | -------------------------------------------------------------------------------- /Math/ExcelColumnNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a column title as appears in an Excel sheet, return its corresponding column number. 3 | 4 | Example: 5 | 6 | A -> 1 7 | 8 | B -> 2 9 | 10 | C -> 3 11 | 12 | ... 13 | 14 | Z -> 26 15 | 16 | AA -> 27 17 | 18 | AB -> 28 19 | 20 | LINK: https://www.interviewbit.com/problems/excel-column-number/ 21 | */ 22 | 23 | int Solution::titleToNumber(string A) 24 | { 25 | int n=A.length(); 26 | 27 | int ans=0; 28 | 29 | for(int i=0;i A 7 | 2 -> B 8 | 3 -> C 9 | ... 10 | 26 -> Z 11 | 27 -> AA 12 | 28 -> AB 13 | 14 | LINK: https://www.interviewbit.com/problems/excel-column-title/ 15 | */ 16 | 17 | string Solution::convertToTitle(int A) 18 | { 19 | string s=""; 20 | 21 | while(A) 22 | { 23 | int r = (A%26)-1; 24 | if(r<0) 25 | { 26 | r+=26; 27 | A--; 28 | } 29 | s += r +'A'; 30 | A/=26; 31 | } 32 | reverse(s.begin(), s.end()); 33 | return s; 34 | } 35 | -------------------------------------------------------------------------------- /Math/FizzBuzz.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a positive integer N, print all the integers from 1 to N. But for multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. Also for number which are multiple of 3 and 5, prints “FizzBuzz”. 3 | 4 | Example 5 | 6 | N = 5 7 | Return: [1 2 Fizz 4 Buzz] 8 | Note: Instead of printing the answer, you have to return it as list of strings. 9 | 10 | LINK: https://www.interviewbit.com/problems/fizzbuzz/ 11 | */ 12 | 13 | vector Solution::fizzBuzz(int A) 14 | { 15 | vector v; 16 | for(int i=1;i<=A;i++) 17 | { 18 | if(i%3!=0 && i%5!=0) 19 | v.push_back(to_string(i)); 20 | else 21 | { 22 | string s=""; 23 | if(i%3==0) 24 | s+="Fizz"; 25 | if(i%5==0) 26 | s+="Buzz"; 27 | v.push_back(s); 28 | } 29 | } 30 | return v; 31 | } -------------------------------------------------------------------------------- /Math/GreatestCommonDivisor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given 2 non negative integers m and n, find gcd(m, n) 3 | 4 | GCD of 2 integers m and n is defined as the greatest integer g such that g is a divisor of both m and n. 5 | Both m and n fit in a 32 bit signed integer. 6 | 7 | Example 8 | 9 | m : 6 10 | n : 9 11 | 12 | GCD(m, n) : 3 13 | 14 | LINK: https://www.interviewbit.com/problems/greatest-common-divisor/ 15 | */ 16 | 17 | int Solution::gcd(int A, int B) 18 | { 19 | if(B==0) 20 | return A; 21 | else 22 | return gcd(B,A%B); 23 | } -------------------------------------------------------------------------------- /Math/GridUniquePaths.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A robot is located at the top-left corner of an A x B grid (marked ‘Start’ in the diagram below). 3 | 4 | Path Sum: Example 1 5 | 6 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below). 7 | 8 | How many possible unique paths are there? 9 | 10 | Note: A and B will be such that the resulting answer fits in a 32 bit signed integer. 11 | 12 | Example : 13 | 14 | Input : A = 2, B = 2 15 | Output : 2 16 | 17 | 2 possible routes : (0, 0) -> (0, 1) -> (1, 1) 18 | OR : (0, 0) -> (1, 0) -> (1, 1) 19 | 20 | LINK: https://www.interviewbit.com/problems/grid-unique-paths/ 21 | */ 22 | 23 | int calc(long long int n,long long int r) 24 | { 25 | if(n==r) 26 | return 1; 27 | long long ans = 1; 28 | for(long long int i=0;i 1 and A > 0. A and P both should be integers. 3 | 4 | Example 5 | 6 | Input : 4 7 | Output : True 8 | as 2^2 = 4. 9 | 10 | LINK: https://www.interviewbit.com/problems/power-of-two-integers/ 11 | */ 12 | 13 | typedef long long int ll; 14 | 15 | int Solution::isPower(int A) 16 | { 17 | if(A==1) 18 | return 1; 19 | 20 | for(ll i=2;i*i<=A;i++) 21 | { 22 | for(ll j=i*i;j<=A;j*=i) 23 | { 24 | if(j==A) 25 | return 1; 26 | } 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Math/PrimeSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an even number ( greater than 2 ), return two prime numbers whose sum will be equal to given number. 3 | 4 | NOTE A solution will always exist. read Goldbach’s conjecture 5 | 6 | Example: 7 | 8 | 9 | Input : 4 10 | Output: 2 + 2 = 4 11 | 12 | If there are more than one solutions possible, return the lexicographically smaller solution. 13 | 14 | If [a, b] is one solution with a <= b, 15 | and [c,d] is another solution with c <= d, then 16 | 17 | [a, b] < [c, d] 18 | 19 | If a < c OR a==c AND b < d. 20 | 21 | LINK: https://www.interviewbit.com/problems/prime-sum/ 22 | */ 23 | 24 | vector Solution::primesum(int A) 25 | { 26 | vector v(A+1,0); 27 | v[0]=v[1]=1; 28 | 29 | for(int i=2;i*i<=A;i++) 30 | { 31 | if(v[i]==0) 32 | { 33 | for(int j=i*i;j<=A;j+=i) 34 | v[j]=1; 35 | } 36 | } 37 | 38 | vector prime; 39 | 40 | for(int i=0;i<=A;i++) 41 | { 42 | if(v[i]==0 && v[A-i]==0) 43 | { 44 | vector ans = {i, A-i}; 45 | return ans; 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Math/RearrangeArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rearrange a given array so that Arr[i] becomes Arr[Arr[i]] with O(1) extra space. 3 | 4 | Example: 5 | 6 | Input : [1, 0] 7 | Return : [0, 1] 8 | Lets say N = size of the array. Then, following holds true : 9 | All elements in the array are in the range [0, N-1] 10 | N * N does not overflow for a signed integer 11 | 12 | LINK: https://www.interviewbit.com/problems/rearrange-array/ 13 | */ 14 | 15 | void Solution::arrange(vector &A) 16 | { 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 | int n = A.size(); 23 | 24 | for(int i=0;i= INT_MAX/10) 35 | return 0; 36 | s = s*10 + (A%10); 37 | A /= 10; 38 | } 39 | 40 | if(flag) 41 | s=s*-1; 42 | return s; 43 | } -------------------------------------------------------------------------------- /Math/SortedPermutationRank.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, find the rank of the string amongst its permutations sorted lexicographically. 3 | Assume that no characters are repeated. 4 | 5 | Example : 6 | 7 | Input : 'acb' 8 | Output : 2 9 | 10 | The order permutations with letters 'a', 'c', and 'b' : 11 | abc 12 | acb 13 | bac 14 | bca 15 | cab 16 | cba 17 | The answer might not fit in an integer, so return your answer % 1000003 18 | 19 | LINK: https://www.interviewbit.com/problems/sorted-permutation-rank/ 20 | */ 21 | 22 | typedef long long int ll; 23 | #define MOD 1000003 24 | 25 | ll fact(ll n) 26 | { 27 | if(n<=1) 28 | return 1; 29 | else 30 | return (n%MOD * fact(n-1)%MOD)%MOD; 31 | } 32 | 33 | 34 | int Solution::findRank(string A) 35 | { 36 | ll n = A.length(); 37 | ll mul = fact(n); 38 | 39 | ll rank = 0; 40 | 41 | for(int i=0;iA[j]) 49 | cnt++; 50 | 51 | rank +=(cnt*fact(n-i-1))%MOD; 52 | } 53 | 54 | return (rank+1)%MOD; 55 | } -------------------------------------------------------------------------------- /Math/SumofpairwiseHammingDistance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Hamming distance between two non-negative integers is defined as the number of positions at which the corresponding bits are different. 3 | 4 | For example, 5 | 6 | HammingDistance(2, 7) = 2, as only the first and the third bit differs in the binary representation of 2 (010) and 7 (111). 7 | 8 | Given an array of N non-negative integers, find the sum of hamming distances of all pairs of integers in the array. 9 | Return the answer modulo 1000000007. 10 | 11 | Example 12 | 13 | Let f(x, y) be the hamming distance defined above. 14 | 15 | A=[2, 4, 6] 16 | 17 | We return, 18 | f(2, 2) + f(2, 4) + f(2, 6) + 19 | f(4, 2) + f(4, 4) + f(4, 6) + 20 | f(6, 2) + f(6, 4) + f(6, 6) = 21 | 22 | 0 + 2 + 1 23 | 2 + 0 + 1 24 | 1 + 1 + 0 = 8 25 | 26 | LINK: https://www.interviewbit.com/problems/sum-of-pairwise-hamming-distance/ 27 | */ 28 | 29 | #define MOD 1000000007 30 | 31 | int Solution::hammingDistance(const vector &A) 32 | { 33 | int n=A.size(); 34 | int bit[32]; 35 | memset(bit,0,sizeof(bit)); 36 | 37 | for(int i=0;i>j)&1) 42 | bit[j]++; 43 | } 44 | } 45 | 46 | long long int ans = 0; 47 | 48 | for(int i=0;i<31;i++) 49 | { 50 | long long int a = bit[i], b = n-bit[i]; 51 | ans += ((a%MOD)*(b%MOD))%MOD; 52 | } 53 | ans = (ans*2)%MOD; 54 | 55 | return ans; 56 | } -------------------------------------------------------------------------------- /Math/TrailingZerosinFactorial.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return the number of trailing zeroes in n!. 3 | 4 | Note: Your solution should be in logarithmic time complexity. 5 | 6 | Example : 7 | 8 | n = 5 9 | n! = 120 10 | Number of trailing zeros = 1 11 | So, return 1 12 | 13 | LINK: https://www.interviewbit.com/problems/trailing-zeros-in-factorial/ 14 | */ 15 | 16 | int Solution::trailingZeroes(int A) 17 | { 18 | int n=5,ans=0; 19 | while(n<=A) 20 | { 21 | ans += (A/n); 22 | n *= 5; 23 | } 24 | return ans; 25 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # InterviewBit 2 | 3 | InterviewBit Programming Solutions. 4 | 5 | https://www.interviewbit.com 6 | -------------------------------------------------------------------------------- /StacksAndQueues/EvaluateExpression.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 3 | 4 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 5 | 6 | Examples: 7 | 8 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 9 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 10 | 11 | LINK: https://www.interviewbit.com/problems/evaluate-expression/ 12 | */ 13 | 14 | int Solution::evalRPN(vector &A) 15 | { 16 | stack st; 17 | int n = A.size(); 18 | 19 | for(int i=0;i &A) 20 | { 21 | int n = A.size(); 22 | int mxarea = 0, i = 0; 23 | 24 | stack st; 25 | 26 | while(i st, mnst; 26 | 27 | MinStack::MinStack() 28 | { 29 | stack temp1, temp2; 30 | swap(st,temp1); 31 | swap(mnst,temp2); 32 | } 33 | 34 | void MinStack::push(int x) 35 | { 36 | st.push(x); 37 | if(mnst.empty() || x<=mnst.top()) 38 | mnst.push(x); 39 | } 40 | 41 | void MinStack::pop() 42 | { 43 | if(!st.empty()) 44 | { 45 | int x = st.top(); 46 | st.pop(); 47 | if(x==mnst.top()) 48 | mnst.pop(); 49 | } 50 | } 51 | 52 | int MinStack::top() 53 | { 54 | if(!st.empty()) 55 | return st.top(); 56 | return -1; 57 | } 58 | 59 | int MinStack::getMin() 60 | { 61 | if(!st.empty()) 62 | return mnst.top(); 63 | return -1; 64 | } -------------------------------------------------------------------------------- /StacksAndQueues/NearestSmallerElement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i. 3 | 4 | More formally, 5 | 6 | G[i] for an element A[i] = an element A[j] such that 7 | j is maximum possible AND 8 | j < i AND 9 | A[j] < A[i] 10 | Elements for which no smaller element exist, consider next smaller element as -1. 11 | 12 | Example: 13 | 14 | Input : A : [4, 5, 2, 10, 8] 15 | Return : [-1, 4, -1, 2, 2] 16 | 17 | Example 2: 18 | 19 | Input : A : [3, 2, 1] 20 | Return : [-1, -1, -1] 21 | 22 | LINK: https://www.interviewbit.com/problems/nearest-smaller-element/ 23 | */ 24 | 25 | vector Solution::prevSmaller(vector &A) 26 | { 27 | stack st; 28 | int n = A.size(); 29 | vector v; 30 | 31 | for(int i=0;i= A[i]) 34 | st.pop(); 35 | if(st.empty()) 36 | v.push_back(-1); 37 | else 38 | v.push_back(st.top()); 39 | st.push(A[i]); 40 | } 41 | return v; 42 | } -------------------------------------------------------------------------------- /StacksAndQueues/RainWaterTrapped.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 3 | 4 | Example : 5 | 6 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 7 | 8 | Rain water trapped: Example 1 9 | 10 | The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. 11 | In this case, 6 units of rain water (blue section) are being trapped. 12 | 13 | LINK: https://www.interviewbit.com/problems/rain-water-trapped/ 14 | */ 15 | 16 | int Solution::trap(const vector &A) 17 | { 18 | int n = A.size(); 19 | 20 | int l = 0, r = n-1; 21 | int lmx = 0, rmx = 0, ans = 0; 22 | 23 | while(l<=r) 24 | { 25 | if(A[l] lmx) 28 | lmx = A[l]; 29 | else 30 | ans += lmx - A[l]; 31 | l++; 32 | } 33 | else 34 | { 35 | if(A[r] > rmx) 36 | rmx = A[r]; 37 | else 38 | ans += rmx - A[r]; 39 | r--; 40 | } 41 | } 42 | return ans; 43 | } -------------------------------------------------------------------------------- /StacksAndQueues/RedundantBraces.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to validate if the input string has redundant braces? 3 | Return 0/1 4 | 5 | 0 -> NO 6 | 1 -> YES 7 | Input will be always a valid expression 8 | 9 | and operators allowed are only + , * , - , / 10 | 11 | Example: 12 | 13 | ((a + b)) has redundant braces so answer will be 1 14 | (a + (a + b)) doesn't have have any redundant braces so answer will be 0 15 | 16 | LINK: https://www.interviewbit.com/problems/redundant-braces/ 17 | */ 18 | 19 | int Solution::braces(string s) 20 | { 21 | stack st; 22 | int n = s.length(); 23 | 24 | for(int i=0;i "/home" 7 | path = "/a/./b/../../c/", => "/c" 8 | Note that absolute path always begin with ‘/’ ( root directory ) 9 | Path will not have whitespace characters. 10 | 11 | LINK: https://www.interviewbit.com/problems/simplify-directory-path/ 12 | */ 13 | 14 | string Solution::simplifyPath(string s) 15 | { 16 | int n = s.length(); 17 | 18 | stack st; 19 | string temp = ""; 20 | string res = ""; 21 | 22 | for(int i=0;i0) 42 | st.push(temp); 43 | } 44 | 45 | while(!st.empty()) 46 | { 47 | temp = st.top(); 48 | st.pop(); 49 | if(res=="") 50 | res = temp; 51 | else 52 | res = temp + "/" + res; 53 | } 54 | res = "/" + res; 55 | return res; 56 | } -------------------------------------------------------------------------------- /Strings/AddBinaryStrings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary strings, return their sum (also a binary string). 3 | 4 | Example: 5 | 6 | a = "100" 7 | 8 | b = "11" 9 | Return a + b = “111”. 10 | 11 | LINK: https://www.interviewbit.com/problems/add-binary-strings/ 12 | */ 13 | 14 | string Solution::addBinary(string A, string B) 15 | { 16 | reverse(A.begin(), A.end()); 17 | reverse(B.begin(), B.end()); 18 | int an = A.length(); 19 | int bn = B.length(); 20 | int i=0,j=0,carry=0; 21 | string s=""; 22 | 23 | while(i=INT_MAX) 46 | return INT_MAX; 47 | if(neg==1 && (-1*res)<=INT_MIN) 48 | return INT_MIN; 49 | i++; 50 | } 51 | 52 | if(neg) 53 | res*=-1; 54 | return (int)res; 55 | } -------------------------------------------------------------------------------- /Strings/CountAndSay.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The count-and-say sequence is the sequence of integers beginning as follows: 3 | 4 | 1, 11, 21, 1211, 111221, ... 5 | 1 is read off as one 1 or 11. 6 | 11 is read off as two 1s or 21. 7 | 8 | 21 is read off as one 2, then one 1 or 1211. 9 | 10 | Given an integer n, generate the nth sequence. 11 | 12 | Note: The sequence of integers will be represented as a string. 13 | 14 | Example: 15 | 16 | if n = 2, 17 | the sequence is 11. 18 | 19 | LINK: https://www.interviewbit.com/problems/count-and-say/ 20 | */ 21 | 22 | string Solution::countAndSay(int n) 23 | { 24 | string s="1"; 25 | n--; 26 | 27 | while(n--) 28 | { 29 | string temp=""; 30 | int cnt=1, len=s.size(); 31 | for(int i=1;i0 && s[n-1]==' ') 36 | n--; 37 | 38 | if(ind>=n) 39 | return 0; 40 | else 41 | return (n-ind); 42 | } 43 | -------------------------------------------------------------------------------- /Strings/LongestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | 4 | Longest common prefix for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2. 5 | 6 | As an example, longest common prefix of "abcdefgh" and "abcefgh" is "abc". 7 | 8 | Given the array of strings, you need to find the longest S which is the prefix of ALL the strings in the array. 9 | 10 | Example: 11 | 12 | Given the array as: 13 | 14 | [ 15 | 16 | "abcdefgh", 17 | 18 | "aefghijk", 19 | 20 | "abcefgh" 21 | ] 22 | The answer would be “a”. 23 | 24 | LINK: https://www.interviewbit.com/problems/longest-common-prefix/ 25 | */ 26 | 27 | string Solution::longestCommonPrefix(vector &s) 28 | { 29 | int n = s.size(); 30 | int mnl = INT_MAX; 31 | 32 | for(int i=0;i=0 && high maxlen || ((high-low+1)==maxlen && low=0 && high maxlen || ((high-low+1)==maxlen && low0) 25 | { 26 | if(ispalin(s)) 27 | break; 28 | else 29 | { 30 | cnt++; 31 | s.erase(s.end()-1); 32 | } 33 | } 34 | return cnt; 35 | } -------------------------------------------------------------------------------- /Strings/MultiplyStrings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two numbers represented as strings, return multiplication of the numbers as a string. 3 | 4 | Note: The numbers can be arbitrarily large and are non-negative. 5 | Note2: Your answer should not have leading zeroes. For example, 00 is not a valid answer. 6 | For example, 7 | given strings "12", "10", your answer should be “120”. 8 | 9 | NOTE : DO NOT USE BIG INTEGER LIBRARIES ( WHICH ARE AVAILABLE IN JAVA / PYTHON ). 10 | We will retroactively disqualify such submissions and the submissions will incur penalties. 11 | 12 | LINK: https://www.interviewbit.com/problems/multiply-strings/ 13 | */ 14 | 15 | string Solution::multiply(string A, string B) 16 | { 17 | int na = A.length(), nb = B.length(); 18 | 19 | vector v(na+nb, 0); 20 | 21 | int ina = 0, inb = 0; 22 | 23 | for(int i=na-1;i>=0;i--) 24 | { 25 | int carry = 0; 26 | int num1 = A[i]-'0'; 27 | 28 | inb = 0; 29 | 30 | for(int j=nb-1;j>=0;j--) 31 | { 32 | int num2 = B[j]-'0'; 33 | int sum = (num1*num2) + v[ina+inb] + carry; 34 | carry = sum/10; 35 | v[ina+inb] = sum%10; 36 | inb++; 37 | } 38 | if(carry>0) 39 | v[ina+inb]+=carry; 40 | ina++; 41 | } 42 | 43 | int i =v.size()-1; 44 | while(i>=0 && v[i]==0) 45 | i--; 46 | 47 | if(i==-1) 48 | return "0"; 49 | 50 | string ans = ""; 51 | 52 | while(i>=0) 53 | ans.push_back(v[i--]+'0'); 54 | 55 | return ans; 56 | } -------------------------------------------------------------------------------- /Strings/PalindromeString.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | 4 | Example: 5 | 6 | "A man, a plan, a canal: Panama" is a palindrome. 7 | 8 | "race a car" is not a palindrome. 9 | 10 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 11 | 12 | LINK: https://www.interviewbit.com/problems/palindrome-string/ 13 | */ 14 | 15 | × 16 | int Solution::isPalindrome(string s) 17 | { 18 | int i=0,j=s.length()-1; 19 | 20 | while(i<=j) 21 | { 22 | while(!isalnum(s[i])) 23 | i++; 24 | while(!isalnum(s[j])) 25 | j--; 26 | if(i>j) 27 | break; 28 | if(tolower(s[i])!=tolower(s[j])) 29 | return 0; 30 | i++; 31 | j--; 32 | } 33 | return 1; 34 | } -------------------------------------------------------------------------------- /Strings/Powerof2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find if Given number is power of 2 or not. 3 | More specifically, find if given number can be expressed as 2^k where k >= 1. 4 | 5 | Input: 6 | 7 | number length can be more than 64, which mean number can be greater than 2 ^ 64 (out of long long range) 8 | Output: 9 | 10 | return 1 if the number is a power of 2 else return 0 11 | 12 | Example: 13 | 14 | Input : 128 15 | Output : 1 16 | 17 | LINK: https://www.interviewbit.com/problems/power-of-2/ 18 | */ 19 | 20 | string div2(string s) 21 | { 22 | string res; 23 | 24 | int n=s.length(); 25 | int carry=0,i=0; 26 | while(i0 && res[0]=='0') 39 | res.erase(res.begin()); 40 | 41 | return res; 42 | } 43 | 44 | int Solution::power(string s) 45 | { 46 | if(s.length()==1 && s[0]=='1') 47 | return 0; 48 | 49 | while(s.length()>0) 50 | { 51 | if(s.length()==1 && s[0]=='1') 52 | break; 53 | 54 | if((s[s.length()-1]-'0')%2) 55 | return 0; 56 | 57 | s = div2(s); 58 | } 59 | return 1; 60 | } -------------------------------------------------------------------------------- /Strings/ReversetheString.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an input string, reverse the string word by word. 3 | 4 | Example: 5 | 6 | Given s = "the sky is blue", 7 | 8 | return "blue is sky the". 9 | 10 | A sequence of non-space characters constitutes a word. 11 | Your reversed string should not contain leading or trailing spaces, even if it is present in the input string. 12 | If there are multiple spaces between words, reduce them to a single space in the reversed string. 13 | 14 | LINK: https://www.interviewbit.com/problems/reverse-the-string/ 15 | */ 16 | 17 | void Solution::reverseWords(string &s) 18 | { 19 | // Do not write main() function. 20 | // Do not read input, instead use the arguments to the function. 21 | // Do not print the output, instead return values as specified 22 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 23 | 24 | vector words; 25 | string word = ""; 26 | int n = s.length(); 27 | 28 | for(int i=0;i0) 31 | { 32 | words.push_back(word); 33 | word = ""; 34 | } 35 | else 36 | word.push_back(s[i]); 37 | } 38 | if(word.length()>0) 39 | words.push_back(word); 40 | 41 | reverse(words.begin(), words.end()); 42 | s=""; 43 | 44 | for(int i=0;iv1) 48 | { 49 | res += v2-v1; 50 | i++; 51 | } 52 | else 53 | res += v1; 54 | } 55 | else 56 | res += v1; 57 | } 58 | return res; 59 | } -------------------------------------------------------------------------------- /TreeDataStructure/BSTIterator.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 3 | 4 | The first call to next() will return the smallest number in BST. Calling next() again will return the next smallest number in the BST, and so on. 5 | 6 | Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 7 | Try to optimize the additional space complexity apart from the amortized time complexity. 8 | 9 | LINK: https://www.interviewbit.com/problems/bst-iterator/ 10 | */ 11 | 12 | /** 13 | * Definition for binary tree 14 | * struct TreeNode { 15 | * int val; 16 | * TreeNode *left; 17 | * TreeNode *right; 18 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 | * }; 20 | */ 21 | 22 | stack st; 23 | 24 | void pushLeft(TreeNode* root) 25 | { 26 | while(root!=NULL) 27 | { 28 | st.push(root); 29 | root = root->left; 30 | } 31 | } 32 | 33 | BSTIterator::BSTIterator(TreeNode *root) 34 | { 35 | pushLeft(root); 36 | } 37 | 38 | /** @return whether we have a next smallest number */ 39 | bool BSTIterator::hasNext() 40 | { 41 | return !st.empty(); 42 | } 43 | 44 | /** @return the next smallest number */ 45 | int BSTIterator::next() 46 | { 47 | TreeNode* temp = st.top(); 48 | st.pop(); 49 | pushLeft(temp->right); 50 | return temp->val; 51 | } 52 | 53 | /** 54 | * Your BSTIterator will be called like this: 55 | * BSTIterator i = BSTIterator(root); 56 | * while (i.hasNext()) cout << i.next(); 57 | */ -------------------------------------------------------------------------------- /TreeDataStructure/BalancedBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, determine if it is height-balanced. 3 | 4 | Height-balanced binary tree : is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 6 | 7 | Example : 8 | 9 | Input : 10 | 1 11 | / \ 12 | 2 3 13 | 14 | Return : True or 1 15 | 16 | Input 2 : 17 | 3 18 | / 19 | 2 20 | / 21 | 1 22 | 23 | Return : False or 0 24 | Because for the root node, left subtree has depth 2 and right subtree has depth 0. 25 | Difference = 2 > 1. 26 | 27 | LINK: https://www.interviewbit.com/problems/balanced-binary-tree/ 28 | */ 29 | 30 | /** 31 | * Definition for binary tree 32 | * struct TreeNode { 33 | * int val; 34 | * TreeNode *left; 35 | * TreeNode *right; 36 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 37 | * }; 38 | */ 39 | 40 | int check_bal(TreeNode* root) 41 | { 42 | if(root==NULL) 43 | return 0; 44 | 45 | int lefth = check_bal(root->left); 46 | int righth = check_bal(root->right); 47 | 48 | if(lefth==-1 || righth==-1) 49 | return -1; 50 | 51 | if(abs(lefth-righth)>1) 52 | return -1; 53 | 54 | return 1+max(lefth,righth); 55 | } 56 | 57 | int Solution::isBalanced(TreeNode* A) 58 | { 59 | if(check_bal(A)==-1) 60 | return 0; 61 | else 62 | return 1; 63 | } -------------------------------------------------------------------------------- /TreeDataStructure/BinaryTreeFromInorderAndPostorder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given inorder and postorder traversal of a tree, construct the binary tree. 3 | 4 | Note: You may assume that duplicates do not exist in the tree. 5 | Example : 6 | 7 | Input : 8 | Inorder : [2, 1, 3] 9 | Postorder : [2, 3, 1] 10 | 11 | Return : 12 | 1 13 | / \ 14 | 2 3 15 | 16 | LINK: https://www.interviewbit.com/problems/binary-tree-from-inorder-and-postorder/ 17 | */ 18 | 19 | /** 20 | * Definition for binary tree 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | 29 | TreeNode* build(int si, int ei, vector &In, int sp, int ep, vector &Post) 30 | { 31 | if(si>ei || sp>ep) 32 | return NULL; 33 | 34 | int ind = -1; 35 | for(int i=si;i<=ei;i++) 36 | { 37 | if(In[i]==Post[ep]) 38 | { 39 | ind = i; 40 | break; 41 | } 42 | } 43 | 44 | TreeNode* node = new TreeNode(In[ind]); 45 | int len = ei-ind; 46 | node->left = build(si,ind-1,In,sp,ep-len-1,Post); 47 | node->right = build(ind+1,ei,In,ep-len,ep-1,Post); 48 | return node; 49 | } 50 | 51 | TreeNode* Solution::buildTree(vector &A, vector &B) 52 | { 53 | if(A.empty() || B.empty()) 54 | return NULL; 55 | 56 | return build(0,A.size()-1,A,0,B.size()-1,B); 57 | } -------------------------------------------------------------------------------- /TreeDataStructure/ConstructBinaryTreeFromInorderAndPreorder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given preorder and inorder traversal of a tree, construct the binary tree. 3 | 4 | Note: You may assume that duplicates do not exist in the tree. 5 | Example : 6 | 7 | Input : 8 | Preorder : [1, 2, 3] 9 | Inorder : [2, 1, 3] 10 | 11 | Return : 12 | 1 13 | / \ 14 | 2 3 15 | 16 | LINK: https://www.interviewbit.com/problems/construct-binary-tree-from-inorder-and-preorder/ 17 | */ 18 | 19 | /** 20 | * Definition for binary tree 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | 29 | TreeNode* build(int si, int ei, vector &In, int sp, int ep, vector &Pre) 30 | { 31 | if(si>ei || sp>ep) 32 | return NULL; 33 | 34 | int ind = -1; 35 | for(int i=si;i<=ei;i++) 36 | { 37 | if(In[i]==Pre[sp]) 38 | { 39 | ind = i; 40 | break; 41 | } 42 | } 43 | 44 | TreeNode* node = new TreeNode(In[ind]); 45 | int len = ind-si; 46 | node->left = build(si,ind-1,In,sp+1,sp+len,Pre); 47 | node->right = build(ind+1,ei,In,sp+len+1,ep,Pre); 48 | return node; 49 | } 50 | 51 | TreeNode* Solution::buildTree(vector &A, vector &B) 52 | { 53 | if(A.empty() || B.empty()) 54 | return NULL; 55 | 56 | return build(0,B.size()-1,B,0,A.size()-1,A); 57 | } -------------------------------------------------------------------------------- /TreeDataStructure/FlattenBinaryTreetoLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, flatten it to a linked list in-place. 3 | 4 | Example : 5 | Given 6 | 7 | 8 | 1 9 | / \ 10 | 2 5 11 | / \ \ 12 | 3 4 6 13 | The flattened tree should look like: 14 | 15 | 1 16 | \ 17 | 2 18 | \ 19 | 3 20 | \ 21 | 4 22 | \ 23 | 5 24 | \ 25 | 6 26 | Note that the left child of all nodes should be NULL. 27 | 28 | LINK: https://www.interviewbit.com/problems/flatten-binary-tree-to-linked-list/ 29 | */ 30 | 31 | /** 32 | * Definition for binary tree 33 | * struct TreeNode { 34 | * int val; 35 | * TreeNode *left; 36 | * TreeNode *right; 37 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 38 | * }; 39 | */ 40 | 41 | TreeNode* Solution::flatten(TreeNode* A) 42 | { 43 | // Do not write main() function. 44 | // Do not read input, instead use the arguments to the function. 45 | // Do not print the output, instead return values as specified 46 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 47 | 48 | TreeNode* root = A; 49 | if(!root) 50 | return root; 51 | 52 | while(A) 53 | { 54 | if(A->left) 55 | { 56 | TreeNode* leftRightmost = A->left; 57 | while(leftRightmost->right) 58 | leftRightmost = leftRightmost->right; 59 | leftRightmost->right = A->right; 60 | A->right = A->left; 61 | A->left = NULL; 62 | } 63 | A = A->right; 64 | } 65 | return root; 66 | } -------------------------------------------------------------------------------- /TreeDataStructure/IdenticalBinaryTrees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two binary trees, write a function to check if they are equal or not. 3 | 4 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 5 | 6 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 7 | 8 | Example : 9 | 10 | Input : 11 | 12 | 1 1 13 | / \ / \ 14 | 2 3 2 3 15 | 16 | Output : 17 | 1 or True 18 | 19 | LINK: https://www.interviewbit.com/problems/identical-binary-trees/ 20 | */ 21 | 22 | /** 23 | * Definition for binary tree 24 | * struct TreeNode { 25 | * int val; 26 | * TreeNode *left; 27 | * TreeNode *right; 28 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 29 | * }; 30 | */ 31 | 32 | int isSame(TreeNode* root1, TreeNode* root2) 33 | { 34 | if(!root1 && !root2) 35 | return 1; 36 | if(!root1 || !root2) 37 | return 0; 38 | if(root1->val!=root2->val) 39 | return 0; 40 | 41 | return (isSame(root1->left, root2->left) && isSame(root1->right,root2->right)); 42 | } 43 | 44 | int Solution::isSameTree(TreeNode* A, TreeNode* B) 45 | { 46 | return isSame(A,B); 47 | } -------------------------------------------------------------------------------- /TreeDataStructure/InorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the inorder traversal of its nodes’ values. 3 | 4 | Example : 5 | Given binary tree 6 | 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | return [1,3,2]. 13 | 14 | Using recursion is not allowed. 15 | 16 | LINK: https://www.interviewbit.com/problems/inorder-traversal/ 17 | */ 18 | 19 | /** 20 | * Definition for binary tree 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | vector Solution::inorderTraversal(TreeNode* A) 29 | { 30 | vector res; 31 | stack st; 32 | 33 | TreeNode* curr = A; 34 | 35 | while(!st.empty() || curr) 36 | { 37 | while(curr) 38 | { 39 | st.push(curr); 40 | curr = curr->left; 41 | } 42 | 43 | curr = st.top(); 44 | st.pop(); 45 | res.push_back(curr->val); 46 | curr = curr->right; 47 | } 48 | return res; 49 | } -------------------------------------------------------------------------------- /TreeDataStructure/InorderTraversalofCartesianTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an inorder traversal of a cartesian tree, construct the tree. 3 | 4 | Cartesian tree : is a heap ordered binary tree, where the root is greater than all the elements in the subtree. 5 | Note: You may assume that duplicates do not exist in the tree. 6 | Example : 7 | 8 | Input : [1 2 3] 9 | 10 | Return : 11 | 3 12 | / 13 | 2 14 | / 15 | 1 16 | 17 | LINK: https://www.interviewbit.com/problems/inorder-traversal-of-cartesian-tree/ 18 | */ 19 | 20 | /** 21 | * Definition for binary tree 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | 30 | int findMax(int s, int e, vector &A) 31 | { 32 | int mxi = s; 33 | for(int i=s+1;i<=e;i++) 34 | if(A[i]>A[mxi]) 35 | mxi = i; 36 | return mxi; 37 | } 38 | 39 | TreeNode* build(int s, int e, vector &A) 40 | { 41 | if(s>e) 42 | return NULL; 43 | 44 | int i = findMax(s,e,A); 45 | TreeNode* node = new TreeNode(A[i]); 46 | node->left = build(s,i-1,A); 47 | node->right = build(i+1,e,A); 48 | return node; 49 | } 50 | 51 | TreeNode* Solution::buildTree(vector &A) 52 | { 53 | if(A.empty()) 54 | return NULL; 55 | 56 | return build(0,A.size()-1,A); 57 | } -------------------------------------------------------------------------------- /TreeDataStructure/InvertTheBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, invert the binary tree and return it. 3 | Look at the example for more details. 4 | 5 | Example : 6 | Given binary tree 7 | 8 | 1 9 | / \ 10 | 2 3 11 | / \ / \ 12 | 4 5 6 7 13 | invert and return 14 | 15 | 1 16 | / \ 17 | 3 2 18 | / \ / \ 19 | 7 6 5 4 20 | 21 | LINK: https://www.interviewbit.com/problems/invert-the-binary-tree/ 22 | */ 23 | 24 | /** 25 | * Definition for binary tree 26 | * struct TreeNode { 27 | * int val; 28 | * TreeNode *left; 29 | * TreeNode *right; 30 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 31 | * }; 32 | */ 33 | 34 | void invert(TreeNode* root) 35 | { 36 | if(root==NULL) 37 | return; 38 | 39 | TreeNode* temp = root->left; 40 | root->left = root->right; 41 | root->right = temp; 42 | 43 | invert(root->left); 44 | invert(root->right); 45 | } 46 | 47 | TreeNode* Solution::invertTree(TreeNode* A) 48 | { 49 | invert(A); 50 | return A; 51 | } -------------------------------------------------------------------------------- /TreeDataStructure/KthSmallestElementInTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary search tree, write a function to find the kth smallest element in the tree. 3 | 4 | Example : 5 | 6 | Input : 7 | 2 8 | / \ 9 | 1 3 10 | 11 | and k = 2 12 | 13 | Return : 2 14 | 15 | As 2 is the second smallest element in the tree. 16 | NOTE : You may assume 1 <= k <= Total number of nodes in BST 17 | 18 | LINK: https://www.interviewbit.com/problems/kth-smallest-element-in-tree/ 19 | */ 20 | 21 | /** 22 | * Definition for binary tree 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | 31 | vector inorderTraversal(TreeNode* A) 32 | { 33 | vector res; 34 | stack st; 35 | 36 | TreeNode* curr = A; 37 | 38 | while(!st.empty() || curr) 39 | { 40 | while(curr) 41 | { 42 | st.push(curr); 43 | curr = curr->left; 44 | } 45 | 46 | curr = st.top(); 47 | st.pop(); 48 | res.push_back(curr->val); 49 | curr = curr->right; 50 | } 51 | return res; 52 | } 53 | 54 | int Solution::kthsmallest(TreeNode* A, int B) 55 | { 56 | vector v = inorderTraversal(A); 57 | return v[B-1]; 58 | } -------------------------------------------------------------------------------- /TreeDataStructure/MaxDepthofBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find its maximum depth. 3 | 4 | The maximum depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | 6 | NOTE : The path has to end on a leaf node. 7 | Example : 8 | 9 | 1 10 | / 11 | 2 12 | max depth = 2. 13 | 14 | LINK: https://www.interviewbit.com/problems/max-depth-of-binary-tree/ 15 | */ 16 | 17 | /** 18 | * Definition for binary tree 19 | * struct TreeNode { 20 | * int val; 21 | * TreeNode *left; 22 | * TreeNode *right; 23 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 24 | * }; 25 | */ 26 | int Solution::maxDepth(TreeNode* A) 27 | { 28 | if(A==NULL) 29 | return 0; 30 | return 1+max(maxDepth(A->left), maxDepth(A->right)); 31 | } -------------------------------------------------------------------------------- /TreeDataStructure/MinDepthofBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | 6 | NOTE : The path has to end on a leaf node. 7 | Example : 8 | 9 | 1 10 | / 11 | 2 12 | min depth = 2. 13 | 14 | LINK: https://www.interviewbit.com/problems/min-depth-of-binary-tree/ 15 | */ 16 | 17 | /** 18 | * Definition for binary tree 19 | * struct TreeNode { 20 | * int val; 21 | * TreeNode *left; 22 | * TreeNode *right; 23 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 24 | * }; 25 | */ 26 | int Solution::minDepth(TreeNode* A){ 27 | if(A==NULL) 28 | return 0; 29 | if(A->left==NULL && A->right==NULL) 30 | return 1; 31 | if(!A->right) 32 | return 1+minDepth(A->left); 33 | if(!A->left) 34 | return 1+minDepth(A->right); 35 | 36 | return 1+min(minDepth(A->left), minDepth(A->right)); 37 | } -------------------------------------------------------------------------------- /TreeDataStructure/PathSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 3 | 4 | Example : 5 | 6 | Given the below binary tree and sum = 22, 7 | 8 | 5 9 | / \ 10 | 4 8 11 | / / \ 12 | 11 13 4 13 | / \ \ 14 | 7 2 1 15 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 16 | 17 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 18 | 19 | LINK: https://www.interviewbit.com/problems/path-sum/ 20 | */ 21 | 22 | /** 23 | * Definition for binary tree 24 | * struct TreeNode { 25 | * int val; 26 | * TreeNode *left; 27 | * TreeNode *right; 28 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 29 | * }; 30 | */ 31 | 32 | int check(TreeNode* root, int sum, int d) 33 | { 34 | if(root==NULL) 35 | return 0; 36 | 37 | d+=root->val; 38 | 39 | if(sum==d && root->left==NULL && root->right==NULL) 40 | return 1; 41 | 42 | if(check(root->left, sum, d)) 43 | return 1; 44 | if(check(root->right, sum, d)) 45 | return 1; 46 | return 0; 47 | } 48 | 49 | int Solution::hasPathSum(TreeNode* A, int B) 50 | { 51 | return check(A,B,0); 52 | } -------------------------------------------------------------------------------- /TreeDataStructure/PostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the postorder traversal of its nodes’ values. 3 | 4 | Example : 5 | 6 | Given binary tree 7 | 8 | 1 9 | \ 10 | 2 11 | / 12 | 3 13 | return [3,2,1]. 14 | 15 | Using recursion is not allowed. 16 | 17 | LINK: https://www.interviewbit.com/problems/postorder-traversal/ 18 | */ 19 | 20 | /** 21 | * Definition for binary tree 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | vector Solution::postorderTraversal(TreeNode* A) 30 | { 31 | vector res; 32 | 33 | if(A==NULL) 34 | return res; 35 | 36 | deque dq; 37 | dq.push_back(A); 38 | 39 | while(!dq.empty()) 40 | { 41 | TreeNode* curr = dq.back(); 42 | if(curr->left || curr->right) 43 | { 44 | if(curr->right) 45 | { 46 | dq.push_back(curr->right); 47 | curr->right = NULL; 48 | } 49 | if(curr->left) 50 | { 51 | dq.push_back(curr->left); 52 | curr->left = NULL; 53 | } 54 | } 55 | else 56 | { 57 | res.push_back(curr->val); 58 | dq.pop_back(); 59 | } 60 | } 61 | return res; 62 | } -------------------------------------------------------------------------------- /TreeDataStructure/PreorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the preorder traversal of its nodes’ values. 3 | 4 | Example : 5 | Given binary tree 6 | 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | return [1,2,3]. 13 | 14 | Using recursion is not allowed. 15 | 16 | LINK: https://www.interviewbit.com/problems/preorder-traversal/ 17 | */ 18 | 19 | /** 20 | * Definition for binary tree 21 | * struct TreeNode { 22 | * int val; 23 | * TreeNode *left; 24 | * TreeNode *right; 25 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | * }; 27 | */ 28 | vector Solution::preorderTraversal(TreeNode* A) 29 | { 30 | vector res; 31 | stack st; 32 | 33 | st.push(A); 34 | TreeNode* curr; 35 | 36 | while(!st.empty()) 37 | { 38 | curr = st.top(); 39 | st.pop(); 40 | res.push_back(curr->val); 41 | 42 | if(curr->right) 43 | st.push(curr->right); 44 | if(curr->left) 45 | st.push(curr->left); 46 | } 47 | return res; 48 | } -------------------------------------------------------------------------------- /TreeDataStructure/RootToLeafPathsWithSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 7 | 5 8 | / \ 9 | 4 8 10 | / / \ 11 | 11 13 4 12 | / \ / \ 13 | 7 2 5 1 14 | return 15 | 16 | [ 17 | [5,4,11,2], 18 | [5,8,4,5] 19 | ] 20 | 21 | LINK: https://www.interviewbit.com/problems/root-to-leaf-paths-with-sum/ 22 | */ 23 | 24 | /** 25 | * Definition for binary tree 26 | * struct TreeNode { 27 | * int val; 28 | * TreeNode *left; 29 | * TreeNode *right; 30 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 31 | * }; 32 | */ 33 | 34 | vector > res; 35 | 36 | void check(TreeNode* root, int sum, int d, vector &temp) 37 | { 38 | if(root==NULL) 39 | return; 40 | 41 | d+=root->val; 42 | temp.push_back(root->val); 43 | 44 | if(sum==d && root->left==NULL && root->right==NULL) 45 | { 46 | res.push_back(temp); 47 | temp.pop_back(); 48 | return; 49 | } 50 | 51 | check(root->left, sum, d, temp); 52 | check(root->right, sum, d, temp); 53 | temp.pop_back(); 54 | } 55 | 56 | vector > Solution::pathSum(TreeNode* A, int B) 57 | { 58 | res.clear(); 59 | vector temp; 60 | check(A,B,0,temp); 61 | return res; 62 | } -------------------------------------------------------------------------------- /TreeDataStructure/SortedArrayToBalancedBST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | 4 | Balanced tree : a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | Example : 6 | 7 | 8 | Given A : [1, 2, 3] 9 | A height balanced BST : 10 | 11 | 2 12 | / \ 13 | 1 3 14 | 15 | LINK: https://www.interviewbit.com/problems/sorted-array-to-balanced-bst/ 16 | */ 17 | 18 | /** 19 | * Definition for binary tree 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | 28 | TreeNode* build(int s, int e, const vector &A) 29 | { 30 | if(s>e) 31 | return NULL; 32 | 33 | int i = (s+e)/2; 34 | TreeNode* node = new TreeNode(A[i]); 35 | node->left = build(s,i-1,A); 36 | node->right = build(i+1,e,A); 37 | return node; 38 | } 39 | 40 | TreeNode* Solution::sortedArrayToBST(const vector &A) 41 | { 42 | // Do not write main() function. 43 | // Do not read input, instead use the arguments to the function. 44 | // Do not print the output, instead return values as specified 45 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 46 | 47 | if(A.empty()) 48 | return NULL; 49 | return build(0,A.size()-1,A); 50 | } -------------------------------------------------------------------------------- /TreeDataStructure/SumRootToLeafNumbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 3 | 4 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 5 | 6 | Find the total sum of all root-to-leaf numbers % 1003. 7 | 8 | Example : 9 | 10 | 1 11 | / \ 12 | 2 3 13 | The root-to-leaf path 1->2 represents the number 12. 14 | The root-to-leaf path 1->3 represents the number 13. 15 | 16 | Return the sum = (12 + 13) % 1003 = 25 % 1003 = 25. 17 | 18 | LINK: https://www.interviewbit.com/problems/sum-root-to-leaf-numbers/ 19 | */ 20 | 21 | /** 22 | * Definition for binary tree 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | 31 | #define MOD 1003 32 | 33 | int calc(TreeNode* root, int sum) 34 | { 35 | if(root==NULL) 36 | return sum; 37 | 38 | sum+=root->val; 39 | 40 | if(root->left==NULL && root->right==NULL) 41 | return sum; 42 | 43 | sum = (sum*10)%MOD; 44 | 45 | int left_sum = 0; 46 | if(root->left) 47 | left_sum = calc(root->left,sum); 48 | int right_sum = 0; 49 | if(root->right) 50 | right_sum = calc(root->right,sum); 51 | 52 | return (left_sum + right_sum)%MOD; 53 | } 54 | 55 | int Solution::sumNumbers(TreeNode* A) 56 | { 57 | return calc(A,0); 58 | } -------------------------------------------------------------------------------- /TreeDataStructure/SymmetricBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 | 4 | Example : 5 | 6 | 1 7 | / \ 8 | 2 2 9 | / \ / \ 10 | 3 4 4 3 11 | The above binary tree is symmetric. 12 | But the following is not: 13 | 14 | 1 15 | / \ 16 | 2 2 17 | \ \ 18 | 3 3 19 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 20 | 21 | LINK: https://www.interviewbit.com/problems/symmetric-binary-tree/ 22 | */ 23 | 24 | /** 25 | * Definition for binary tree 26 | * struct TreeNode { 27 | * int val; 28 | * TreeNode *left; 29 | * TreeNode *right; 30 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 31 | * }; 32 | */ 33 | 34 | vector inorderTraversal(TreeNode* A) 35 | { 36 | vector res; 37 | stack st; 38 | 39 | TreeNode* curr = A; 40 | 41 | while(!st.empty() || curr) 42 | { 43 | while(curr) 44 | { 45 | st.push(curr); 46 | curr = curr->left; 47 | } 48 | 49 | curr = st.top(); 50 | st.pop(); 51 | res.push_back(curr->val); 52 | curr = curr->right; 53 | } 54 | return res; 55 | } 56 | int Solution::isSymmetric(TreeNode* A) 57 | { 58 | vector v = inorderTraversal(A); 59 | int n = v.size(); 60 | 61 | for(int i=0;i > res; 34 | 35 | int maxDepth(TreeNode* A) 36 | { 37 | if(A==NULL) 38 | return 0; 39 | return 1+max(maxDepth(A->left), maxDepth(A->right)); 40 | } 41 | 42 | void zigzag(TreeNode* root, int d) 43 | { 44 | if(root==NULL) 45 | return; 46 | res[d].push_back(root->val); 47 | zigzag(root->left,d+1); 48 | zigzag(root->right,d+1); 49 | } 50 | 51 | vector > Solution::zigzagLevelOrder(TreeNode* A) 52 | { 53 | int n = maxDepth(A); 54 | res.clear(); 55 | res.resize(n); 56 | 57 | zigzag(A,0); 58 | 59 | for(int i=1;i &A, int B) 17 | { 18 | sort(A.begin(), A.end()); 19 | int n = A.size(); 20 | 21 | int res = A[n-1]+A[n-2]+A[n-3]; 22 | 23 | for(int i=0;i > Solution::threeSum(vector &A) 16 | { 17 | sort(A.begin(), A.end()); 18 | int n = A.size(); 19 | vector< vector > res; 20 | 21 | for(int i=0;i=n-2) 26 | break; 27 | int l=i+1, r=n-1; 28 | 29 | while(l v = {A[i],A[l],A[r]}; 35 | res.push_back(v); 36 | l++; 37 | while(l &A, const vector &B, const vector &C) 26 | { 27 | int res = INT_MAX; 28 | int i=0,j=0,k=0; 29 | int na=A.size(), nb=B.size(), nc=C.size(); 30 | 31 | while(i &A) 23 | { 24 | int area = 0; 25 | int l=0,r=A.size()-1; 26 | while(l &A) 23 | { 24 | sort(A.begin(), A.end()); 25 | int n = A.size(); 26 | int res = 0; 27 | 28 | for(int i=0;iA[k]) 35 | k++; 36 | res = (res + (k-j-1)%MOD)%MOD; 37 | } 38 | } 39 | return res; 40 | } -------------------------------------------------------------------------------- /TwoPointers/Diffk.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array ‘A’ of sorted integers and another non negative integer k, find if there exists 2 indices i and j such that A[i] - A[j] = k, i != j. 3 | 4 | Example: Input : 5 | A : [1 3 5] 6 | k : 4 7 | Output : YES as 5 - 1 = 4 8 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 9 | 10 | Try doing this in less than linear space complexity. 11 | 12 | LINK: https://www.interviewbit.com/problems/diffk/ 13 | */ 14 | 15 | int Solution::diffPossible(vector &A, int B) 16 | { 17 | int n=A.size(); 18 | 19 | for(int i=0;i Solution::intersect(const vector &A, const vector &B) 24 | { 25 | int n = A.size(); 26 | int m = B.size(); 27 | int i=0,j=0; 28 | vector v; 29 | 30 | while(i Solution::maxone(vector &A, int B) 22 | { 23 | int l=0,r=0,n=A.size(); 24 | int zcnt = 0; 25 | int mxcnt=0,ind=0; 26 | 27 | while(rB) 36 | { 37 | if(A[l]==0) 38 | zcnt--; 39 | l++; 40 | } 41 | if((r-l)>mxcnt) 42 | { 43 | mxcnt = r-l; 44 | ind = l; 45 | } 46 | } 47 | 48 | vector v; 49 | for(int i=0;i &A, vector &B) 20 | { 21 | // Do not write main() function. 22 | // Do not read input, instead use the arguments to the function. 23 | // Do not print the output, instead return values as specified 24 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 25 | 26 | int n = A.size(); 27 | int m = B.size(); 28 | int i=0,j=0; 29 | vector v; 30 | 31 | while(i &A, vector &B, vector &C) 23 | { 24 | int res = INT_MAX; 25 | int i=0,j=0,k=0; 26 | int na=A.size(), nb=B.size(), nc=C.size(); 27 | 28 | while(i &A) 17 | { 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 | 24 | int n = A.size(); 25 | int i=0,j=0; 26 | 27 | while(j=n) 35 | break; 36 | A[i]=A[j]; 37 | j++; 38 | } 39 | } 40 | return i+1; 41 | } 42 | -------------------------------------------------------------------------------- /TwoPointers/RemoveDuplicatesfromSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Duplicates from Sorted Array 3 | 4 | Given a sorted array, remove the duplicates in place such that each element can appear atmost twice and return the new length. 5 | 6 | Do not allocate extra space for another array, you must do this in place with constant memory. 7 | 8 | Note that even though we want you to return the new length, make sure to change the original array as well in place 9 | 10 | For example, 11 | Given input array A = [1,1,1,2], 12 | 13 | Your function should return length = 3, and A is now [1,1,2]. 14 | 15 | LINK: https://www.interviewbit.com/problems/remove-duplicates-from-sorted-array-ii/ 16 | */ 17 | 18 | int Solution::removeDuplicates(vector &A) 19 | { 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 | int n = A.size(); 26 | int i=0,j=1,cnt=1; 27 | 28 | while(j=2) 31 | j++; 32 | else 33 | { 34 | if(A[i]==A[j]) 35 | cnt++; 36 | else 37 | cnt=1; 38 | i++; 39 | if(i>=n) 40 | break; 41 | A[i]=A[j]; 42 | j++; 43 | } 44 | } 45 | return i+1; 46 | } -------------------------------------------------------------------------------- /TwoPointers/RemoveElementfromArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Element 3 | 4 | Given an array and a value, remove all the instances of that value in the array. 5 | Also return the number of elements left in the array after the operation. 6 | It does not matter what is left beyond the expected length. 7 | 8 | Example: 9 | If array A is [4, 1, 1, 2, 1, 3] 10 | and value elem is 1, 11 | then new length is 3, and A is now [4, 2, 3] 12 | Try to do it in less than linear additional space complexity. 13 | 14 | LINK: https://www.interviewbit.com/problems/remove-element-from-array/ 15 | */ 16 | 17 | int Solution::removeElement(vector &A, int B) 18 | { 19 | // Do not write main() function. 20 | // Do not read input, instead use the arguments to the function. 21 | // Do not print the output, instead return values as specified 22 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 23 | 24 | int i=0,j=0,n=A.size(); 25 | while(j &A) 18 | { 19 | // Do not write main() function. 20 | // Do not read input, instead use the arguments to the function. 21 | // Do not print the output, instead return values as specified 22 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 23 | 24 | int i=0,j=0,k=A.size()-1; 25 | 26 | while(j<=k) 27 | { 28 | if(A[j]==0) 29 | swap(A[i++],A[j++]); 30 | else 31 | if(A[j]==2) 32 | swap(A[j],A[k--]); 33 | else 34 | j++; 35 | } 36 | } --------------------------------------------------------------------------------