├── README.md ├── Math ├── GreatestCommonDivisor.cpp ├── TrailingZerosinFactorial.cpp ├── LargestCoprimeDivisor.cpp ├── ExcelColumnNumber.cpp ├── PowerOfTwoIntegers.cpp ├── ExcelColumnTitle.cpp ├── PalindromeInteger.cpp ├── ReverseInteger.cpp ├── FizzBuzz.cpp ├── RearrangeArray.cpp ├── GridUniquePaths.cpp ├── PrimeSum.cpp ├── SortedPermutationRank.cpp └── SumofpairwiseHammingDistance.cpp ├── BitManipulation ├── SingleNumber.cpp ├── MinXORvalue.cpp ├── SingleNumberII.cpp ├── DivideIntegers.cpp ├── Numberof1Bits.cpp ├── ReverseBits.cpp └── DifferentBitsSumPairwise.cpp ├── Greedy ├── HighestProduct.cpp ├── MajorityElement.cpp ├── Bulbs.cpp ├── DistributeCandy.cpp └── AssignMiceToHoles.cpp ├── DynamicProgramming ├── Stairs.cpp ├── WaysToColorA3xNBoard.cpp ├── BestTimeToBuyAndSellStocksI.cpp ├── JumpGameArray.cpp ├── MinSumPathInMatrix.cpp ├── MaxProductSubarray.cpp ├── MaxSumWithoutAdjacentElements.cpp ├── IntersectingChordsInACircle.cpp ├── LongestValidParentheses.cpp ├── CoinSumInfinite.cpp ├── UniqueBinarySearchTreesII.cpp ├── BestTimeToBuyAndSellStocksII.cpp ├── EditDistance.cpp ├── MaxSumPathInBinaryTree.cpp ├── WaystoDecode.cpp ├── RepeatingSub-Sequence.cpp ├── LengthofLongestSubsequence.cpp ├── LongestIncreasingSubsequence.cpp ├── MinJumpsArray.cpp ├── InterleavingStrings.cpp ├── DistinctSubsequences.cpp ├── BestTimeToBuyAndSellStocksIII.cpp ├── NDigitNumbersWithDigitSumS.cpp ├── WordBreak.cpp ├── PalindromePartitioningII.cpp ├── RegularExpressionII.cpp ├── UniquePathsInAGrid.cpp ├── CoinsInALine.cpp ├── MinSumPathInTriangle.cpp ├── SubMatricesWithSumZero.cpp ├── RegularExpressionMatch.cpp ├── FlipArray.cpp └── WordBreakII.cpp ├── Arrays ├── NobleInteger.cpp ├── MaxSumContiguousSubarray.cpp ├── KthRowofPascal'sTriangle.cpp ├── WaveArray.cpp ├── PascalTriangle.cpp ├── MaxDistance.cpp ├── MaximumAbsoluteDifference.cpp ├── FirstMissingInteger.cpp ├── RepeatandMissingNumberArray.cpp ├── AntiDiagonals.cpp ├── FindPermutation.cpp ├── LargestNumber.cpp ├── AddOneToNumber.cpp ├── RotateMatrix.cpp ├── MinStepsinInfiniteGrid.cpp ├── SpiralOrderMatrixII.cpp ├── MergeOverlappingIntervals.cpp └── SetMatrixZeros.cpp ├── Hashing ├── DiffkII.cpp ├── LongestSubstringWithoutRepeat.cpp ├── ColorfulNumber.cpp ├── LargestContinuousSequenceZeroSum.cpp ├── Fraction.cpp ├── 2Sum.cpp ├── Anagrams.cpp └── SubstringConcatenation.cpp ├── Strings ├── PalindromeString.cpp ├── MinimumCharactersrequiredtomakeaStringPalindromic.cpp ├── LengthofLastWord.cpp ├── CountAndSay.cpp ├── LongestCommonPrefix.cpp ├── RomanToInteger.cpp ├── AmazingSubarrays.cpp ├── Powerof2.cpp ├── AddBinaryStrings.cpp ├── ReversetheString.cpp ├── Atoi.cpp ├── MultiplyStrings.cpp └── LongestPalindromicSubstring.cpp ├── TreeDataStructure ├── MaxDepthofBinaryTree.cpp ├── MinDepthofBinaryTree.cpp ├── InvertTheBinaryTree.cpp ├── PreorderTraversal.cpp ├── InorderTraversal.cpp ├── IdenticalBinaryTrees.cpp ├── KthSmallestElementInTree.cpp ├── PathSum.cpp ├── PostorderTraversal.cpp ├── InorderTraversalofCartesianTree.cpp ├── ZigZagLevelOrderTraversalBT.cpp ├── SumRootToLeafNumbers.cpp ├── RootToLeafPathsWithSum.cpp ├── BinaryTreeFromInorderAndPostorder.cpp ├── SymmetricBinaryTree.cpp ├── ConstructBinaryTreeFromInorderAndPreorder.cpp ├── SortedArrayToBalancedBST.cpp ├── BalancedBinaryTree.cpp ├── BSTIterator.cpp └── FlattenBinaryTreetoLinkedList.cpp ├── BinarySearch ├── SortedInsertPosition.cpp ├── MatrixMedian.cpp ├── SquareRootofInteger.cpp ├── ImplementPowerFunction.cpp ├── SearchforaRange.cpp └── RotatedSortedArraySearch.cpp ├── LinkedLists ├── SwapListNodesinpairs.cpp ├── PalindromeList.cpp ├── RotateList.cpp ├── RemoveDuplicatesfromSortedList.cpp ├── RemoveNthNodefromListEnd.cpp ├── InsertionSortList.cpp ├── Kreverselinkedlist.cpp ├── ReverseLinkListII.cpp ├── PartitionList.cpp ├── ListCycle.cpp ├── ReorderList.cpp └── MergeTwoSortedLists.cpp ├── TwoPointers ├── Diffk.cpp ├── IntersectionOfSortedArrays.cpp ├── 3Sum.cpp ├── CountingTriangles.cpp ├── RemoveElementfromArray.cpp ├── SortbyColor.cpp ├── ContainerWithMostWater.cpp ├── Minimizetheabsolutedifference.cpp ├── Array3Pointers.cpp ├── RemoveDuplicatesfromSortedArray.cpp ├── MaxContinuousSeriesof1s.cpp ├── 3SumZero.cpp ├── MergeTwoSortedListsII.cpp └── RemoveDuplicatesfromSortedArrayII.cpp ├── GraphDataStructure&Algorithms ├── SumOfFibonacciNumbers.cpp ├── SmallestSequenceWithGivenPrimes.cpp ├── LevelOrder.cpp ├── SteppingNumbers.cpp ├── BlackShapes.cpp └── CloneGraph.cpp ├── StacksAndQueues ├── NearestSmallerElement.cpp ├── RainWaterTrapped.cpp ├── RedundantBraces.cpp ├── EvaluateExpression.cpp ├── SimplifyDirectoryPath.cpp ├── LargestRectangleinHistogram.cpp └── MinStack.cpp ├── Backtracking ├── Combinations.cpp ├── Subset.cpp ├── LetterPhone.cpp ├── SubsetsII.cpp ├── Permutations.cpp ├── GenerateallParenthesesII.cpp ├── GrayCode.cpp ├── CombinationSumII.cpp └── KthPermutationSequence.cpp └── HeapsAndMaps ├── DistinctNumbersInWindow.cpp ├── MagicianAndChocolates.cpp └── NMaxPairCombinations.cpp /README.md: -------------------------------------------------------------------------------- 1 | # InterviewBit 2 | 3 | InterviewBit Programming Solutions. 4 | 5 | https://www.interviewbit.com 6 | -------------------------------------------------------------------------------- /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/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 | } -------------------------------------------------------------------------------- /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 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 | -------------------------------------------------------------------------------- /Math/LargestCoprimeDivisor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two positive numbers A and B. You need to find the maximum valued integer X such that: 3 | 4 | X divides A i.e. A % X = 0 5 | X and B are co-prime i.e. gcd(X, B) = 1 6 | For example, 7 | 8 | A = 30 9 | B = 12 10 | We return 11 | X = 5 12 | 13 | LINK: https://www.interviewbit.com/problems/largest-coprime-divisor/ 14 | */ 15 | 16 | int gcd(int a,int b) 17 | { 18 | if(b==0) 19 | return a; 20 | else 21 | return gcd(b,a%b); 22 | } 23 | 24 | int Solution::cpFact(int A, int B) 25 | { 26 | while(gcd(A,B)!=1) 27 | A /= gcd(A,B); 28 | return A; 29 | } -------------------------------------------------------------------------------- /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 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 | -------------------------------------------------------------------------------- /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 &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 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 | -------------------------------------------------------------------------------- /Arrays/MaxSumContiguousSubarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 3 | 4 | For example: 5 | 6 | Given the array [-2,1,-3,4,-1,2,1,-5,4], 7 | 8 | the contiguous subarray [4,-1,2,1] has the largest sum = 6. 9 | 10 | For this problem, return the maximum sum. 11 | 12 | LINK: https://www.interviewbit.com/problems/max-sum-contiguous-subarray/ 13 | */ 14 | 15 | int Solution::maxSubArray(const vector &A) 16 | { 17 | int mx = INT_MIN, mxt = 0; 18 | 19 | for(int i=0;i Solution::getRow(int n) 18 | { 19 | vector v; 20 | v.push_back(1); 21 | 22 | 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 | } -------------------------------------------------------------------------------- /Hashing/DiffkII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array A of 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 : 5 | 6 | Input : 7 | 8 | A : [1 5 3] 9 | k : 2 10 | Output : 11 | 12 | 1 13 | as 3 - 1 = 2 14 | 15 | Return 0 / 1 for this problem. 16 | 17 | LINK: https://www.interviewbit.com/problems/diffk-ii/ 18 | */ 19 | 20 | int Solution::diffPossible(const vector &A, int B) 21 | { 22 | unordered_map hash; 23 | 24 | int n=A.size(); 25 | 26 | for(int i=0;i= 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;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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /DynamicProgramming/BestTimeToBuyAndSellStocksI.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 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 5 | 6 | Example : 7 | 8 | Input : [1 2] 9 | Return : 1 10 | 11 | LINK: https://www.interviewbit.com/problems/best-time-to-buy-and-sell-stocks-i/ 12 | */ 13 | 14 | int Solution::maxProfit(const vector &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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /DynamicProgramming/JumpGameArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Determine if you are able to reach the last index. 7 | 8 | For example: 9 | A = [2,3,1,1,4], return 1 ( true ). 10 | 11 | A = [3,2,1,0,4], return 0 ( false ). 12 | 13 | Return 0/1 for this problem 14 | 15 | LINK: https://www.interviewbit.com/problems/jump-game-array/ 16 | */ 17 | 18 | int Solution::canJump(vector &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 | } -------------------------------------------------------------------------------- /BitManipulation/SingleNumberII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears thrice except for one which occurs once. 3 | 4 | Find that element which does not appear thrice. 5 | 6 | Note: Your algorithm should have a linear runtime complexity. 7 | 8 | Could you implement it without using extra memory? 9 | 10 | Example : 11 | 12 | Input : [1, 2, 4, 3, 3, 2, 2, 3, 1, 1] 13 | Output : 4 14 | 15 | LINK: https://www.interviewbit.com/problems/single-number-ii/ 16 | */ 17 | 18 | int Solution::singleNumber(const vector &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<=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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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::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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /BitManipulation/Numberof1Bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that takes an unsigned integer and returns the number of 1 bits it has. 3 | 4 | Example: 5 | 6 | The 32-bit integer 11 has binary representation 7 | 8 | 00000000000000000000000000001011 9 | so the function should return 3. 10 | 11 | Note that since Java does not have unsigned int, use long for Java 12 | 13 | LINK: https://www.interviewbit.com/problems/number-of-1-bits/ 14 | */ 15 | 16 | int Solution::numSetBits(unsigned int 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 | int cnt = 0; 24 | while(A) 25 | { 26 | cnt++; 27 | A = (A)&(A-1); 28 | } 29 | return cnt; 30 | } 31 | -------------------------------------------------------------------------------- /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/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 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;i0) 25 | { 26 | if(ispalin(s)) 27 | break; 28 | else 29 | { 30 | cnt++; 31 | s.erase(s.end()-1); 32 | } 33 | } 34 | return cnt; 35 | } -------------------------------------------------------------------------------- /DynamicProgramming/MaxProductSubarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest product. 3 | Return an integer corresponding to the maximum product possible. 4 | 5 | Example : 6 | 7 | Input : [2, 3, -2, 4] 8 | Return : 6 9 | 10 | Possible with [2, 3] 11 | 12 | LINK: https://www.interviewbit.com/problems/max-product-subarray/ 13 | */ 14 | 15 | int Solution::maxProduct(const vector &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;i &A, int B) 16 | { 17 | int n=A.size(); 18 | 19 | for(int i=0;i > &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 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 mp; 17 | int res = 0, cnt = 0, i = 0; 18 | int n = A.size(); 19 | 20 | while(i st; 16 | st.push(-1); 17 | 18 | int res = 0; 19 | 20 | for(int i=0;i 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 | } -------------------------------------------------------------------------------- /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) 20 | { 21 | int max1,max2,min1,min2; 22 | max1=max2=INT_MIN; 23 | min1=min2=INT_MAX; 24 | 25 | for(int i=0;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 &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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /DynamicProgramming/UniqueBinarySearchTreesII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given A, how many structurally unique BST’s (binary search trees) that store values 1...A? 3 | 4 | Example : 5 | 6 | Given A = 3, there are a total of 5 unique BST’s. 7 | 8 | 9 | 1 3 3 2 1 10 | \ / / / \ \ 11 | 3 2 1 1 3 2 12 | / / \ \ 13 | 2 1 2 3 14 | 15 | LINK: https://www.interviewbit.com/problems/unique-binary-search-trees-ii/ 16 | */ 17 | 18 | vector 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 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 | } -------------------------------------------------------------------------------- /Greedy/Bulbs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of current bulb. Given an initial state of all bulbs, find the minimum number of switches you have to press to turn on all the bulbs. You can press the same switch multiple times. 3 | 4 | Note : 0 represents the bulb is off and 1 represents the bulb is on. 5 | 6 | Example: 7 | 8 | Input : [0 1 0 1] 9 | Return : 4 10 | 11 | Explanation : 12 | press switch 0 : [1 0 1 0] 13 | press switch 1 : [1 1 0 1] 14 | press switch 2 : [1 1 1 0] 15 | press switch 3 : [1 1 1 1] 16 | 17 | LINK: https://www.interviewbit.com/problems/bulbs/ 18 | */ 19 | 20 | int Solution::bulbs(vector &A) 21 | { 22 | int n = A.size(); 23 | int sum = 0; 24 | int temp = 1; 25 | 26 | for(int i=0;ileft; 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 | } -------------------------------------------------------------------------------- /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 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /BitManipulation/ReverseBits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse bits of an 32 bit unsigned integer 3 | 4 | Example 1: 5 | 6 | x = 0, 7 | 8 | 00000000000000000000000000000000 9 | => 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 | } -------------------------------------------------------------------------------- /TwoPointers/3Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. 3 | Return the sum of the three integers. 4 | 5 | Assume that there will only be one solution 6 | 7 | Example: 8 | given array S = {-1 2 1 -4}, 9 | and target = 1. 10 | 11 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2) 12 | 13 | LINK: https://www.interviewbit.com/problems/3-sum/ 14 | */ 15 | 16 | int Solution::threeSumClosest(vector &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 > &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 &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/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(j2->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 | } -------------------------------------------------------------------------------- /Strings/LengthofLastWord.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | Example: 9 | 10 | Given s = "Hello World", 11 | 12 | return 5 as length("World") = 5. 13 | 14 | Please make sure you try to solve this problem without using library functions. Make sure you only traverse the string once. 15 | 16 | LINK: https://www.interviewbit.com/problems/length-of-last-word/ 17 | */ 18 | 19 | int Solution::lengthOfLastWord(const string s) 20 | { 21 | int n = s.length(),ind = 0,flag=1; 22 | 23 | 24 | for(int i=0;i0 && s[n-1]==' ') 36 | n--; 37 | 38 | if(ind>=n) 39 | return 0; 40 | else 41 | return (n-ind); 42 | } 43 | -------------------------------------------------------------------------------- /Arrays/AntiDiagonals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details. 3 | 4 | Example: 5 | 6 | 7 | Input: 8 | 9 | 1 2 3 10 | 4 5 6 11 | 7 8 9 12 | 13 | Return the following : 14 | 15 | [ 16 | [1], 17 | [2, 4], 18 | [3, 5, 7], 19 | [6, 8], 20 | [9] 21 | ] 22 | 23 | 24 | Input : 25 | 1 2 26 | 3 4 27 | 28 | Return the following : 29 | 30 | [ 31 | [1], 32 | [2, 3], 33 | [4] 34 | ] 35 | 36 | LINK: https://www.interviewbit.com/problems/anti-diagonals/ 37 | */ 38 | 39 | vector > 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::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 | } -------------------------------------------------------------------------------- /DynamicProgramming/EditDistance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two words A and B, find the minimum number of steps required to convert A to B. (each operation is counted as 1 step.) 3 | 4 | You have the following 3 operations permitted on a word: 5 | 6 | Insert a character 7 | Delete a character 8 | Replace a character 9 | Example : 10 | edit distance between 11 | "Anshuman" and "Antihuman" is 2. 12 | 13 | Operation 1: Replace s with t. 14 | Operation 2: Insert i. 15 | 16 | LINK: https://www.interviewbit.com/problems/edit-distance/ 17 | */ 18 | 19 | int Solution::minDistance(string A, string B) 20 | { 21 | int na = A.length(), nb = B.length(); 22 | 23 | int dp[na+1][nb+1]; 24 | 25 | for(int i=0;i<=na;i++) 26 | dp[i][0] = i; 27 | for(int j=0;j<=nb;j++) 28 | dp[0][j] = j; 29 | 30 | for(int i=1;i<=na;i++) 31 | { 32 | for(int j=1;j<=nb;j++) 33 | { 34 | if(A[i-1]==B[j-1]) 35 | dp[i][j] = dp[i-1][j-1]; 36 | else 37 | dp[i][j] = 1 + min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])); 38 | } 39 | } 40 | return dp[na][nb]; 41 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /Arrays/FindPermutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a positive integer n and a string s consisting only of letters D or I, you have to find any permutation of first n positive integer that satisfy the given input string. 3 | 4 | D means the next number is smaller, while I means the next number is greater. 5 | 6 | Notes 7 | 8 | Length of given string s will always equal to n - 1 9 | Your solution should run in linear time and space. 10 | Example : 11 | 12 | Input 1: 13 | 14 | n = 3 15 | 16 | s = ID 17 | 18 | Return: [1, 3, 2] 19 | 20 | LINK: https://www.interviewbit.com/problems/find-permutation/ 21 | */ 22 | 23 | vector 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/LargestNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a list of non negative integers, arrange them such that they form the largest number. 3 | 4 | For example: 5 | 6 | Given [3, 30, 34, 5, 9], the largest formed number is 9534330. 7 | 8 | Note: The result may be very large, so you need to return a string instead of an integer. 9 | 10 | LINK: https://www.interviewbit.com/problems/largest-number/ 11 | */ 12 | 13 | bool comp(int ai,int bi) 14 | { 15 | string a,b; 16 | a = to_string(ai); 17 | b = to_string(bi); 18 | string t1,t2; 19 | t1 = a+b; 20 | t2 = b+a; 21 | return t1 &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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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;iA[j]) 49 | cnt++; 50 | 51 | rank +=(cnt*fact(n-i-1))%MOD; 52 | } 53 | 54 | return (rank+1)%MOD; 55 | } -------------------------------------------------------------------------------- /TwoPointers/SortbyColor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array with n objects colored red, white or blue, 3 | sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. 4 | 5 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 6 | 7 | Note: Using library sort function is not allowed. 8 | 9 | Example : 10 | 11 | Input : [0 1 2 0 1 2] 12 | Modify array so that it becomes : [0 0 1 1 2 2] 13 | 14 | LINK: https://www.interviewbit.com/problems/sort-by-color/ 15 | */ 16 | 17 | void Solution::sortColors(vector &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 | } -------------------------------------------------------------------------------- /DynamicProgramming/MaxSumPathInBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find the maximum path sum. 3 | 4 | The path may start and end at any node in the tree. 5 | 6 | Example : 7 | 8 | Given the below binary tree, 9 | 10 | 1 11 | / \ 12 | 2 3 13 | Return 6. 14 | 15 | LINK: https://www.interviewbit.com/problems/max-sum-path-in-binary-tree/ 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 | int ans INT_MIN; 29 | 30 | int findMaxPathSum(TreeNode* root) 31 | { 32 | if(!root) 33 | return 0; 34 | 35 | int leftSum = findMaxPathSum(root->left); 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/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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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;i > 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 | } -------------------------------------------------------------------------------- /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 &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 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 &s) 28 | { 29 | int n = s.size(); 30 | int mnl = INT_MAX; 31 | 32 | for(int i=0;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/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 | } -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 area = 0; 25 | int l=0,r=A.size()-1; 26 | while(lv1) 48 | { 49 | res += v2-v1; 50 | i++; 51 | } 52 | else 53 | res += v1; 54 | } 55 | else 56 | res += v1; 57 | } 58 | return res; 59 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 > 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 | } -------------------------------------------------------------------------------- /Strings/AmazingSubarrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string S, and you have to find all the amazing substrings of S. 3 | 4 | Amazing Substring is one that starts with a vowel (a, e, i, o, u, A, E, I, O, U). 5 | 6 | Input 7 | 8 | Only argument given is string S. 9 | Output 10 | 11 | Return a single integer X mod 10003, here X is number of Amazing Substrings in given string. 12 | Constraints 13 | 14 | 1 <= length(S) <= 1e6 15 | S can have special characters 16 | Example 17 | 18 | Input 19 | ABEC 20 | 21 | Output 22 | 6 23 | 24 | Explanation 25 | Amazing substrings of given string are : 26 | 1. A 27 | 2. AB 28 | 3. ABE 29 | 4. ABEC 30 | 5. E 31 | 6. EC 32 | here number of substrings are 6 and 6 % 10003 = 6. 33 | 34 | LINK: https://www.interviewbit.com/problems/amazing-subarrays/ 35 | */ 36 | 37 | #define MOD 10003 38 | 39 | bool check(char c) 40 | { 41 | c = tolower(c); 42 | if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u') 43 | return true; 44 | return false; 45 | } 46 | 47 | int Solution::solve(string A) 48 | { 49 | int n = A.length(); 50 | int ans = 0; 51 | 52 | for(int i=0;i &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 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 &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 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 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 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 | } -------------------------------------------------------------------------------- /DynamicProgramming/NDigitNumbersWithDigitSumS.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find out the number of N digit numbers, whose digits on being added equals to a given number S. Note that a valid number starts from digits 1-9 except the number 0 itself. i.e. leading zeroes are not allowed. 3 | 4 | Since the answer can be large, output answer modulo 1000000007 5 | 6 | ** 7 | 8 | N = 2, S = 4 9 | Valid numbers are {22, 31, 13, 40} 10 | Hence output 4. 11 | 12 | LINK: https://www.interviewbit.com/problems/n-digit-numbers-with-digit-sum-s-/ 13 | */ 14 | 15 | typedef long long int ll; 16 | #define MOD 1000000007 17 | 18 | vector > 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 | } -------------------------------------------------------------------------------- /Hashing/Fraction.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. 3 | 4 | If the fractional part is repeating, enclose the repeating part in parentheses. 5 | 6 | Example : 7 | 8 | Given numerator = 1, denominator = 2, return "0.5" 9 | Given numerator = 2, denominator = 1, return "2" 10 | Given numerator = 2, denominator = 3, return "0.(6)" 11 | 12 | LINK: https://www.interviewbit.com/problems/fraction/ 13 | */ 14 | 15 | string Solution::fractionToDecimal(int A, int B) 16 | { 17 | if(A==0) 18 | return "0"; 19 | long long int a = A; 20 | long long int b = B; 21 | string res = ""; 22 | if((a<0)^(b<0)) 23 | res+='-'; 24 | a = abs(a); 25 | b = abs(b); 26 | res += to_string(a/b); 27 | 28 | long long int rem = a%b; 29 | 30 | if(rem==0) 31 | return res; 32 | 33 | res += '.'; 34 | 35 | unordered_map 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /HeapsAndMaps/MagicianAndChocolates.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given N bags, each bag contains Ai chocolates. There is a kid and a magician. In one unit of time, kid chooses a random bag i, eats Ai chocolates, then the magician fills the ith bag with floor(Ai/2) chocolates. 3 | 4 | Given Ai for 1 <= i <= N, find the maximum number of chocolates kid can eat in K units of time. 5 | 6 | For example, 7 | 8 | K = 3 9 | N = 2 10 | A = 6 5 11 | 12 | Return: 14 13 | At t = 1 kid eats 6 chocolates from bag 0, and the bag gets filled by 3 chocolates 14 | At t = 2 kid eats 5 chocolates from bag 1, and the bag gets filled by 2 chocolates 15 | At t = 3 kid eats 3 chocolates from bag 0, and the bag gets filled by 1 chocolate 16 | so, total number of chocolates eaten: 6 + 5 + 3 = 14 17 | 18 | Note: Return your answer modulo 10^9+7 19 | 20 | LINK: https://www.interviewbit.com/problems/magician-and-chocolates/ 21 | */ 22 | 23 | #define MOD 1000000007 24 | 25 | int Solution::nchoc(int A, vector &B) 26 | { 27 | long long int ans = 0; 28 | int n = B.size(); 29 | priority_queue pq; 30 | 31 | 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 &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) 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/MaxContinuousSeriesof1s.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given with an array of 1s and 0s. And you are given with an integer M, which signifies number of flips allowed. 3 | Find the position of zeros which when flipped will produce maximum continuous series of 1s. 4 | 5 | For this problem, return the indices of maximum continuous series of 1s in order. 6 | 7 | Example: 8 | 9 | Input : 10 | Array = {1 1 0 1 1 0 0 1 1 1 } 11 | M = 1 12 | 13 | Output : 14 | [0, 1, 2, 3, 4] 15 | 16 | If there are multiple possible solutions, return the sequence which has the minimum start index. 17 | 18 | LINK: https://www.interviewbit.com/problems/max-continuous-series-of-1s/ 19 | */ 20 | 21 | vector 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) 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) 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /TwoPointers/3SumZero.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? 3 | Find all unique triplets in the array which gives the sum of zero. 4 | 5 | Note: 6 | 7 | Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) 8 | The solution set must not contain duplicate triplets. For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: 9 | (-1, 0, 1) 10 | (-1, -1, 2) 11 | 12 | LINK: https://www.interviewbit.com/problems/3-sum-zero/ 13 | */ 14 | 15 | vector > 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=0;i--) 37 | { 38 | for(int j=nb-1;j>=0;j--) 39 | { 40 | bool match = (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/BlackShapes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given N * M field of O's and X's, where O=white, X=black 3 | Return the number of black shapes. A black shape consists of one or more adjacent X's (diagonals not included) 4 | 5 | Example: 6 | 7 | OOOXOOO 8 | OOXXOXO 9 | OXOOOXO 10 | 11 | answer is 3 shapes are : 12 | (i) X 13 | X X 14 | (ii) 15 | X 16 | (iii) 17 | X 18 | X 19 | Note that we are looking for connected shapes here. 20 | 21 | For example, 22 | 23 | XXX 24 | XXX 25 | XXX 26 | is just one single connected black shape. 27 | 28 | LINK: https://www.interviewbit.com/problems/black-shapes/ 29 | */ 30 | 31 | int n,m; 32 | int X[] = {0, 0, 1, -1}; 33 | int Y[] = {1, -1, 0, 0}; 34 | 35 | void dfs(int x, int y, vector &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 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 | } -------------------------------------------------------------------------------- /Hashing/2Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, find two numbers such that they add up to a specific target number. 3 | 4 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2. Please note that your returned answers (both index1 and index2 ) are not zero-based. 5 | Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ). Note that, if no pair exists, return empty list. 6 | 7 | If multiple solutions exist, output the one where index2 is minimum. If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them. 8 | 9 | Input: [2, 7, 11, 15], target=9 10 | Output: index1 = 1, index2 = 2 11 | 12 | LINK: https://www.interviewbit.com/problems/2-sum/ 13 | */ 14 | 15 | vector 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::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 | } -------------------------------------------------------------------------------- /TwoPointers/MergeTwoSortedListsII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted integer arrays A and B, merge B into A as one sorted array. 3 | 4 | Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. 5 | TIP: C users, please malloc the result into a new array and return the result. 6 | If the number of elements initialized in A and B are m and n respectively, the resulting size of array A after your code is executed should be m + n 7 | 8 | Example : 9 | 10 | Input : 11 | A : [1 5 8] 12 | B : [6 9] 13 | 14 | Modified A : [1 5 6 8 9] 15 | 16 | LINK: https://www.interviewbit.com/problems/merge-two-sorted-lists-ii/ 17 | */ 18 | 19 | void Solution::merge(vector &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) 20 | { 21 | int n = A.size(); 22 | int mxarea = 0, i = 0; 23 | 24 | stack st; 25 | 26 | while(i &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 | } -------------------------------------------------------------------------------- /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;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 | } -------------------------------------------------------------------------------- /TreeDataStructure/ZigZagLevelOrderTraversalBT.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between). 3 | 4 | Example : 5 | Given binary tree 6 | 7 | 3 8 | / \ 9 | 9 20 10 | / \ 11 | 15 7 12 | return 13 | 14 | [ 15 | [3], 16 | [20, 9], 17 | [15, 7] 18 | ] 19 | 20 | LINK: https://www.interviewbit.com/problems/zigzag-level-order-traversal-bt/ 21 | */ 22 | 23 | /** 24 | * Definition for binary tree 25 | * struct TreeNode { 26 | * int val; 27 | * TreeNode *left; 28 | * TreeNode *right; 29 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 30 | * }; 31 | */ 32 | 33 | vector > 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) 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;i &A, vector &B) 33 | { 34 | int x=A[0], y=B[0]; 35 | int cnt = 0; 36 | for(int i=1;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 | } -------------------------------------------------------------------------------- /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/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 | } -------------------------------------------------------------------------------- /DynamicProgramming/MinSumPathInTriangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 3 | 4 | For example, given the following triangle 5 | 6 | [ 7 | [2], 8 | [3,4], 9 | [6,5,7], 10 | [4,1,8,3] 11 | ] 12 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 13 | 14 | Note: 15 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 16 | 17 | LINK: https://www.interviewbit.com/problems/min-sum-path-in-triangle/ 18 | */ 19 | 20 | int Solution::minimumTotal(vector > &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 &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 | } -------------------------------------------------------------------------------- /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 &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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 &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 | } -------------------------------------------------------------------------------- /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;i &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/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 | } -------------------------------------------------------------------------------- /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 > 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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Strings/Atoi.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement atoi to convert a string to an integer. 3 | 4 | Example : 5 | 6 | Input : "9 2704" 7 | Output : 9 8 | Note: There might be multiple corner cases here. Clarify all your doubts using “See Expected Output”. 9 | 10 | Questions: Q1. Does string contain whitespace characters before the number? 11 | A. Yes Q2. Can the string have garbage characters after the number? 12 | A. Yes. Ignore it. Q3. If no numeric character is found before encountering garbage characters, what should I do? 13 | A. Return 0. Q4. What if the integer overflows? 14 | A. Return INT_MAX if the number is positive, INT_MIN otherwise. 15 | Warning : DO NOT USE LIBRARY FUNCTION FOR ATOI. 16 | If you do, we will disqualify your submission retroactively and give you penalty points. 17 | 18 | LINK: https://www.interviewbit.com/problems/atoi/ 19 | */ 20 | 21 | int Solution::atoi(const string A) 22 | { 23 | int n = A.length(); 24 | int i=0, neg=0; 25 | 26 | 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 | } -------------------------------------------------------------------------------- /BinarySearch/RotatedSortedArraySearch.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 3 | 4 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 ). 5 | 6 | You are given a target value to search. If found in the array, return its index, otherwise return -1. 7 | 8 | You may assume no duplicate exists in the array. 9 | 10 | Input : [4 5 6 7 0 1 2] and target = 4 11 | Output : 0 12 | 13 | NOTE : Think about the case when there are duplicates. Does your current solution work? How does the time complexity change?* 14 | 15 | LINK: https://www.interviewbit.com/problems/rotated-sorted-array-search/ 16 | */ 17 | 18 | int b_search(const vector &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 | } -------------------------------------------------------------------------------- /Hashing/SubstringConcatenation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string, S, and a list of words, L, that are all of the same length. 3 | 4 | Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. 5 | 6 | Example : 7 | 8 | S: "barfoothefoobarman" 9 | L: ["foo", "bar"] 10 | You should return the indices: [0,9]. 11 | (order does not matter). 12 | 13 | LINK: https://www.interviewbit.com/problems/substring-concatenation/ 14 | */ 15 | 16 | vector 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /Backtracking/CombinationSumII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. 3 | 4 | Each number in C may only be used once in the combination. 5 | 6 | Note: 7 | All numbers (including target) will be positive integers. 8 | Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 9 | The solution set must not contain duplicate combinations. 10 | Example : 11 | 12 | Given candidate set 10,1,2,7,6,1,5 and target 8, 13 | 14 | A solution set is: 15 | 16 | [1, 7] 17 | [1, 2, 5] 18 | [2, 6] 19 | [1, 1, 6] 20 | 21 | LINK: https://www.interviewbit.com/problems/combination-sum-ii/ 22 | */ 23 | 24 | set > 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /Arrays/SpiralOrderMatrixII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 3 | 4 | Example: 5 | 6 | Given n = 3, 7 | 8 | You should return the following matrix: 9 | 10 | [ 11 | [ 1, 2, 3 ], 12 | [ 8, 9, 4 ], 13 | [ 7, 6, 5 ] 14 | ] 15 | 16 | LINK: https://www.interviewbit.com/problems/spiral-order-matrix-ii/ 17 | */ 18 | 19 | vector > 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 | } -------------------------------------------------------------------------------- /HeapsAndMaps/NMaxPairCombinations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two arrays A & B of size N each. 3 | Find the maximum n elements from the sum combinations (Ai + Bj) formed from elements in array A and B. 4 | 5 | For example if A = [1,2], B = [3,4], then possible pair sums can be 1+3 = 4 , 1+4=5 , 2+3=5 , 2+4=6 6 | and maximum 2 elements are 6, 5 7 | 8 | Example: 9 | 10 | N = 4 11 | a[]={1,4,2,3} 12 | b[]={2,5,1,6} 13 | 14 | Maximum 4 elements of combinations sum are 15 | 10 (4+6), 16 | 9 (3+6), 17 | 9 (4+5), 18 | 8 (2+6) 19 | 20 | LINK: https://www.interviewbit.com/problems/n-max-pair-combinations/ 21 | */ 22 | 23 | vector 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/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 | } -------------------------------------------------------------------------------- /StacksAndQueues/MinStack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 3 | 4 | push(x) – Push element x onto stack. 5 | pop() – Removes the element on top of the stack. 6 | top() – Get the top element. 7 | getMin() – Retrieve the minimum element in the stack. 8 | Note that all the operations have to be constant time operations. 9 | 10 | Questions to ask the interviewer : 11 | 12 | Q: What should getMin() do on empty stack? 13 | A: In this case, return -1. 14 | 15 | Q: What should pop do on empty stack? 16 | A: In this case, nothing. 17 | 18 | Q: What should top() do on empty stack? 19 | A: In this case, return -1 20 | NOTE : If you are using your own declared global variables, make sure to clear them out in the constructor 21 | 22 | LINK: https://www.interviewbit.com/problems/min-stack/ 23 | */ 24 | 25 | stack 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 | } -------------------------------------------------------------------------------- /Strings/LongestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, find the longest palindromic substring in S. 3 | 4 | Substring of string S: 5 | 6 | S[i...j] where 0 <= i <= j < len(S) 7 | 8 | Palindrome string: 9 | 10 | A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. 11 | 12 | Incase of conflict, return the substring which occurs first ( with the least starting index ). 13 | 14 | Example : 15 | 16 | Input : "aaaabaaa" 17 | Output : "aaabaaa" 18 | 19 | LINK: https://www.interviewbit.com/problems/longest-palindromic-substring/ 20 | */ 21 | 22 | string Solution::longestPalindrome(string s) 23 | { 24 | int maxlen = 1, start = 0, low, high; 25 | int len = s.length(); 26 | 27 | for(int i=0;i=0 && high maxlen || ((high-low+1)==maxlen && low=0 && high maxlen || ((high-low+1)==maxlen && low 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 | */ -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /DynamicProgramming/RegularExpressionMatch.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement wildcard pattern matching with support for '?' and '*'. 3 | 4 | '?' : Matches any single character. 5 | '*' : Matches any sequence of characters (including the empty sequence). 6 | The matching should cover the entire input string (not partial). 7 | 8 | The function prototype should be: 9 | 10 | int isMatch(const char *s, const char *p) 11 | Examples : 12 | 13 | isMatch("aa","a") → 0 14 | isMatch("aa","aa") → 1 15 | isMatch("aaa","aa") → 0 16 | isMatch("aa", "*") → 1 17 | isMatch("aa", "a*") → 1 18 | isMatch("ab", "?*") → 1 19 | isMatch("aab", "c*a*b") → 0 20 | Return 1/0 for this problem. 21 | 22 | LINK: https://www.interviewbit.com/problems/regular-expression-match/ 23 | */ 24 | 25 | int Solution::isMatch(const string A, const string B) 26 | { 27 | int na = A.length(); 28 | int nb = B.length(); 29 | 30 | if(nb==0) 31 | return (na==0); 32 | 33 | bool dp[nb+1]; 34 | memset(dp,false,sizeof(dp)); 35 | 36 | dp[0]=true; 37 | 38 | for(int i=1;i<=nb;i++) 39 | if(B[i-1]=='*') 40 | dp[i] = dp[i-1]; 41 | 42 | bool temp; 43 | 44 | for(int i=1;i<=na;i++) 45 | { 46 | temp = dp[0]; 47 | for(int j=1;j<=nb;j++) 48 | { 49 | bool match = false; 50 | if(B[j-1]=='?' || A[i-1]==B[j-1]) 51 | match = temp; 52 | else 53 | if(B[j-1]=='*') 54 | match = dp[j] || dp[j-1]; 55 | 56 | temp = dp[j]; 57 | dp[j] = match; 58 | } 59 | dp[0]=false; 60 | } 61 | return dp[nb]; 62 | } -------------------------------------------------------------------------------- /Arrays/MergeOverlappingIntervals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | For example: 5 | 6 | Given [1,3],[2,6],[8,10],[15,18], 7 | 8 | return [1,6],[8,10],[15,18]. 9 | 10 | Make sure the returned intervals are sorted. 11 | 12 | LINK: https://www.interviewbit.com/problems/merge-overlapping-intervals/ 13 | */ 14 | 15 | /** 16 | * Definition for an interval. 17 | * struct Interval { 18 | * int start; 19 | * int end; 20 | * Interval() : start(0), end(0) {} 21 | * Interval(int s, int e) : start(s), end(e) {} 22 | * }; 23 | */ 24 | 25 | bool comp(Interval i1, Interval i2) 26 | { 27 | return (i1.start < i2.start); 28 | } 29 | 30 | vector 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/SetMatrixZeros.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an m x n matrix of 0s and 1s, if an element is 0, set its entire row and column to 0. 3 | 4 | Do it in place. 5 | 6 | Example 7 | 8 | Given array A as 9 | 10 | 1 0 1 11 | 1 1 1 12 | 1 1 1 13 | On returning, the array A should be : 14 | 15 | 0 0 0 16 | 1 0 1 17 | 1 0 1 18 | Note that this will be evaluated on the extra memory used. Try to minimize the space and time complexity. 19 | 20 | LINK: https://www.interviewbit.com/problems/set-matrix-zeros/ 21 | */ 22 | 23 | void Solution::setZeroes(vector > &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;inext; 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 | } -------------------------------------------------------------------------------- /Backtracking/KthPermutationSequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The set [1,2,3,…,n] contains a total of n! unique permutations. 3 | 4 | By listing and labeling all of the permutations in order, 5 | We get the following sequence (ie, for n = 3 ) : 6 | 7 | 1. "123" 8 | 2. "132" 9 | 3. "213" 10 | 4. "231" 11 | 5. "312" 12 | 6. "321" 13 | Given n and k, return the kth permutation sequence. 14 | 15 | For example, given n = 3, k = 4, ans = "231" 16 | 17 | Good questions to ask the interviewer : 18 | What if n is greater than 10. How should multiple digit numbers be represented in string? 19 | In this case, just concatenate the number to the answer. 20 | so if n = 11, k = 1, ans = "1234567891011" 21 | Whats the maximum value of n and k? 22 | In this case, k will be a positive integer thats less than INT_MAX. 23 | n is reasonable enough to make sure the answer does not bloat up a lot. 24 | 25 | LINK: https://www.interviewbit.com/problems/kth-permutation-sequence/ 26 | */ 27 | 28 | int fact(int n) 29 | { 30 | if(n>12) 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 | -------------------------------------------------------------------------------- /DynamicProgramming/FlipArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of positive elements, you have to flip the sign of some of its elements such that the resultant sum of the elements of array should be minimum non-negative(as close to zero as possible). Return the minimum no. of elements whose sign needs to be flipped such that the resultant sum is minimum non-negative. 3 | 4 | Constraints: 5 | 6 | 1 <= n <= 100 7 | Sum of all the elements will not exceed 10,000. 8 | 9 | Example: 10 | 11 | A = [15, 10, 6] 12 | ans = 1 (Here, we will flip the sign of 15 and the resultant sum will be 1 ) 13 | 14 | A = [14, 10, 4] 15 | ans = 1 (Here, we will flip the sign of 14 and the resultant sum will be 0) 16 | 17 | Note that flipping the sign of 10 and 4 also gives the resultant sum 0 but flippings there are not minimum 18 | 19 | LINK: https://www.interviewbit.com/problems/flip-array/ 20 | */ 21 | 22 | int Solution::solve(const vector &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/WordBreakII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. 3 | 4 | Return all such possible sentences. 5 | 6 | For example, given 7 | 8 | s = "catsanddog", 9 | dict = ["cat", "cats", "and", "sand", "dog"]. 10 | A solution is 11 | 12 | [ 13 | "cat sand dog", 14 | "cats and dog" 15 | ] 16 | Make sure the strings are sorted in your result. 17 | 18 | LINK: https://www.interviewbit.com/problems/word-break-ii/ 19 | */ 20 | 21 | vector 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 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 | } -------------------------------------------------------------------------------- /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 | } --------------------------------------------------------------------------------