├── .gitignore
├── .idea
├── misc.xml
└── vcs.xml
├── C++
├── Arrays
│ └── Trapping the rain water.cpp
├── Bit Manipulation
│ ├── Checking Whether K-th Bit is Set or Not.cpp
│ ├── Clearing the K-th bit of a number.cpp
│ ├── Setting the K-th bit of a number.cpp
│ ├── Toggling Rightmost Set Bit of a number.cpp
│ └── Toggling the K-th bit of a number.cpp
├── Dynamic Programming
│ ├── Edit Distance.cpp
│ ├── Longest Common Subsequence.cpp
│ ├── Longest Common Substring.cpp
│ ├── Longest Increasing Subsequence.cpp
│ ├── Longest palindromic Subsequence.cpp
│ └── Matrix Chain Multiplication.cpp
├── Graph Algorithms
│ ├── All Pair Shortest Path Problem.cpp
│ ├── Breadth First Search.cpp
│ ├── Connected Components Algorithm DFS.cpp
│ ├── Depth First Search.cpp
│ ├── Kruskal's Minimum Spanning Tree Algorithm.cpp
│ ├── Prims Minimum Spanning Tree Algorithm.cpp
│ ├── Recursive Depth First Search.cpp
│ ├── Single Shortest Path Bellman Ford Algorithm.cpp
│ ├── Single Source Shortest Path Dijkstra Algorithm.cpp
│ └── Topological Sorting.cpp
├── Heaps - Priority Queues
│ └── K-th Largest element of the stream.cpp
├── Linked List
│ └── Reverse a linked list recursively.cpp
├── Number Theory Algorithms
│ ├── Divisors.cpp
│ └── Sieve of Eratosthenes.cpp
├── Recursion
│ ├── Partition of array on the pivot.cpp
│ └── Permutation of a string.cpp
├── Segment Tree
│ └── Segment Tree.cpp
├── Stacks - Queue
│ └── CircularQueue.cpp
├── String Algorithms
│ ├── KMP.cpp
│ └── Trie.cpp
└── Union Find
│ └── Union Find.cpp
├── LICENSE
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── python
├── array
│ ├── arrayaddition.py
│ ├── commonthreesortedarray.py
│ ├── countinversionofsize3.py
│ ├── flip0smaximum1s.py
│ ├── longestsamesumspan.py
│ ├── maximumsumpathtwoarrays.py
│ ├── maxproductsubarray.py
│ ├── numberoftrianglesunsortedarray.py
│ ├── positiveandnegativealternativelymaintainingorder.py
│ ├── rearrangearrayperindex.py
│ ├── reorderarraybyindex.py
│ ├── rotationwithmaxsum.py
│ ├── smallestintegernotrepresentedbysubsetsum.py
│ ├── tripletsumlessthantotal.py
│ └── zigzagarrangement.py
├── dynamic
│ ├── bitonicsequence.py
│ ├── boxstacking.py
│ ├── breakword.py
│ ├── coin_change_num_ways.py
│ ├── coinchangingmincoins.py
│ ├── count_num_A.py
│ ├── count_num_binary_without_consec_1.py
│ ├── cutting_rod.py
│ ├── dice_throw_ways.py
│ ├── editdistance.py
│ ├── egg_drop.py
│ ├── knapsack_01.py
│ ├── kth_ugly_number.py
│ ├── longest_common_subsequence.py
│ ├── longest_common_substring.py
│ ├── longest_increasing_subsequence.py
│ ├── longest_palindromic_subsequence.py
│ ├── matrix_chain_order.py
│ ├── maximum_increasing_subsequence.py
│ ├── nth_fibonacci.py
│ ├── num_bst.py
│ ├── num_paths_nm_matrix.py
│ ├── num_trees_preorder.py
│ ├── optimal_bst.py
│ ├── stockbuysellktransactions.py
│ ├── string_interleaving.py
│ ├── sub_rectangular_maximum_sum.py
│ ├── subset_sum.py
│ ├── symbolexpressionevaluation.py
│ └── weighted_job_scheduling_max_profit.py
├── geometry
│ └── skylinedrawing.py
├── graph
│ ├── cycledirectedgraph.py
│ ├── cycleundirectedgraph.py
│ ├── dijkstrashortestpath.py
│ ├── disjointset.py
│ ├── floydwarshall.py
│ ├── fordfulkerson.py
│ ├── graph.py
│ ├── graphtraversal.py
│ ├── kruskalmst.py
│ ├── primmst.py
│ ├── priorityqueue.py
│ └── topologicalsort.py
├── recursion
│ ├── setpairtogether.py
│ └── stringpermutation.py
├── string
│ ├── Z_Algorithm.py
│ ├── knuthmorrispratt.py
│ └── rabinkarp.py
└── tree
│ ├── binary_tree.py
│ ├── construct_tree_from_inorder_preorder.py
│ ├── fenwick_tree.py
│ ├── largest_bst_in_binary_tree.py
│ ├── max_depth_binary_tree.py
│ ├── morris_traversal.py
│ └── segmenttreesum.py
├── src
└── com
│ └── interview
│ ├── array
│ ├── AdditiveNumber.java
│ ├── ArrayAddition.java
│ ├── BestMeetingPoint.java
│ ├── BuySellStockProfit.java
│ ├── CheckIfArrayElementsAreConsecutive.java
│ ├── ChunkMerge.java
│ ├── CommonThreeSortedArray.java
│ ├── ConvertAnArrayIntoDecreaseIncreaseFashion.java
│ ├── CountInversionOfSize3.java
│ ├── CountSmallerOnRight.java
│ ├── DivideNumbersInEqualGroupWithClosestSum.java
│ ├── DuplicateNumberDetection.java
│ ├── DuplicateWithinkIndices.java
│ ├── FindElementsOccurringNByKTimesTetris.java
│ ├── FirstPositiveMissing.java
│ ├── Flip0sMaximum1s.java
│ ├── FourSum.java
│ ├── GasStationCircle.java
│ ├── GreedyTextJustification.java
│ ├── GroupElementsInSizeM.java
│ ├── HIndex.java
│ ├── IncreasingSubsequnceOfLength3WithMaxProduct.java
│ ├── IncreasingTripletSubsequence.java
│ ├── JumpGame.java
│ ├── KadaneWrapArray.java
│ ├── KthElementInArray.java
│ ├── KthLargestInTwoSortedArray.java
│ ├── LargerElementOnRight.java
│ ├── LargestMountain.java
│ ├── LargestSubArrayWithEqual0sAnd1s.java
│ ├── LeetCodeCandy.java
│ ├── LongestConsecutiveSubsequence.java
│ ├── LongestIncreasingSubSequenceOlogNMethod.java
│ ├── LongestSameSumSpan.java
│ ├── LongestSubstringWithAtMost2Char.java
│ ├── MaxNumberFromTwoArray.java
│ ├── MaxProductSubarray.java
│ ├── MaxRepeatingNumber.java
│ ├── MaximumGap.java
│ ├── MaximumIminusJSuchThatAiGTAj.java
│ ├── MaximumMinimumArrangement.java
│ ├── MaximumOfSubarrayOfSizeK.java
│ ├── MaximumSumPathTwoArrays.java
│ ├── MaximumSumThreeNonOverlappingSubarray.java
│ ├── MeetingRooms.java
│ ├── MinimumDistanceBetweenTwoNumbers.java
│ ├── MinimumNumberFromSequence.java
│ ├── MinimumSortedWhichSortsEntireArray.java
│ ├── MissingRanges.java
│ ├── MoveAllZerosToEnd.java
│ ├── MultiplyAllFieldsExceptOwnPosition.java
│ ├── NthElementOfCountNumberSequence.java
│ ├── NumberOfTrianglesInUnsortedArray.java
│ ├── PositiveAndNegativeNumberAlternatively.java
│ ├── PositiveAndNegativeNumberAlternativelyMaintainingOrder.java
│ ├── RearrangeArrayPerIndex.java
│ ├── RearrangeSuchThatArriBecomesArrArri.java
│ ├── ReorderArrayByIndex.java
│ ├── RepeatingAndMissingNumber.java
│ ├── RotationWithMaxSum.java
│ ├── SelfCrossing.java
│ ├── ShortestPalindrome.java
│ ├── SmallestIntegerNotRepresentedBySubsetSum.java
│ ├── SmallestSubarrayWithAtleastKSum.java
│ ├── SortedArrayTransformation.java
│ ├── StableMarriageProblem.java
│ ├── SubarrayWithGivenSum.java
│ ├── SummaryRanges.java
│ ├── ThreeSumSmallerThanTarget.java
│ ├── TrappingWater.java
│ ├── TripletInArray.java
│ ├── TripletSumLessThanTotal.java
│ ├── TugOfWar.java
│ ├── WaterContainer.java
│ ├── WiggleSort.java
│ └── ZigZagArrangement.java
│ ├── binarysearch
│ ├── ArithmeticProgressionSearch.java
│ ├── BinarySearch.java
│ ├── CircularBinarySearch.java
│ ├── CountNDistinctPairsWithDifferenceK.java
│ ├── FirstOccurrenceOfNumberInSortedArray.java
│ ├── FloorAndCeilingSortedArray.java
│ ├── MedianOfTwoSortedArray.java
│ ├── MedianOfTwoSortedArrayOfDifferentLength.java
│ ├── MinimumInSortedRotatedArray.java
│ ├── MissingNumberInConsecutiveNumbers.java
│ ├── MonotonicallyIncreasingFunctionBecomesPositive.java
│ ├── NumberOfPairWithXPowerYGreaterThanYPowerX.java
│ ├── PeakElement.java
│ ├── SearchForRange.java
│ ├── SearchInsertPosition.java
│ ├── SortedAndRotatedArraySearch.java
│ └── SquareRootOfNumber.java
│ ├── bits
│ ├── AddTwoNumberInBinaryRepresentation.java
│ ├── BitRotation.java
│ ├── ByteAsStorage.java
│ ├── CountBits.java
│ ├── CountingBitsTillNum.java
│ ├── DrawHorizontalLine.java
│ ├── FindNumberOccurringOnceOtherNumbers3Times.java
│ ├── GrayCode.java
│ ├── InsertMintoNiTojBits.java
│ ├── MaxProductWordLength.java
│ ├── MissingNumbers.java
│ ├── NextHigherAndNextLowerWithSameNumberBits.java
│ ├── NextPowerOf2.java
│ ├── NumberOccuringOddTimes.java
│ ├── NumberOfBitsFlipToConvertNToM.java
│ ├── RealNumberToBinary.java
│ ├── RepeatedDnaSequence.java
│ ├── ReverseBits.java
│ ├── SquareOfNumber.java
│ ├── SwapOddEvenBits.java
│ ├── SwapTwoBits.java
│ └── WinnerWithBeautifulNumber.java
│ ├── dynamic
│ ├── BitonicSequence.java
│ ├── BoxStacking.java
│ ├── BreakMultipleWordsWithNoSpaceIntoSpace.java
│ ├── BurstBalloons.java
│ ├── CoinChanging.java
│ ├── CoinChangingMinimumCoin.java
│ ├── CountAs.java
│ ├── CountNumberOfBinaryWithoutConsecutive1s.java
│ ├── CountNumberOfTreePreorder.java
│ ├── CountNumberOfTreesInBST.java
│ ├── CutRodToMinimizeCost.java
│ ├── CuttingRod.java
│ ├── DecodeWays.java
│ ├── DiceThrowWays.java
│ ├── DistinctSubsequence.java
│ ├── DungeonGame.java
│ ├── EditDistance.java
│ ├── EggDropping.java
│ ├── ExpressionEvaluation.java
│ ├── FibonacciSeries.java
│ ├── Immutable2DSumRangeQuery.java
│ ├── Knapsack01.java
│ ├── LongestCommonSubsequence.java
│ ├── LongestCommonSubstring.java
│ ├── LongestEvenLengthSubstringOfEqualHalf.java
│ ├── LongestIncreasingPath.java
│ ├── LongestIncreasingSubsequence.java
│ ├── LongestPalindromicSubsequence.java
│ ├── MatrixMultiplicationCost.java
│ ├── MaxSumForNonAdjacentElements.java
│ ├── MaximizeSkiGates.java
│ ├── MaximumLengthChainPair.java
│ ├── MaximumProductCutting.java
│ ├── MaximumRectangularSubmatrixOf1s.java
│ ├── MaximumSizeSubMatrix.java
│ ├── MaximumSumSubsequence.java
│ ├── MinCostPath.java
│ ├── MinJumpToReachEnd.java
│ ├── MinimumCostTrainTicket.java
│ ├── MinimumNumberOfPerfectSquares.java
│ ├── MinimumTriangleSum.java
│ ├── NPotGold.java
│ ├── NumberOfPathsInMxNMatrix.java
│ ├── NumberOfWaysToScorePoints.java
│ ├── OptimalTreeSearch.java
│ ├── PaintHouse.java
│ ├── PalindromePartition.java
│ ├── PhoneDialNumberOfCombinationOfSizeK.java
│ ├── RegexMatching.java
│ ├── RemoveFromEndToMake2IntoMinGreaterThanMax.java
│ ├── ScrambledString.java
│ ├── StockBuySellKTransactions.java
│ ├── SubRectangularMatrixWithMaximumSum.java
│ ├── SubsetSum.java
│ ├── SubsquareSurrounedByXs.java
│ ├── SymbolExpressionEvaluation.java
│ ├── TextJustification.java
│ ├── TwoStringInterleavingToFormThird.java
│ ├── UglyNumbers.java
│ ├── WeightedJobSchedulingMaximumProfit.java
│ └── WildCardMatching.java
│ ├── geometry
│ ├── ClosestPairOfPoints.java
│ ├── GrahamScanConvexHull.java
│ ├── JarvisMarchConvexHull.java
│ ├── MaximumPointsOnSameLine.java
│ └── SkylineDrawing.java
│ ├── graph
│ ├── AlientDictionary.java
│ ├── AllCyclesInDirectedGraphJohnson.java
│ ├── AllCyclesInDirectedGraphTarjan.java
│ ├── ArticulationPoint.java
│ ├── BellmanFordShortestPath.java
│ ├── BinaryMaxHeap.java
│ ├── BinaryMinHeap.java
│ ├── BiparteGraph.java
│ ├── Boggle.java
│ ├── Bridge.java
│ ├── CloneDirectedGraph.java
│ ├── CloneGraph.java
│ ├── ConvertOneWordToAnother.java
│ ├── CourseSchedule.java
│ ├── CycleInDirectedGraph.java
│ ├── CycleUndirectedGraph.java
│ ├── DAGShortestPathTopological.java
│ ├── DijkstraShortestPath.java
│ ├── DirectedGraphConnectivity.java
│ ├── DisjointSet.java
│ ├── EulerianPathAndCircuit.java
│ ├── EvaluateDivison.java
│ ├── FillOsWIthXsIfSurroundedByXs.java
│ ├── FloodFillAlgorithm.java
│ ├── FloydWarshallAllPairShortestPath.java
│ ├── FordFulkerson.java
│ ├── Graph.java
│ ├── GraphColoring.java
│ ├── GraphTraversal.java
│ ├── HamiltonianCycle.java
│ ├── KruskalMST.java
│ ├── MaximumBiparteMatching.java
│ ├── MinimumHeightTree.java
│ ├── NumberOfIsland.java
│ ├── NumberOfIslandDynamic.java
│ ├── NumberofTriangles.java
│ ├── PrimMST.java
│ ├── PrintAllPathFromSourceToDestination.java
│ ├── ShortestDistanceFromExit.java
│ ├── StronglyConnectedComponent.java
│ ├── TarjanStronglyConnectedComponent.java
│ ├── TopologicalSort.java
│ ├── TransitiveClosure.java
│ ├── TravelingSalesmanHeldKarp.java
│ ├── ValidTree.java
│ ├── WallsAndGates.java
│ └── WordLadder.java
│ ├── linklist
│ ├── AddNumberRepresentedByLinkList.java
│ ├── CopyLinkListWIthArbitPointer.java
│ ├── DeleteDuplicateNodes.java
│ ├── DeleteNAfterMNodes.java
│ ├── DeleteNodeWithGreaterValueOnRight.java
│ ├── DoubleLinkList.java
│ ├── Flatten2DList.java
│ ├── FlattenLinkList.java
│ ├── InsertionSortLinkList.java
│ ├── LRUCache.java
│ ├── LRUCacheLeetCode.java
│ ├── LinkList.java
│ ├── LinkListIsPalindrome.java
│ ├── LinkListToCompleteBinaryTree.java
│ ├── LoopInLinkList.java
│ ├── MergeForLargestSum.java
│ ├── MergeSortLinkList.java
│ ├── MiddleElementOfLinkList.java
│ ├── MultiplyTwoNumbersLinkList.java
│ ├── QuickSortSingleLinkList.java
│ ├── RemoveDuplicatesSortedList.java
│ ├── RemoveMiddleElementsOfLineSegment.java
│ ├── ReorderList.java
│ ├── ReverseAlternateKNodes.java
│ ├── ReverseAlternateNodeAndAppendAtEnd.java
│ ├── ReverseKNodes.java
│ ├── RotateList.java
│ ├── ShuffleMerge.java
│ ├── SortNearlySortedList.java
│ ├── SortedCircularLinkList.java
│ ├── SortedLLToBalancedBST.java
│ ├── StackWithLinkListMiddleOperation.java
│ ├── SwapTwoNodesInDoubleLL.java
│ └── TripletToSumInLinkList.java
│ ├── misc
│ ├── AddingTwoSetOfIntervals.java
│ ├── AngleBetweenHourAndMinuteHand.java
│ ├── BulbSwitcher.java
│ ├── CandiesProblem.java
│ ├── ContainsNumberWithinKDistance.java
│ ├── ConvertNumberIntoBase26.java
│ ├── CountRanges.java
│ ├── DayDifferenceBetweenTwoDates.java
│ ├── DifferenceBetweenTwoTime.java
│ ├── FindingCelebrity.java
│ ├── FloatPointConversion.java
│ ├── FourPointsFormSquare.java
│ ├── GetKthPermutation.java
│ ├── HammingDistanceBetweenPair.java
│ ├── InsertInterval.java
│ ├── IntegerListParser.java
│ ├── KthLargestInRowiseColumnWiseSorted2DArray.java
│ ├── LoadBalancers.java
│ ├── NestedIterator.java
│ ├── NumberToWord.java
│ ├── PrimeNumbersBeforeN.java
│ ├── Read4Function.java
│ ├── RomanNumberToDecimal.java
│ └── SparseTableRangeMinimumQuery.java
│ ├── multiarray
│ ├── Fill2DMatrixWith1.java
│ ├── GameOfLife.java
│ ├── LongestConsecutiveIntegerInUnsorted2DArray.java
│ ├── MatrixCalculation.java
│ ├── MatrixFindAllSubSquareRectangleMatrix.java
│ ├── MatrixInDiagonalOrder.java
│ ├── MatrixOf0sAnd1s.java
│ ├── MoveCellPerCellValue.java
│ ├── Mutable2DSumRangeQuery.java
│ ├── RotateImage.java
│ ├── ShortestDistanceFromAllBuildings.java
│ ├── SmallestRectangleBlackPixel.java
│ ├── SpiralGeneration.java
│ ├── SpiralPrinting.java
│ └── TilingProblem.java
│ ├── multithreaded
│ ├── BoundedBlockingQueue.java
│ ├── CountingWord.java
│ ├── DependencyTaskExecutor.java
│ ├── FillupMatrix.java
│ ├── MinMaxKeeper.java
│ ├── PrintInSequence.java
│ ├── RealTimeCounter.java
│ ├── SingleQueueDomainTableUpdate.java
│ ├── SpinLockMutex.java
│ ├── ThreadPoolExample.java
│ └── ThreadPoolImpl.java
│ ├── number
│ ├── AggregateNumber.java
│ ├── AllStrobogrammaticNumber.java
│ ├── ArithemeticProgressionExists.java
│ ├── ArrayMultiplication.java
│ ├── BasicCalculator.java
│ ├── BinomialCoefficient.java
│ ├── ConvertToBaseN.java
│ ├── CountNoOf2s.java
│ ├── CountNumbersNotIncluding4.java
│ ├── DivisionWithoutDivisionOperator.java
│ ├── EuclideanAlgoForGCD.java
│ ├── FactorialOfLargeNumber.java
│ ├── GenerateSignature.java
│ ├── LargestMultipleOf3inArray.java
│ ├── LuckyNumbers.java
│ ├── MedianOf3Number.java
│ ├── MthNumberInNSizeArray.java
│ ├── NBy2PairSumToK.java
│ ├── NextLargestPalindrome.java
│ ├── NotIncluding4.java
│ ├── NumberOfCombinationsForStairs.java
│ ├── PermutationBiggerThanNumber.java
│ ├── PermutationLargerThanGivenArray.java
│ ├── PowerFunction.java
│ ├── RearrangeNumberInArrayToFormLargestNumber.java
│ ├── RussianPeasantMultiplication.java
│ ├── SmallestNumberGreaterThanGiveNumberIncreasingSequence.java
│ ├── SquareRoot.java
│ ├── StrobogrammaticNumber.java
│ ├── Trailing0sinFactorial.java
│ └── UniquePartitionOfInteger.java
│ ├── playground
│ └── TestInnerClass.java
│ ├── random
│ ├── Rand7UsingRand5.java
│ ├── RandomCountrySelectionByPopluation.java
│ ├── SelectMRandomNumbersInStream.java
│ └── ShuffleArray.java
│ ├── recursion
│ ├── AllAdjacentCombination.java
│ ├── Bracketology.java
│ ├── ChainWordsToFormCircle.java
│ ├── Combination.java
│ ├── CombinationOfSizeK.java
│ ├── CombinationWithStar.java
│ ├── DifferentWaysToAddParentheses.java
│ ├── FancyShuffle.java
│ ├── InterpretationOfArray.java
│ ├── KeyPadPermutation.java
│ ├── LongestAbsolutePath.java
│ ├── MinimumEditForReversePolishNotation.java
│ ├── NQueenProblem.java
│ ├── OneEditApart.java
│ ├── OperatorAdditionForTarget.java
│ ├── OptimalDivision.java
│ ├── PrintAllPathFromTopLeftToBottomRight.java
│ ├── PrintAllSubsequence.java
│ ├── PrintArrayInAdjacentWay.java
│ ├── PrintArrayInCustomizedFormat.java
│ ├── PrintSumCombination.java
│ ├── ReconstructItinerary.java
│ ├── RemoveInvalidParenthesis.java
│ ├── RestoreIPAddresses.java
│ ├── SetPairTogether.java
│ ├── StringInterleaving.java
│ ├── StringPermutation.java
│ ├── StringPermutationRotation.java
│ ├── SudokuSolver.java
│ ├── WordCombination.java
│ └── WordPattern.java
│ ├── regex
│ └── MultiSpaceReplacement.java
│ ├── sort
│ ├── CountingSort.java
│ ├── HeapSort.java
│ ├── IterativeQuickSort.java
│ ├── MergeSort.java
│ ├── PanCakeSorting.java
│ ├── QuickSort.java
│ ├── RadixSort.java
│ ├── Sort0toN3.java
│ └── SortArrayByFrequence.java
│ ├── stackqueue
│ ├── CircularQueue.java
│ ├── MaximumHistogram.java
│ ├── MedianFinder.java
│ ├── RealTimeCounter.java
│ ├── RealTimeCounterUsingCircularQueue.java
│ ├── RemoveDuplicateMaintainingOrder.java
│ ├── RemoveExtraBrackets.java
│ ├── ReverseStackUsingRecursion.java
│ ├── SimplyPath.java
│ └── StockSpanProblem.java
│ ├── string
│ ├── AnagramOfFirstAsSubstring.java
│ ├── CycleLeaderIteration.java
│ ├── GroupAnagramsTogether.java
│ ├── InPlaceTransformationOfString.java
│ ├── LexicographicRankInPermutation.java
│ ├── LongestPalindromeSubstring.java
│ ├── LongestSubstringWithKDistinctCharacters.java
│ ├── LongestSubstringWithoutRepetingCharacter.java
│ ├── MultiplyStrings.java
│ ├── NTMatch.java
│ ├── PalindromePair.java
│ ├── PrintAnagramTogether.java
│ ├── RabinKarpSearch.java
│ ├── RearrangeDuplicateCharsdDistanceAway.java
│ ├── RemoveConsecutiveDuplicate.java
│ ├── RunLengthEncoding.java
│ ├── SmallestWindowContaingAllCharacters.java
│ ├── StringEncoderDecoder.java
│ ├── SubstringSearch.java
│ ├── SubtringWithConcatentationOfWords.java
│ ├── ValidPalindrome.java
│ ├── ValidWordAbbreviation.java
│ ├── WordAbbreviationCombination.java
│ └── ZAlgorithm.java
│ ├── suffixprefix
│ ├── SuffixArray.java
│ ├── SuffixTree.java
│ ├── TernaryTree.java
│ └── Trie.java
│ └── tree
│ ├── AVLTree.java
│ ├── AddGreaterValueNodeToEveryNode.java
│ ├── ArbitaryTreeToChildSumTree.java
│ ├── BSTOneChildPreOrderTraversal.java
│ ├── BSTSearch.java
│ ├── BTree.java
│ ├── BinaryTree.java
│ ├── BinaryTreeFromParentRepresentation.java
│ ├── BinaryTreeMaximumPathSum.java
│ ├── BinaryTreeToCircularLinkList.java
│ ├── BinaryTreeToDoubleLinkList.java
│ ├── BinaryTreeToSortedLinkList.java
│ ├── BoundaryTraversal.java
│ ├── ClosestValueBinaryTree.java
│ ├── ConnectNodesAtSameLevel.java
│ ├── ConstructAllBinaryTreeFromInorderTraversal.java
│ ├── ConstructBSTFromPreOrderArray.java
│ ├── ConstructFullTreeFromPreOrderPostOrder.java
│ ├── ConstructTreeFromInOrderPreOrder.java
│ ├── ConstructTreeFromLevelOrderInOrder.java
│ ├── ConstructTreeFromPreOrderTraversalWith0or2Child.java
│ ├── ContructTreeFromInOrderTraversalRootGreaterThanChild.java
│ ├── ContructTreeFromInorderPostOrder.java
│ ├── CountNodesCompleteTree.java
│ ├── CountNumberOfSmallerElementOnRight.java
│ ├── CountPathSum.java
│ ├── CountUnivalueTree.java
│ ├── CousinNodes.java
│ ├── DegenerateBinaryTreeToSortedLL.java
│ ├── DiameterOfTree.java
│ ├── FenwickTree.java
│ ├── FlattenLinkListToBinaryTreePreorder.java
│ ├── HeightBalanced.java
│ ├── HuffmanEncoding.java
│ ├── IdenticalTrees.java
│ ├── InorderSuccessor.java
│ ├── IntervalTree.java
│ ├── IsBST.java
│ ├── IsCompleteBinaryTree.java
│ ├── IsPreOrderArrayBST.java
│ ├── KClosestValueInBinaryTree.java
│ ├── LargestBSTInBinaryTree.java
│ ├── LargestIndependentSetInTree.java
│ ├── LeavesOfBinaryTree.java
│ ├── LevelOrderTraversal.java
│ ├── LevelOrderTraversalInReverse.java
│ ├── LongestConsecutiveSequence.java
│ ├── LowestCommonAncestorInBinaryTree.java
│ ├── LowestCommonAncestoryBinarySearchTree.java
│ ├── MorrisTraversal.java
│ ├── NextInorderSuccessorIterator.java
│ ├── NextInorderSuccessorOfTwoTree.java
│ ├── NodesAtDistanceK.java
│ ├── NodesWithNoSibling.java
│ ├── PathSum.java
│ ├── PopulateInOrderSuccessor.java
│ ├── PrintPostOrderFromPreOrderInOrder.java
│ ├── PrintTwoBSTInSortedForm.java
│ ├── RedBlackTree.java
│ ├── RootToLeafToSum.java
│ ├── SameTree.java
│ ├── SegmentTree.java
│ ├── SegmentTreeMinimumRangeQuery.java
│ ├── SerializeDeserializeBinaryTree.java
│ ├── SinkNegativeToBottom.java
│ ├── SizeOfBinaryTree.java
│ ├── SortedArrayToBST.java
│ ├── SortedOrderPrintCompleteTreeArray.java
│ ├── SuccinctTree.java
│ ├── SumTree.java
│ ├── TreeIsomorphism.java
│ ├── TreeTraversalInSpiralOrder.java
│ ├── TreeTraversalLevelByLevel.java
│ ├── TreeTraversals.java
│ ├── UpsidedownBinaryTree.java
│ ├── VertexCoverBinaryTreeDP.java
│ ├── VerticalOrder.java
│ └── VerticalTreePrinting.java
└── test
└── com
└── interview
├── TestUtil.java
├── array
├── AdditiveNumberTest.java
├── ArrayAdditionTest.java
├── MaximumMinimumArrangementTest.java
├── MeetingRoomsTest.java
├── MultiplyAllFieldsExceptOwnPositionTest.java
├── NumberOfTriangledInUnsortedArrayTest.java
└── ThreeSumSmallerThanTargetTest.java
├── bits
├── CountingBitsTillNumTest.java
└── MaxProductWordLengthTest.java
├── dynamic
├── DecodeWaysTest.java
└── PalindromePartitionTest.java
├── graph
├── CourseScheduleTest.java
├── TravelingSalesmanHeldKarpTest.java
└── WallsAndGatesTest.java
├── linklist
└── DeleteDuplicateNodesTest.java
├── misc
└── IntegerListParserTest.java
├── multiarray
└── Mutable2DSumRangeQueryTest.java
├── number
├── AllStrobogrammaticNumberTest.java
└── BasicCalculatorTest.java
├── recursion
└── RestoreIPAddressesTest.java
├── string
├── LongestSubstringWithKDistinctCharactersTest.java
├── PalindromePairTest.java
├── StringEncoderDecoderTest.java
├── ValidPalindromeTest.java
└── ValidWordAbbreviationTest.java
├── suffixprefix
└── TrieTest.java
└── tree
├── KClosestValueInBinaryTreeTest.java
└── VerticalOrderTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | interview.iml
2 | interview.ipr
3 | interview.iws
4 | build/
5 | .gradle/
6 | .classpath
7 | .project
8 | .settings/
9 | /bin/
10 | /out
11 | .DS_Store
12 | python/graph/__pycache__/
13 | python/.idea
14 | target/
15 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/C++/Arrays/Trapping the rain water.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | int trapped_water(int array[],int size){
5 | int amount = 0;
6 | int left[size],right[size];
7 | left[0] = array[0]; right[size-1] = array[size-1];
8 | for(int i = 1; i < size; i++){
9 | left[i] = max(left[i-1],array[i]);
10 | }
11 | for(int i = size-2; i >=0; i--){
12 | right[i] = max(right[i+1],array[i]);
13 | }
14 | for(int i = 0 ; i < size;i++){
15 | amount += min(left[i],right[i]) - array[i];
16 | }
17 | return amount;
18 | }
19 |
20 | int main(){
21 | int array[] = {1,0,3,4,5,0,5,7,7,8,9,0};
22 | int size = sizeof(array) / sizeof(int);
23 | cout << trapped_water(array,size);
24 | return 0;
25 | }
26 |
--------------------------------------------------------------------------------
/C++/Bit Manipulation/Checking Whether K-th Bit is Set or Not.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | int main(){
4 | int n,k;
5 | cout << "Enter the number and the value of K : ";
6 | cin >> n >> k;
7 | int mask = 1 << (k-1);
8 | if(n & mask){
9 | cout << "Yes K-th bit is set" << endl;
10 | }
11 | else{
12 | cout << "No K-th bit is not set" << endl;
13 | }
14 | return 0;
15 | }
16 |
--------------------------------------------------------------------------------
/C++/Bit Manipulation/Clearing the K-th bit of a number.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | int main(){
4 | int n,k,mask;
5 | cout << "Enter the number and the value of K : ";
6 | cin >> n >> k;
7 | mask = ~(1 << (k-1));
8 | n = n&mask;
9 | cout << "The number after clearing the K-th bit is : " << n << endl;
10 | return 0;
11 | }
12 |
--------------------------------------------------------------------------------
/C++/Bit Manipulation/Setting the K-th bit of a number.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | int main(){
4 | int n,k;
5 | cout << "Enter the number and the value of K :";
6 | cin >> n >> k;
7 | int mask = 1 << (k - 1);
8 | n = n | mask;
9 | cout << "The number after setting the K-th bit is:" << n;
10 | return 0;
11 | }
12 |
--------------------------------------------------------------------------------
/C++/Bit Manipulation/Toggling Rightmost Set Bit of a number.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | int main(){
4 | int n;
5 | cout << "Enter the number : ";
6 | cin >> n ;
7 | n = n & (n-1);
8 | cout << "The number after toggling right most set bit : " << n << endl;
9 | return 0;
10 | }
11 |
--------------------------------------------------------------------------------
/C++/Bit Manipulation/Toggling the K-th bit of a number.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | int main(){
4 | int n,k,mask;
5 | cout << "Enter the number and the value of K : ";
6 | cin >> n >> k;
7 | mask = 1 << (k-1);
8 | n = n ^ mask;
9 | cout << "The number after toggling the K-th bit is : " << n << endl;
10 | return 0;
11 | }
12 |
--------------------------------------------------------------------------------
/C++/Dynamic Programming/Edit Distance.cpp:
--------------------------------------------------------------------------------
1 | int editDistance(string s1, string s2){
2 | int m = s1.length();
3 | int n = s2.length();
4 | int dp[m+1][n+1];
5 | for (int i = 0; i <= m; i++) {
6 | dp[i][0] = i;
7 | }
8 | for (int j = 0; j <= n; j++) {
9 | dp[0][j] = j;
10 | }
11 |
12 | for (int i = 1; i <= m; i++) {
13 | for (int j = 1; j <= n; j++) {
14 | if (s1[i-1] == s2[j-1]) dp[i][j] = dp[i-1][j-1];
15 | else dp[i][j] = 1 + min(min(dp[i][j-1],dp[i-1][j]),dp[i-1][j-1]);
16 | }
17 | }
18 | return dp[m][n];
19 | }
20 |
--------------------------------------------------------------------------------
/C++/Dynamic Programming/Longest Common Subsequence.cpp:
--------------------------------------------------------------------------------
1 | int lcs(string x,string y){
2 | int m = x.size(),n = y.size();
3 | int dp[m+1][n+1];
4 | for(int i=0;i<=m;i++){
5 | dp[i][0] = 0;
6 | }
7 | for(int j=0;j<=m;j++){
8 | dp[0][j] = 0;
9 | }
10 | for(int i=1;i<=m;i++){
11 | for(int j=1;j<=n;j++){
12 | if(x[i-1] == y[j-1]){
13 | dp[i][j] = dp[i-1][j-1]+1;
14 | }
15 | else{
16 | dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
17 | }
18 | }
19 | }
20 | return dp[m][n];
21 | }
22 |
--------------------------------------------------------------------------------
/C++/Dynamic Programming/Longest Common Substring.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | int longest_common_substring(string x,string y){
5 | int m = x.size();
6 | int n = y.size();
7 | int lcs[m+1][n+1];
8 | for(int i = 0 ; i < m; i++){
9 | lcs[i][0] = 0;
10 | }
11 | for(int j = 0; j < n; j++){
12 | lcs[0][j] = 0;
13 | }
14 | for(int i = 1; i <= m; i++){
15 | for(int j = 1; j <=n; j++){
16 | if(x[i-1] == y[j-1]){
17 | lcs[i][j] = 1 + lcs[i-1][j-1];
18 | }
19 | else{
20 | lcs[i][j] = 0;
21 | }
22 | }
23 | }
24 | return lcs[m][n];
25 | }
26 | int main(){
27 | string x,y;
28 | cin >> x >> y;
29 | cout << longest_common_substring(x,y);
30 | return 0;
31 | }
--------------------------------------------------------------------------------
/C++/Dynamic Programming/Longest Increasing Subsequence.cpp:
--------------------------------------------------------------------------------
1 | int lis(int array[],int n){
2 | int dp[n],lis_value = -1;
3 | for(int i=0;i array[j] and dp[i] < dp[j]+1){
9 | dp[i] = dp[j] + 1;
10 | }
11 | }
12 | }
13 | for(int i=0;i
2 | using namespace std;
3 | int longest_palindromic_subsequence(string str){
4 | int table[str.size()][str.size()];
5 | for(int i = 0 ; i < str.size(); i++){
6 | table[i][i] = 1;
7 | }
8 | for(int l = 1 ; l < str.size() ; l++){
9 | int i = 0, j = l;
10 | while(j != str.size()){
11 | if(str[i] == str[j]){
12 | table[i][j] = 2 + table[i+1][j-1];
13 | }
14 | else{
15 | table[i][j] = max(table[i+1][j],table[i][j-1]);
16 | }
17 | i++;j++;
18 | }
19 | }
20 | return table[0][str.size()-1];
21 | }
22 | int main(){
23 | string str;
24 | cin >> str;
25 | cout << longest_palindromic_subsequence(str);
26 | return 0;
27 | }
--------------------------------------------------------------------------------
/C++/Dynamic Programming/Matrix Chain Multiplication.cpp:
--------------------------------------------------------------------------------
1 | int mcm(int p[], int n){
2 | int m[n][n];
3 | int i, j, k, L, q;
4 | for (i = 1; i < n; i++)
5 | m[i][i] = 0;
6 | for (L=2; L
2 | #include
3 | using namespace std;
4 |
5 | void floydWarshall(vector> &graph){
6 | for (int k=0; k> graph;
17 | int v,e,src,des,weight;
18 | cin >> v >> e;
19 | graph.resize(v,vector(v,0));
20 | while(e--){
21 | cin >> src >> des >> weight;
22 | graph[src][des] = weight;
23 | }
24 | floydWarshall(graph);
25 | for(int i=0;i
2 | #include
3 | #include
4 | #include
5 | using namespace std;
6 | void breadth_first_search(vector> graph,int src){
7 | vectorvisited(graph.size(),false);
8 | queueQ;
9 | Q.push(src);
10 | visited[src] = true;
11 | while(!Q.empty()){
12 | int vertex = Q.front(); Q.pop();
13 | cout << vertex << " ";
14 | for(list::iterator itr = graph[vertex].begin();itr!=graph[vertex].end();itr++){
15 | if(!visited[*itr])
16 | Q.push(*itr);
17 | visited[*itr] = true;
18 | }
19 | }
20 | }
21 | int main(){
22 | vector> graph;
23 | int v,e,src,des;
24 | cin >> v >> e;
25 | graph.resize(v);
26 | while(e--){
27 | cin >> src >> des;
28 | graph[src].push_back(des);
29 | graph[des].push_back(src);
30 | }
31 | cin >> src;
32 | breadth_first_search(graph,src);
33 | return 0;
34 | }
35 |
--------------------------------------------------------------------------------
/C++/Graph Algorithms/Connected Components Algorithm DFS.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | using namespace std;
5 |
6 | void connectedComponentsDFS(vector> graph,int src,vector &visited){
7 | if(!visited[src]){
8 | visited[src] = true;
9 | for(list::iterator itr = graph[src].begin();itr != graph[src].end();itr++){
10 | connectedComponentsDFS(graph,*itr,visited);
11 | }
12 | }
13 | }
14 |
15 | int connectedComponents(vector> graph){
16 | int components = 0;
17 | vector visited(graph.size(),false);
18 | for(int src = 0; src < graph.size();src++){
19 | if(!visited[src]){
20 | components++;
21 | connectedComponentsDFS(graph,src,visited);
22 | }
23 | }
24 | return components;
25 | }
26 |
27 | int main(){
28 | vector> graph;
29 | int v,e,src,des;
30 | cin >> v >> e;
31 | graph.resize(v);
32 | while(e--){
33 | cin >> src >> des;
34 | graph[src].push_back(des);
35 | }
36 | cout << connectedComponents(graph);
37 | return 0;
38 | }
39 |
40 |
--------------------------------------------------------------------------------
/C++/Graph Algorithms/Depth First Search.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | using namespace std;
6 | void depth_first_search(vector> graph,int src){
7 | vectorvisited(graph.size(),false);
8 | stackS;
9 | S.push(src);
10 | visited[src] = true;
11 | while(!S.empty()){
12 | int vertex = S.top(); S.pop();
13 | cout << vertex << " ";
14 | for(list::iterator itr = graph[vertex].begin();itr!=graph[vertex].end();itr++){
15 | if(!visited[*itr])
16 | S.push(*itr);
17 | visited[*itr] = true;
18 | }
19 | }
20 | }
21 | int main(){
22 | vector> graph;
23 | int v,e,src,des;
24 | cin >> v >> e;
25 | graph.resize(v);
26 | while(e--){
27 | cin >> src >> des;
28 | graph[src].push_back(des);
29 | graph[des].push_back(src);
30 | }
31 | cin >> src;
32 | depth_first_search(graph,src);
33 | return 0;
34 | }
35 |
--------------------------------------------------------------------------------
/C++/Graph Algorithms/Recursive Depth First Search.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | using namespace std;
5 | void depth_first_search(vector> graph,int src,vector &visited){
6 | if(!visited[src]){
7 | cout << src << " ";
8 | visited[src] = true;
9 | for(list::iterator itr = graph[src].begin();itr != graph[src].end();itr++){
10 | depth_first_search(graph,*itr,visited);
11 | }
12 | }
13 | }
14 | int main(){
15 | vector> graph;
16 | vector visited;
17 | int v,e,src,des;
18 | cin >> v >> e;
19 | graph.resize(v);
20 | visited.resize(v,false);
21 | while(e--){
22 | cin >> src >> des;
23 | graph[src].push_back(des);
24 | }
25 | cin >> src;
26 | depth_first_search(graph,src,visited);
27 | return 0;
28 | }
29 |
--------------------------------------------------------------------------------
/C++/Graph Algorithms/Topological Sorting.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | using namespace std;
5 |
6 | void topologicalSortDFS(vector> graph,int src,vector &visited,list &topologicalSortedList){
7 | if(!visited[src]){
8 | visited[src] = true;
9 | for(list::iterator itr = graph[src].begin();itr != graph[src].end();itr++){
10 | topologicalSortDFS(graph,*itr,visited,topologicalSortedList);
11 | }
12 | topologicalSortedList.push_front(src);
13 | }
14 | }
15 |
16 | list topologicalSort(vector> graph){
17 | list topologicalSortedList;
18 | vector visited(graph.size(),false);
19 | for(int src = 0; src < graph.size();src++){
20 | topologicalSortDFS(graph,src,visited,topologicalSortedList);
21 | }
22 | return topologicalSortedList;
23 | }
24 |
25 | int main(){
26 | vector> graph;
27 | int v,e,src,des;
28 | cin >> v >> e;
29 | graph.resize(v);
30 | while(e--){
31 | cin >> src >> des;
32 | graph[src].push_back(des);
33 | }
34 | list topologicalSortedList = topologicalSort(graph);
35 | for(list::iterator itr = topologicalSortedList.begin();itr!=topologicalSortedList.end();itr++){
36 | cout << *itr << " ";
37 | }
38 | return 0;
39 | }
40 |
--------------------------------------------------------------------------------
/C++/Heaps - Priority Queues/K-th Largest element of the stream.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std;
4 |
5 | int main(){
6 | int n,k;
7 | priority_queue,greater>Q;
8 | cout << "Enter the the value of K : ";
9 | cin >> k;
10 | while(cin >> n){
11 | cout << k << "-th largest element of the stream : ";
12 | if(Q.size() < k){
13 | Q.push(n);
14 | if(Q.size() == k){
15 | cout << Q.top() 3<< endl;
16 | }
17 | else{
18 | cout << "NULL" << endl;
19 | }
20 | }
21 | else{
22 | if(Q.top() < n){
23 | Q.pop();
24 | Q.push(n);
25 | }
26 | cout << Q.top() << endl;
27 | }
28 | cout << "Enter next element of the stream : ";
29 | }
30 | return 0;
31 | }
32 |
--------------------------------------------------------------------------------
/C++/Linked List/Reverse a linked list recursively.cpp:
--------------------------------------------------------------------------------
1 | void reverse_list(list_node *head){
2 | list_node *
3 | }
4 |
--------------------------------------------------------------------------------
/C++/Number Theory Algorithms/Divisors.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std;
4 | set generateDivisors(long long int num){
5 | set divisors;
6 | for(int i = 1 ; i*i <= num; i++ ){
7 | if(num % i == 0){
8 | divisors.insert(i);
9 | if( i != num/i ){
10 | divisors.insert(num/i);
11 | }
12 | }
13 | }
14 | return divisors;
15 | }
16 | int main(){
17 | set d = generateDivisors(23);
18 | for(int x : d){
19 | cout << x << " ";
20 | }
21 | return 0;
22 | }
23 |
--------------------------------------------------------------------------------
/C++/Number Theory Algorithms/Sieve of Eratosthenes.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | using namespace std;
5 |
6 | const int MAX = 1000*1000;
7 | const int LMT = 1000;
8 |
9 | vector prime(MAX+1,true);
10 |
11 | int seiveEratosthenes(){
12 | prime[0] = prime[1] = false;
13 | for(int i = 2; i <= LMT; i++){
14 | if(prime[i]){
15 | for(int j = i + i; j <= MAX ; j += i){
16 | prime[j] = false;
17 | }
18 | }
19 | }
20 | return count_if(prime.begin(),prime.end(),[](bool p){ return p == true;});
21 | }
22 | int main(){
23 | cout << seiveEratosthenes();
24 | return 0;
25 | }
26 |
--------------------------------------------------------------------------------
/C++/Recursion/Partition of array on the pivot.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | void partition(int array[],int low,int high){
4 | int i = low-1, pivot = array[high-1];
5 | for(int j = low ; j < high ; j++){
6 | if(array[j] <= pivot){
7 | i++;
8 | swap(array[i],array[j]);
9 | }
10 | }
11 | swap(array[i+1],array[high-1]);
12 | }
13 | int main(){
14 | int n;
15 | cin >> n;
16 | int array[n];
17 | partition(array,0,n);
18 | return 0;
19 | }
20 |
--------------------------------------------------------------------------------
/C++/Recursion/Permutation of a string.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | void permutation(char str[],int k,int n){
5 | if(k == n){
6 | for(int j = 0; j < n; j++){
7 | cout << str[j];
8 | }
9 | cout << endl;
10 | }
11 | else{
12 | for(int i = k ; i < n; i++){
13 | swap(str[i],str[k]);
14 | permutation(str,k+1,n);
15 | swap(str[i],str[k]);
16 | }
17 | }
18 | }
19 | int main(){
20 | char str[] = {'A','B','C','D'};
21 | permutation(str,0,4);
22 | return 0;
23 | }
24 |
--------------------------------------------------------------------------------
/C++/Segment Tree/Segment Tree.cpp:
--------------------------------------------------------------------------------
1 | void buildTree (int tree[],int array[], int index, int low, int high) {
2 | if (low == high)
3 | tree[index] = array[low];
4 | else {
5 | int mid = (low + high) >> 1;
6 | buildTree (tree,array, index*2, low, mid);
7 | buildTree (tree,array, index*2+1, mid+1, high);
8 | tree[index] = tree[index*2] + tree[index*2+1];
9 | }
10 | }
11 | int rangeQuery (int tree[],int index, int low, int high, int l, int r) {
12 | if (l > r)
13 | return 0;
14 | if (l == low && r == high)
15 | return tree[index];
16 | int mid = (low + high) >> 1;
17 | return rangeQuery (tree,index*2, low, mid, l, min(r,mid))
18 | + rangeQuery (tree,index*2+1, mid+1, high, max(l,mid+1), r);
19 | }
20 | void updateQuery (int tree[],int index, int low, int high, int pos, int delta) {
21 | if (low == high)
22 | tree[index] = delta;
23 | else {
24 | int mid = (low + high) >> 1;
25 | if (pos <= mid)
26 | updateQuery (tree,index*2, low, mid, pos, delta);
27 | else
28 | updateQuery (tree,index*2+1, mid+1, high, pos, delta);
29 | tree[index] = tree[index*2] + tree[index*2+1];
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/C++/String Algorithms/KMP.cpp:
--------------------------------------------------------------------------------
1 | vector computePrefix(string pat){
2 | int m = pat.size();
3 | vector longestPrefix(m);
4 | for(int i = 1, k = 0; i < m; i++){
5 | while(k > 0 && pat[k] != pat[i]){
6 | k = longestPrefix[k - 1];
7 | }
8 | if(pat[i] == pat[k]){
9 | longestPrefix[i] = ++k;
10 | }
11 | else{
12 | longestPrefix[i] = k;
13 | }
14 | }
15 | return longestPrefix;
16 | }
17 | void KMP(string str,string pat){
18 | int n = str.size();
19 | int m = pat.size();
20 | vector longestPrefix = computePrefix(pat);
21 | for(int i = 0, k = 0; i < n; i++){
22 | while(k > 0 && pat[k] != str[i]){
23 | k = longestPrefix[k - 1];
24 | }
25 | if(str[i] == pat[k]){
26 | k++;
27 | }
28 | if(k == m){
29 | cout << i - m + 1 << "\n";
30 | k = longestPrefix[k - 1];
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/C++/String Algorithms/Trie.cpp:
--------------------------------------------------------------------------------
1 | struct Trie {
2 | Trie* child[26];
3 | bool isLeaf;
4 |
5 | Trie() {
6 | memset(child, 0, sizeof(child));
7 | isLeaf = 0;
8 | }
9 |
10 | void pushWord(char *str) {
11 | if(*str == '\0')
12 | isLeaf = 1;
13 | else {
14 | int cur = *str - 'a';
15 | if(child[cur] == 0 )
16 | child[cur] = new Trie();
17 | child[cur]->pushWord(str+1);
18 | }
19 | }
20 |
21 | bool wordExist(char* str) {
22 | if(*str == '\0')
23 | return isLeaf;
24 |
25 | int cur = *str - 'a';
26 | if(child[cur] == 0 )
27 | return false;
28 |
29 | return child[cur]->wordExist(str+1);
30 | }
31 |
32 | bool prefixExist(char* str) {
33 | if(*str == '\0')
34 | return true;
35 |
36 | int cur = *str - 'a';
37 | if(child[cur] == 0 )
38 | return false;
39 |
40 | return child[cur]->prefixExist(str+1);
41 | }
42 | };
43 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 | apply plugin: 'idea'
3 | apply plugin: 'eclipse'
4 | apply plugin: "jacoco"
5 |
6 | sourceCompatibility = '1.8'
7 | targetCompatibility = '1.8'
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | testCompile 'junit:junit:4.12'
15 | }
16 |
17 | sourceSets {
18 | main {
19 | java {
20 | srcDir 'src'
21 | }
22 | }
23 |
24 | test {
25 | java {
26 | srcDir 'test'
27 | }
28 | }
29 | }
30 |
31 | jacocoTestReport {
32 | reports {
33 | xml.enabled false
34 | csv.enabled false
35 | html.destination "${buildDir}/jacocoHtml"
36 | }
37 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mission-peace/interview/94be5deb0c0df30ade2a569cf3056b7cc1e012f4/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Apr 02 16:59:09 PDT 2016
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-bin.zip
7 |
--------------------------------------------------------------------------------
/python/array/arrayaddition.py:
--------------------------------------------------------------------------------
1 | def add(arr1, arr2):
2 |
3 | l = max(len(arr1), len(arr2))
4 | result = [0 for j in range(l)]
5 | c = 0
6 | i = len(arr1) - 1
7 | j = len(arr2) - 1
8 | r = 0
9 | l -= 1
10 |
11 | while i >= 0 and j >= 0:
12 | r = arr1[i] + arr2[j] + c
13 | i -= 1
14 | j -= 1
15 | c = r // 10
16 | result[l] = r % 10
17 | l -= 1
18 |
19 | while i >= 0:
20 | r = arr1[i] + c
21 | i -= 1
22 | c = r // 10
23 | result[l] = r % 10
24 | l -= 1
25 |
26 | while j >= 0:
27 | r = arr1[j] + c
28 | j -= 1
29 | c = r // 10
30 | result[l] = r % 10
31 | l -= 1
32 |
33 | if c != 0:
34 | new_result = [0 for j in range(len(result) + 1)]
35 | t = len(new_result) - 1
36 | while t > 0:
37 | new_result[t] = result[t - 1]
38 | t -= 1
39 | new_result[0] = c
40 | return new_result
41 | return result
42 |
43 | arr1 = [9, 9, 9, 9, 9, 9, 9]
44 | arr2 = [1, 6, 8, 2, 6, 7]
45 | result = add(arr1, arr2)
46 | print(result)
47 |
--------------------------------------------------------------------------------
/python/array/commonthreesortedarray.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/find-common-elements-three-sorted-arrays/
2 |
3 | def common_elements(input1, input2, input3):
4 | result = []
5 | i = 0
6 | j = 0
7 | k = 0
8 | while i < len(input1) and j < len(input2) and k < len(input3):
9 | if input1[i] == input2[j] and input2[j] == input3[k]:
10 | result.append(input1[i])
11 | i = i + 1
12 | j = j + 1
13 | k = k + 1
14 | elif input1[i] < input2[j]:
15 | i = i + 1
16 | elif input2[j] < input3[k]:
17 | j = j + 1
18 | else:
19 | k = k + 1
20 | return result
21 |
22 | if __name__ == '__main__':
23 | input1 = [1, 5, 10, 20, 40, 80]
24 | input2 = [6, 7, 20, 80, 100]
25 | input3 = [3, 4, 15, 20, 30, 70, 80, 120]
26 |
27 | print(common_elements(input1, input2, input3))
28 |
--------------------------------------------------------------------------------
/python/array/countinversionofsize3.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/count-inversions-of-size-three-in-a-give-array/
2 |
3 | def find_inversions(input):
4 | inversion = 0
5 | for i in range(1, len(input) - 1):
6 | larger = 0
7 | for k in range(0, i):
8 | if input[k] > input[i]:
9 | larger = larger + 1
10 | smaller = 0
11 | for k in range(i+1, len(input)):
12 | if input[k] < input[i]:
13 | smaller = smaller + 1
14 |
15 | inversion += larger*smaller
16 | return inversion
17 |
18 | if __name__ == '__main__':
19 | input = [9, 6, 4, 5, 8]
20 | print(find_inversions(input))
21 |
22 |
--------------------------------------------------------------------------------
/python/array/flip0smaximum1s.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/
2 |
3 | def flip_0s_to_maximize_consecutive_1s(input, flips_allowed):
4 | window_start = 0
5 | count_zero = 0
6 | result = 0
7 | for i in range(len(input)):
8 | if input[i] == 1:
9 | result = max(result, i - window_start + 1)
10 | else:
11 | if count_zero < flips_allowed:
12 | count_zero = count_zero + 1
13 | result = max(result, i - window_start + 1)
14 | else:
15 | while True:
16 | if input[window_start] == 0:
17 | window_start = window_start + 1
18 | break
19 | window_start = window_start + 1
20 | return result
21 |
22 | if __name__ == '__main__':
23 | input = [0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1]
24 | print(flip_0s_to_maximize_consecutive_1s(input, 1))
25 |
--------------------------------------------------------------------------------
/python/array/longestsamesumspan.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/longest-span-sum-two-binary-arrays/
2 | # java code https://github.com/mission-peace/interview/blob/master/src/com/interview/array/LongestSameSumSpan.java
3 |
4 | def longest_span(input1, input2):
5 | if len(input1) != len(input2):
6 | raise ValueError;
7 |
8 | diff = {}
9 | prefix1 = 0
10 | prefix2 = 0
11 | max_span = 0
12 | diff[0] = -1
13 | for i in range(len(input1)):
14 | prefix1 += input1[i]
15 | prefix2 += input2[i]
16 | curr_diff = prefix1 - prefix2
17 | if curr_diff in diff:
18 | max_span = max(max_span, i - diff[curr_diff])
19 | else:
20 | diff[curr_diff] = i
21 | return max_span
22 |
23 | if __name__ == '__main__':
24 | input1 = [1, 0, 0, 1, 1, 0]
25 | input2 = [0, 1, 1, 0, 1, 1]
26 |
27 | print(longest_span(input1, input2))
28 |
29 |
30 |
--------------------------------------------------------------------------------
/python/array/maximumsumpathtwoarrays.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/maximum-sum-path-across-two-arrays/
2 |
3 | def max_sum(input1, input2):
4 | max_sum = 0
5 | i = 0
6 | j = 0
7 | sum1 = 0
8 | sum2 = 0
9 | while i < len(input1) and j < len(input2):
10 | if input1[i] == input2[j]:
11 | if sum1 > sum2:
12 | max_sum += sum1 + input1[i]
13 | else:
14 | max_sum += sum2 + input2[j]
15 | i = i + 1
16 | j = j + 1
17 | sum1 = 0
18 | sum2 = 0
19 | elif input1[i] < input2[j]:
20 | sum1 += input1[i]
21 | i = i + 1
22 | else:
23 | sum2 += input2[j]
24 | j = j + 1
25 |
26 | while i < len(input1):
27 | sum1 += input1[i]
28 | i = i + 1
29 |
30 | while j < len(input2):
31 | sum2 += input2[j]
32 | j = j + 1
33 |
34 | if sum1 > sum2:
35 | max_sum += sum1
36 | else:
37 | max_sum += sum2
38 |
39 | return max_sum
40 |
41 | if __name__ == '__main__':
42 | input1 = [2, 3, 7, 10, 12, 15, 30, 34]
43 | input2 = [1, 5, 7, 8, 10, 15, 16, 19]
44 |
45 | print(max_sum(input1, input2))
46 |
47 |
--------------------------------------------------------------------------------
/python/array/maxproductsubarray.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/maximum-product-subarray/
2 |
3 | def max_product(input):
4 | max_ending = 1
5 | min_ending = 1
6 | max_so_far = 1
7 | for i in input:
8 | if i > 0:
9 | max_ending = max_ending * i
10 | min_ending = min(min_ending*i, 1)
11 | elif i == 0:
12 | max_ending = 1
13 | min_ending = 1
14 | else:
15 | t = max_ending
16 | max_ending = max(min_ending*i, 1)
17 | min_ending = t * i
18 | if max_so_far < max_ending:
19 | max_so_far = max_ending
20 | return max_so_far
21 |
22 | if __name__ == '__main__':
23 | input = [-6,-3,8,-9,-1,-1,3,6,9,0,3,-1]
24 | print(max_product(input))
25 |
--------------------------------------------------------------------------------
/python/array/numberoftrianglesunsortedarray.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/find-number-of-triangles-possible/
2 |
3 | def number_of_triangles(input):
4 | input.sort()
5 | count = 0
6 | for i in range(len(input)-2):
7 | k = i + 2
8 | for j in range(i+1, len(input)):
9 | while k < len(input) and input[i] + input[j] > input[k]:
10 | k = k + 1
11 | count += k - j - 1
12 | return count
13 |
14 | if __name__ == '__main__':
15 | input = [15, 9, 8, 3, 4, 5, 6]
16 | print(number_of_triangles(input))
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/python/array/positiveandnegativealternativelymaintainingorder.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/
2 |
3 | def rearrange(input):
4 | for i in range (len(input)):
5 | if i%2 == 0 and input[i] >= 0:
6 | index_of_next_negative = find_next(input, i+1, False)
7 | if index_of_next_negative == -1:
8 | return
9 | else:
10 | right_rotate(input, i, index_of_next_negative)
11 | elif i % 2 != 0 and input[i] < 0:
12 | index_of_next_positive = find_next(input, i+1, True)
13 | if index_of_next_positive == -1:
14 | return
15 | else:
16 | right_rotate(input, i, index_of_next_positive)
17 |
18 | def find_next(input, start, isPositive):
19 | for i in range(start, len(input)):
20 | if (isPositive and input[i] >= 0) or (not isPositive and input[i] < 0):
21 | return i;
22 | return -1
23 |
24 | def right_rotate(input, start, end):
25 | t = input[end]
26 | for i in range(end, start -1, -1):
27 | input[i] = input[i-1]
28 | input[start] = t
29 |
30 | if __name__ == '__main__':
31 | input = [-5, -2, 5, 2, 4, 7, 1, 8, 0, -8];
32 | rearrange(input)
33 | print(input)
34 |
35 |
--------------------------------------------------------------------------------
/python/array/rearrangearrayperindex.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/rearrange-array-arrj-becomes-arri-j/
2 |
3 | def rearrange(input):
4 | for i in range(len(input)):
5 | input[i] += 1
6 |
7 | for i in range(len(input)):
8 | if input[i] > 0:
9 | rearrange_util(input, i)
10 |
11 | for i in range(len(input)):
12 | input[i] = -input[i] - 1
13 |
14 | def rearrange_util(input, start):
15 | i = start + 1
16 | v = input[start]
17 | while v > 0:
18 | t = input[v-1]
19 | input[v-1] = -i
20 | i = v
21 | v = t
22 |
23 | if __name__ == '__main__':
24 | input = [1, 2, 0, 5, 3, 4];
25 | rearrange(input)
26 | print(input)
27 |
--------------------------------------------------------------------------------
/python/array/reorderarraybyindex.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/reorder-a-array-according-to-given-indexes/
2 |
3 | def reorder(input, index):
4 | if len(input) != len(index):
5 | raise ValueError
6 | for i in range(len(index)):
7 | while index[i] != i:
8 | s_index = index[index[i]]
9 | s_val = input[index[i]]
10 |
11 | index[index[i]] = index[i]
12 | input[index[i]] = input[i]
13 |
14 | index[i] = s_index
15 | input[i] = s_val
16 |
17 | if __name__ == '__main__':
18 | input = [50, 40, 70, 60, 90]
19 | index = [3, 0, 4, 1, 2]
20 |
21 | reorder(input, index)
22 | print(input)
23 | print(index)
24 |
25 |
26 |
--------------------------------------------------------------------------------
/python/array/rotationwithmaxsum.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/find-maximum-value-of-sum-iarri-with-only-rotations-on-given-array-allowed/
2 |
3 | def max_sum(input):
4 | arr_sum = 0
5 | rotation_sum = 0
6 | for i in range(len(input)):
7 | arr_sum += input[i]
8 | rotation_sum += i*input[i]
9 |
10 | max_rotation_sum = rotation_sum
11 |
12 | for i in range(1, len(input)):
13 | rotation_sum += len(input)*input[i-1] - arr_sum
14 | max_rotation_sum = max(max_rotation_sum, rotation_sum)
15 |
16 | return max_rotation_sum
17 |
18 | if __name__ == '__main__':
19 | input = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
20 | print(max_sum(input))
21 |
--------------------------------------------------------------------------------
/python/array/smallestintegernotrepresentedbysubsetsum.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/find-smallest-value-represented-sum-subset-given-array/
2 |
3 | def find_smallest_integer(input):
4 | result = 1
5 | for i in range(len(input)):
6 | if input[i] <= result:
7 | result += input[i]
8 | else:
9 | break
10 | return result
11 |
12 | if __name__ == '__main__':
13 | input = [1, 2, 3, 8]
14 | print(find_smallest_integer(input))
15 |
--------------------------------------------------------------------------------
/python/array/tripletsumlessthantotal.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/
2 |
3 | def find_all_triplet(input, total):
4 | input.sort()
5 | result = 0
6 | for i in range(len(input) - 2):
7 | j = i + 1
8 | k = len(input) - 1
9 | while j < k:
10 | if input[i] + input[j] + input[k] >= total:
11 | k = k - 1
12 | else:
13 | result += k - j
14 | j = j + 1
15 | return result
16 |
17 |
18 | if __name__ == '__main__':
19 | input = [5, 1, 3, 4, 7]
20 | print(find_all_triplet(input, 12))
21 |
22 |
--------------------------------------------------------------------------------
/python/array/zigzagarrangement.py:
--------------------------------------------------------------------------------
1 | # http://www.geeksforgeeks.org/convert-array-into-zig-zag-fashion/
2 |
3 | def rearrange(input):
4 | is_less = True
5 | for i in range(len(input)-1):
6 | if is_less:
7 | if input[i] > input[i+1]:
8 | swap(input, i, i+1)
9 | else:
10 | if input[i] < input[i+1]:
11 | swap(input, i, i+1)
12 | is_less = not is_less
13 |
14 | def swap(input, i, j):
15 | t = input[i]
16 | input[i] = input[j]
17 | input[j] = t
18 |
19 | if __name__ == '__main__':
20 | input = [4, 3, 2, 6, 7, 1, 9]
21 | rearrange(input)
22 | print(input)
23 |
24 |
--------------------------------------------------------------------------------
/python/dynamic/count_num_binary_without_consec_1.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 |
5 | Given a positive integer N, count all the numbers from 1 to 2^N, whose binary representation does not have consecutive
6 | 1s.
7 |
8 | This is a simple application of fibonacci series.
9 |
10 | Video
11 | -----
12 |
13 | * https://www.youtube.com/watch?v=a9-NtLIs1Kk
14 |
15 | Complexity
16 | ----------
17 |
18 | * Runtime Complexity: O(n)
19 |
20 |
21 | Reference
22 | ---------
23 |
24 | * http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
25 | """
26 |
27 |
28 | def consec_one(num_n):
29 | f1 = f2 = 1
30 |
31 | for _ in range(num_n):
32 | f1, f2 = f1 + f2, f1
33 |
34 | return f1
35 |
36 | if __name__ == '__main__':
37 | assert 13 == consec_one(5)
38 |
--------------------------------------------------------------------------------
/python/dynamic/dice_throw_ways.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 |
5 | Given n dice each with m faces, numbered from 1 to m, find the number of ways to get sum X. X is the summation of values
6 | on each face when all the dice are thrown.
7 |
8 | Complexity
9 | ----------
10 |
11 | * Run time complexity: O(m * n * x) where m is number of faces, n is number of dice and x is given sum.
12 |
13 |
14 | References
15 | ----------
16 |
17 | * http://www.geeksforgeeks.org/dice-throw-problem/
18 | """
19 |
20 |
21 | def num_ways(faces, dices, sumX):
22 |
23 | T = [[0 for _ in range(sumX + 1)] for _ in range(dices + 1)]
24 |
25 | # For a single dice
26 | for face_value in range(1, faces + 1):
27 | if face_value <= sumX:
28 | T[1][face_value] = 1
29 |
30 | for dice in range(2, dices + 1):
31 | for partial_sum in range(1, sumX + 1):
32 | for face_value in range(1, faces + 1):
33 | if face_value < partial_sum:
34 | T[dice][partial_sum] += T[dice - 1][partial_sum - face_value]
35 |
36 | return T[dices][sumX]
37 |
38 |
39 | if __name__ == '__main__':
40 | assert 7 == num_ways(3, 3, 6)
41 |
--------------------------------------------------------------------------------
/python/dynamic/kth_ugly_number.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 |
5 | Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,
6 | shows the first 11 ugly numbers. By convention, 1 is included.
7 |
8 | Write a program to find the kth ugly number.
9 |
10 | Complexity
11 | ----------
12 |
13 | * Time Complexity O(n)
14 | * Space Complexity O(n)
15 |
16 | Reference
17 | ---------
18 | * http://www.geeksforgeeks.org/ugly-numbers/
19 | """
20 |
21 |
22 | def ugly_number(kth):
23 | ugly_factors = [1] # By convention 1 is included.
24 |
25 | factor_index = {
26 | 2: 0,
27 | 3: 0,
28 | 5: 0}
29 |
30 | for num in range(1, kth):
31 | minimal_factor = min(min(ugly_factors[factor_index[2]] * 2, ugly_factors[factor_index[3]] * 3),
32 | ugly_factors[factor_index[5]] * 5)
33 |
34 | ugly_factors.append(minimal_factor)
35 |
36 | for factor in [2, 3, 5]:
37 | if minimal_factor % factor == 0:
38 | factor_index[factor] += 1
39 |
40 | return ugly_factors[kth - 1]
41 |
42 | if __name__ == '__main__':
43 | assert 5832 == ugly_number(150)
44 |
--------------------------------------------------------------------------------
/python/dynamic/maximum_increasing_subsequence.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 |
5 | Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array
6 | such that the integers in the subsequence are in increasing order.
7 |
8 | Complexity
9 | ----------
10 |
11 | * Time Complexity: O(n^2)
12 | * Space Complexity: O(n)
13 |
14 | Video
15 | -----
16 |
17 | * https://youtu.be/99ssGWhLPUE
18 |
19 | Reference
20 | ---------
21 | * http://www.geeksforgeeks.org/dynamic-programming-set-14-maximum-sum-increasing-subsequence/
22 | """
23 |
24 |
25 | def maximum_sum_subsequence(sequence):
26 | sequence_length = len(sequence)
27 | T = [sequence[i] for i in range(sequence_length)]
28 |
29 | for index_i in range(1, sequence_length):
30 | for index_j in range(0, index_i):
31 | if sequence[index_j] < sequence[index_i]:
32 | T[index_i] = max(T[index_i], T[index_j] + sequence[index_i])
33 |
34 | return max(T)
35 |
36 | if __name__ == '__main__':
37 | sequence = [1, 101, 10, 2, 3, 100, 4]
38 | assert 111 == maximum_sum_subsequence(sequence)
39 |
--------------------------------------------------------------------------------
/python/dynamic/nth_fibonacci.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 |
5 | Given the number n, find the nth fibanacci number.
6 |
7 | The fibonacci series is 0, 1, 1, 2, 3 ...
8 |
9 | And follows the formula Fn = Fn-1 + Fn-2
10 |
11 | Complexity
12 | ----------
13 |
14 | * Recursive Solution: O(2^n)
15 | * Dynamic Programming: O(n)
16 |
17 | """
18 |
19 |
20 | def fibonacci_recursive(n):
21 | if n == 0 or n == 1:
22 | return n
23 |
24 | return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
25 |
26 |
27 | def fibonacci(n):
28 | n1, n2 = 0, 1
29 |
30 | if n == n1 or n == n2:
31 | return n
32 |
33 | for i in range(2, n + 1):
34 | n1, n2 = n2, n1 + n2
35 |
36 | return n2
37 |
38 | if __name__ == '__main__':
39 | assert 610 == fibonacci_recursive(15)
40 | assert 610 == fibonacci(15)
41 |
--------------------------------------------------------------------------------
/python/dynamic/num_bst.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 | Count number of binary search trees created for array of size n. The solution is the nth catalan number.
5 |
6 |
7 | Complexity
8 | ----------
9 | * Dynamic Programming: O(n^2)
10 | * Recursive Solution: O(2^n)
11 |
12 | Video
13 | -----
14 |
15 | * https://youtu.be/YDf982Lb84o
16 |
17 | Reference
18 | ---------
19 | * http://www.geeksforgeeks.org/program-nth-catalan-number/
20 | """
21 |
22 |
23 | def num_bst(num_nodes):
24 | T = [0 for _ in range(num_nodes + 1)]
25 | T[0] = 1
26 | T[1] = 1
27 |
28 | for node in range(2, num_nodes+1):
29 | for sub in range(0, node):
30 | T[node] += T[sub] * T[node - sub - 1]
31 |
32 | return T[num_nodes]
33 |
34 |
35 | def num_bst_recursive(num_nodes):
36 | if num_nodes == 0 or num_nodes == 1:
37 | return 1
38 |
39 | result = 0
40 |
41 | for root in range(1, num_nodes + 1):
42 | result += num_bst_recursive(root - 1) * num_bst_recursive(num_nodes - root)
43 |
44 | return result
45 |
46 |
47 | if __name__ == '__main__':
48 | assert 5 == num_bst(3)
49 | assert 5 == num_bst_recursive(3)
50 |
--------------------------------------------------------------------------------
/python/dynamic/num_paths_nm_matrix.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 |
5 | Count the number of Paths from 1,1 to N,M in an NxM matrix.
6 |
7 | Analysis
8 | --------
9 |
10 | * Dynamic Programing Solution: O(rows * cols)
11 | * Recursive: O(2^rows) if rows > cols else O(2^cols)
12 |
13 |
14 | References
15 | ----------
16 | * http://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
17 |
18 | """
19 |
20 |
21 | def num_paths_matrix(rows, cols):
22 | T = [[1 if row == 0 or col == 0 else 0 for row in range(cols)] for col in range(rows)]
23 | for row in range(1, rows):
24 | for col in range(1, cols):
25 | T[row][col] = T[row - 1][col] + T[row][col - 1]
26 | return T[rows - 1][cols - 1]
27 |
28 |
29 | def num_paths_matrix_recursive(rows, cols):
30 | if rows == 1 or cols == 1:
31 | return 1
32 | return num_paths_matrix(rows-1, cols) + num_paths_matrix(rows, cols - 1)
33 |
34 |
35 | if __name__ == '__main__':
36 | rows = 3
37 | cols = 3
38 | expected = 6
39 | assert expected == num_paths_matrix(rows, cols)
40 | assert expected == num_paths_matrix_recursive(rows, cols)
41 |
--------------------------------------------------------------------------------
/python/dynamic/num_trees_preorder.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 |
5 | Given the number of nodes N, in a pre-order sequence how many unique trees can be created? Number of tree is exactly
6 | same as number of unique BST create with array of size n. The solution is a catalan number.
7 |
8 | Complexity
9 | ----------
10 | * Dynamic Programming: O(n^2)
11 | * Recursive Solution: O(2^n)
12 |
13 | Video
14 | -----
15 | * https://youtu.be/RUB5ZPfKcnY
16 | """
17 |
18 |
19 | def num_trees(num_nodes):
20 | T = [0 for _ in range(num_nodes + 1)]
21 | T[0] = 1
22 | T[1] = 1
23 | for n in range(2, num_nodes + 1):
24 | for j in range(0, n):
25 | T[n] += T[j] * T[n - j - 1]
26 | return T[num_nodes]
27 |
28 |
29 | def num_trees_recursive(num_nodes):
30 | if num_nodes == 0 or num_nodes == 1:
31 | return 1
32 |
33 | result = 0
34 |
35 | for n in range(1, num_nodes + 1):
36 | result += num_trees_recursive(n - 1) * num_trees_recursive(num_nodes - n)
37 |
38 | return result
39 |
40 |
41 |
42 |
43 | if __name__ == '__main__':
44 | assert 5 == num_trees(3)
45 | assert 14 == num_trees(4)
46 | assert 42 == num_trees(5)
47 | assert 5 == num_trees_recursive(3)
48 | assert 14 == num_trees_recursive(4)
49 | assert 42 == num_trees_recursive(5)
50 |
--------------------------------------------------------------------------------
/python/graph/graphtraversal.py:
--------------------------------------------------------------------------------
1 | #doing BFS and DFS traversal of the graph
2 | # java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/GraphTraversal.java
3 |
4 | from graph import *
5 | import queue
6 |
7 | def dfs_util(v, visited):
8 | if v in visited:
9 | return
10 | visited.add(v)
11 | print(v)
12 | for vertex in v.adjacent_vertices:
13 | dfs_util(vertex, visited)
14 |
15 | def dfs(graph):
16 | visited = set()
17 | for id in graph.all_vertex:
18 | dfs_util(graph.all_vertex[id], visited)
19 |
20 | def bfs(graph):
21 | q = queue.Queue()
22 | visited = set()
23 | for vertex in graph.all_vertex.values():
24 | if vertex not in visited:
25 | q.put(vertex)
26 | visited.add(vertex)
27 | while not q.empty():
28 | v = q.get();
29 | print(v)
30 | for adj in v.adjacent_vertices:
31 | if adj not in visited:
32 | q.put(adj)
33 | visited.add(adj)
34 |
35 |
36 | if __name__ == '__main__':
37 | g = Graph(False)
38 | g.add_edge(1,2,10)
39 | g.add_edge(2,3,5)
40 | g.add_edge(1,4,6)
41 |
42 | dfs(g)
43 | bfs(g)
44 |
--------------------------------------------------------------------------------
/python/graph/kruskalmst.py:
--------------------------------------------------------------------------------
1 | # kruskal minimum spanning tree
2 | # java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/KruskalMST.java
3 |
4 | from disjointset import *
5 | from graph import *
6 |
7 | def get_key(edge):
8 | return edge.weight
9 |
10 | def minimum_spanning_tree(graph):
11 |
12 | disjoint_set = DisjointSet()
13 | sorted_edges = sorted(graph.all_edges, key = get_key)
14 | print(sorted_edges)
15 |
16 | for vertex in graph.all_vertex.values():
17 | disjoint_set.make_set(vertex.id)
18 |
19 | result_edge = []
20 |
21 | for edge in sorted_edges:
22 | root1 = disjoint_set.find_set(edge.vertex1.id)
23 | root2 = disjoint_set.find_set(edge.vertex2.id)
24 |
25 | if root1 == root2:
26 | continue
27 | else:
28 | result_edge.append(edge)
29 | disjoint_set.union(edge.vertex1.id, edge.vertex2.id)
30 |
31 | return result_edge
32 |
33 | if __name__ == '__main__':
34 | graph = Graph(False)
35 | graph.add_edge(1,3,1)
36 | graph.add_edge(1,2,4)
37 | graph.add_edge(2,4,2)
38 | graph.add_edge(2,5,1)
39 | graph.add_edge(2,6,3)
40 | graph.add_edge(3,4,5)
41 | graph.add_edge(3,7,8)
42 | graph.add_edge(4,7,2)
43 | graph.add_edge(6,5,2)
44 | graph.add_edge(6,4,3)
45 |
46 | result = minimum_spanning_tree(graph)
47 | for edge in result:
48 | print(edge)
49 |
50 |
--------------------------------------------------------------------------------
/python/graph/topologicalsort.py:
--------------------------------------------------------------------------------
1 | #topological sort
2 | # java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/TopologicalSort.java
3 |
4 | from graph import Graph
5 |
6 | def top_sort(graph):
7 | stack = []
8 | visited = set()
9 | for vertex in graph.all_vertex.values():
10 | if vertex in visited:
11 | continue
12 | top_sort_util(vertex, stack, visited)
13 | return stack
14 |
15 | def top_sort_util(vertex, stack, visited):
16 | visited.add(vertex)
17 | for adjacent in vertex.adjacent_vertices:
18 | if adjacent in visited:
19 | continue
20 | top_sort_util(adjacent, stack, visited)
21 | stack.append(vertex)
22 |
23 | if __name__ == '__main__':
24 | graph = Graph(True)
25 | graph.add_edge(1,3)
26 | graph.add_edge(1,2)
27 | graph.add_edge(3,4)
28 | graph.add_edge(5,6)
29 | graph.add_edge(6,3)
30 | graph.add_edge(3,8)
31 | graph.add_edge(8,11)
32 |
33 | stack = top_sort(graph)
34 |
35 | print(stack[::-1])
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/python/recursion/stringpermutation.py:
--------------------------------------------------------------------------------
1 | # string permutation in lexicographically order with repetition of characters in the string
2 |
3 | def permute(input):
4 | count_map = {}
5 | for ch in input:
6 | if ch in count_map.keys():
7 | count_map[ch] = count_map[ch] + 1
8 | else:
9 | count_map[ch] = 1
10 |
11 | keys = sorted(count_map)
12 | str = []
13 | count = []
14 | for key in keys:
15 | str.append(key)
16 | count.append(count_map[key])
17 | result = [0 for x in range(len(input))]
18 | permute_util(str, count, result, 0)
19 |
20 | def permute_util(str, count, result, level):
21 | if level == len(result):
22 | print(result)
23 | return
24 |
25 | for i in range(len(str)):
26 | if count[i] == 0:
27 | continue;
28 | result[level] = str[i]
29 | count[i] -= 1
30 | permute_util(str, count, result, level + 1)
31 | count[i] += 1
32 |
33 | if __name__ == '__main__':
34 | input = ['B', 'C', 'A', 'A']
35 | permute(input)
36 |
--------------------------------------------------------------------------------
/python/string/knuthmorrispratt.py:
--------------------------------------------------------------------------------
1 | # Knuth-Morris-Pratt algorithm
2 |
3 |
4 | # Compute temporary array to maintain size of suffix which is same as prefix
5 | # Time/space complexity is O(size of pattern)
6 | def compute_temporary_array(pattern):
7 | n = len(pattern)
8 | lsp = [0 for j in range(n)]
9 | index = 0
10 | i = 1
11 | while i < len(pattern):
12 | if pattern[i] == pattern[index]:
13 | lsp[i] = index + 1
14 | index += 1
15 | i += 1
16 | else:
17 | if index != 0:
18 | index = lsp[index - 1]
19 | else:
20 | lsp[i] = 0
21 | i += 1
22 | return lsp
23 |
24 |
25 | # KMP algorithm of pattern matching.
26 | def kmp(text, pattern):
27 | lsp = compute_temporary_array(pattern)
28 | i = 0
29 | j = 0
30 | while i < len(text) and j < len(pattern):
31 | if text[i] == pattern[j]:
32 | i += 1
33 | j += 1
34 | else:
35 | if j != 0:
36 | j = lsp[j - 1]
37 | else:
38 | i += 1
39 | if j == len(pattern):
40 | return True
41 | else:
42 | return False
43 |
44 | src = 'abcxabcdabcdabcy'
45 | sub_string = 'abcdabcy'
46 | result = kmp(src, sub_string)
47 | print(result)
48 |
49 |
50 |
--------------------------------------------------------------------------------
/python/tree/binary_tree.py:
--------------------------------------------------------------------------------
1 | from collections import namedtuple
2 |
3 | Color = namedtuple("Color", "RED BLACK")
4 |
5 |
6 | class Node:
7 | def __init__(self):
8 | self.color = None
9 | self.height = None
10 | self.lis = None
11 | self.data = None
12 | self.size = None
13 | self.next = None
14 | self.right = None
15 | self.left = None
16 |
17 | @staticmethod
18 | def newNode(data):
19 | n = Node()
20 | n.data = data
21 | n.lis = -1
22 | n.height = 1
23 | n.size = 1
24 | n.color = Color.RED
25 | return n
26 |
27 |
28 | class BinaryTree:
29 |
30 | def __init__(self):
31 | pass
32 |
33 | @staticmethod
34 | def add_head(data, head):
35 | temp_head = head
36 | n = Node.newNode(data)
37 |
38 | if head is None:
39 | head = n
40 | return head
41 |
42 | prev = None
43 |
44 | while head is not None:
45 | prev = head
46 | if head.data < data:
47 | head = head.right
48 | else:
49 | head = head.left
50 |
51 | if prev.data < data:
52 | prev.right = n
53 | else:
54 | prev.left = n
55 |
56 | return temp_head
57 |
--------------------------------------------------------------------------------
/python/tree/construct_tree_from_inorder_preorder.py:
--------------------------------------------------------------------------------
1 | from binary_tree import Node
2 |
3 |
4 | class ConstructTreeFromInorderPreOrder:
5 | def __init__(self):
6 | self.index = 0
7 |
8 | def _createTree(self, inorder, preorder, start, end):
9 | if start > end:
10 | return None
11 | i = 0
12 | for i in range(start, end + 1):
13 | if preorder[self.index] == inorder[i]:
14 | break
15 |
16 | node = Node.newNode(preorder[self.index])
17 | self.index += 1
18 | node.left = self._createTree(inorder, preorder, start, i - 1)
19 | node.right = self._createTree(inorder, preorder, i + 1, end)
20 | return node
21 |
22 | def createTree(self, inorder, preorder):
23 | return self._createTree(inorder, preorder, 0, len(inorder) - 1)
24 |
--------------------------------------------------------------------------------
/python/tree/max_depth_binary_tree.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | =================
4 |
5 | Given a binary tree, write a program to find the maximum depth at any given node.
6 |
7 | For e.g, for this binary tree.
8 |
9 | 1
10 | / \
11 | 2 3
12 | / \
13 | 4 5
14 |
15 | The height at 1 is 3, and the height at 3 is 2.
16 |
17 | """
18 |
19 | class Node:
20 | def __init__(self, value):
21 | self.value = value
22 | self.left = None
23 | self.right = None
24 |
25 |
26 | n1 = Node(1)
27 | n2 = Node(2)
28 | n3 = Node(3)
29 | n4 = Node(4)
30 | n5 = Node(5)
31 |
32 | # construct the tree as given in the problem.
33 |
34 | n1.left = n2
35 | n1.right = n3
36 | n3.left = n4
37 | n3.right = n5
38 |
39 |
40 | def find_max_depth(n):
41 | if n is None:
42 | return 0
43 | left_height = find_max_depth(n.left)
44 | right_height = find_max_depth(n.right)
45 | if left_height > right_height:
46 | result = left_height + 1
47 | else:
48 | result = right_height + 1
49 | return result
50 |
51 |
52 | if __name__ == '__main__':
53 | assert 3 == find_max_depth(n1)
54 | assert 2 == find_max_depth(n3)
55 |
--------------------------------------------------------------------------------
/src/com/interview/array/CheckIfArrayElementsAreConsecutive.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/check-if-array-elements-are-consecutive/
5 | */
6 | public class CheckIfArrayElementsAreConsecutive {
7 |
8 | public boolean areConsecutive(int input[]){
9 | int min = Integer.MAX_VALUE;
10 | for(int i=0; i < input.length; i++){
11 | if(input[i] < min){
12 | min = input[i];
13 | }
14 | }
15 | for(int i=0; i < input.length; i++){
16 | if(Math.abs(input[i]) - min >= input.length){
17 | return false;
18 | }
19 | if(input[Math.abs(input[i]) - min] < 0){
20 | return false;
21 | }
22 | input[Math.abs(input[i]) - min] = -input[Math.abs(input[i]) - min];
23 | }
24 | for(int i=0; i < input.length ; i++){
25 | input[i] = Math.abs(input[i]);
26 | }
27 | return true;
28 | }
29 |
30 | public static void main(String args[]){
31 | int input[] = {76,78,76,77,73,74};
32 | CheckIfArrayElementsAreConsecutive cia = new CheckIfArrayElementsAreConsecutive();
33 | System.out.println(cia.areConsecutive(input));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/interview/array/CountInversionOfSize3.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * Date 12/29/15
5 | * @author Tushar Roy
6 | *
7 | * Given input array find number of inversions where i < j < k and input[i] > input[j] > input[k]
8 | *
9 | * http://www.geeksforgeeks.org/count-inversions-of-size-three-in-a-give-array/
10 | */
11 | public class CountInversionOfSize3 {
12 |
13 | /**
14 | * Time complexity of this method is O(n^2)
15 | * Space complexity is O(1)
16 | */
17 | public int findInversions(int input[]) {
18 | int inversion = 0;
19 | for (int i = 1; i < input.length - 1 ; i++) {
20 | int larger = 0;
21 | for (int k = 0; k < i; k++) {
22 | if (input[k] > input[i]) {
23 | larger++;
24 | }
25 | }
26 | int smaller = 0;
27 | for (int k = i+1; k < input.length; k++) {
28 | if (input[k] < input[i]) {
29 | smaller++;
30 | }
31 | }
32 | inversion += smaller*larger;
33 | }
34 | return inversion;
35 | }
36 |
37 | public static void main(String args[]) {
38 | int input[] = {9, 6, 4, 5, 8};
39 | CountInversionOfSize3 ci = new CountInversionOfSize3();
40 | System.out.print(ci.findInversions(input));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/interview/array/DuplicateNumberDetection.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * Date 03/04/2016
5 | * @author Tushar Roy
6 | *
7 | * Given an array of size n + 1 with elements from 1 to n. One element is duplicated mulitiple times.
8 | * Find that element in O(1) space. Array cannot be changed.
9 | *
10 | * Reference
11 | * https://leetcode.com/problems/find-the-duplicate-number/
12 | */
13 | public class DuplicateNumberDetection {
14 | public int findDuplicate(int[] nums) {
15 | if (nums.length == 0 || nums.length == 1) {
16 | return -1;
17 | }
18 |
19 | int slow = nums[0];
20 | int fast = nums[nums[0]];
21 | while (slow != fast) {
22 | slow = nums[slow];
23 | fast = nums[nums[fast]];
24 | }
25 | fast = 0;
26 | while (slow != fast) {
27 | slow = nums[slow];
28 | fast = nums[fast];
29 | }
30 |
31 | return fast;
32 | }
33 |
34 | public static void main(String args[]) {
35 | int[] input = {2,1,3,4,3};
36 | DuplicateNumberDetection dd = new DuplicateNumberDetection();
37 | System.out.println(dd.findDuplicate(input));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/array/DuplicateWithinkIndices.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * Write a function that determines whether a array contains duplicate
8 | * characters within k indices of each other
9 | */
10 | public class DuplicateWithinkIndices {
11 |
12 | public boolean duplicate(int arr[],int k){
13 | Set visited = new HashSet();
14 | for(int i=0; i < arr.length; i++){
15 | if(visited.contains(arr[i])){
16 | return true;
17 | }
18 | if(i >= k){
19 | visited.remove(arr[i-k]);
20 | }
21 | visited.add(arr[i]);
22 | }
23 | return false;
24 | }
25 |
26 | public static void main(String args[]){
27 | int arr[] = {1,2,3,11,2,5,6};
28 | DuplicateWithinkIndices dk = new DuplicateWithinkIndices();
29 | System.out.println(dk.duplicate(arr, 3));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/interview/array/FirstPositiveMissing.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * https://leetcode.com/problems/first-missing-positive/
5 | */
6 | public class FirstPositiveMissing {
7 | public int firstMissingPositive(int[] nums) {
8 | int startOfPositive = segregate(nums);
9 | for (int i = startOfPositive; i < nums.length; i++) {
10 | int index = Math.abs(nums[i]) + startOfPositive - 1;
11 | if (index < nums.length) {
12 | nums[index] = -Math.abs(nums[index]);
13 | }
14 | }
15 | for (int i = startOfPositive; i < nums.length; i++) {
16 | if (nums[i] > 0) {
17 | return i - startOfPositive + 1;
18 | }
19 | }
20 | return nums.length - startOfPositive + 1;
21 | }
22 |
23 | private int segregate(int[] nums) {
24 | int start = 0;
25 | int end = nums.length -1 ;
26 | while (start <= end) {
27 | if (nums[start] <= 0) {
28 | start++;
29 | } else if (nums[end] > 0) {
30 | end--;
31 | } else {
32 | swap(nums, start, end);
33 | }
34 | }
35 | return start;
36 | }
37 |
38 | private void swap(int[] nums, int start, int end) {
39 | int t = nums[start];
40 | nums[start] = nums[end];
41 | nums[end] = t;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/interview/array/LongestConsecutiveSubsequence.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Date 12/03/2016
8 | * @author Tushar Roy
9 | *
10 | * Find longest consecutive subsequence in unsorted array.
11 | *
12 | * Time complexity O(n)
13 | * Space complexity O(n)
14 | *
15 | * Reference
16 | * https://leetcode.com/problems/longest-consecutive-sequence/
17 | */
18 | public class LongestConsecutiveSubsequence {
19 | public int longestConsecutive(int[] nums) {
20 | Map map = new HashMap();
21 | int result = 1;
22 | for (int i : nums) {
23 | if (map.containsKey(i)) {
24 | continue;
25 | }
26 | int left = map.containsKey(i - 1) ? map.get(i - 1) : 0;
27 | int right = map.containsKey(i + 1) ? map.get(i + 1) : 0;
28 |
29 | int sum = left + right + 1;
30 | map.put(i, sum);
31 | result = Math.max(sum, result);
32 | map.put(i - left, sum);
33 | map.put(i + right, sum);
34 | }
35 | return result;
36 | }
37 |
38 | public static void main(String args[]) {
39 | LongestConsecutiveSubsequence lcs = new LongestConsecutiveSubsequence();
40 | int[] input = {100, 4, 200, 1, 3, 2};
41 | System.out.println(lcs.longestConsecutive(input));
42 | }
43 | }
--------------------------------------------------------------------------------
/src/com/interview/array/MaxRepeatingNumber.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/find-the-maximum-repeating-number-in-ok-time/
5 | * Given an array of size n, the array contains numbers in range from 0 to k-1
6 | * where k is a positive integer and k <= n.
7 | * Find the maximum repeating number in this array
8 | */
9 | public class MaxRepeatingNumber {
10 |
11 | public int maxRepeatingNumber(int arr[], int k){
12 | int len = k;
13 | for(int i=0; i < arr.length; i++){
14 | arr[arr[i]%len] += len;
15 | }
16 | int maxRepeating = 0;
17 | int maxRepeatingIndex =0;
18 | for(int i=0; i < len; i++){
19 | if(maxRepeating < arr[i]){
20 | maxRepeating = arr[i];
21 | maxRepeatingIndex = i;
22 | }
23 | }
24 | for(int i=0; i < len; i++){
25 | arr[i] = arr[i] % len;
26 | }
27 | return maxRepeatingIndex;
28 | }
29 |
30 | public static void main(String args[]){
31 | MaxRepeatingNumber mrn = new MaxRepeatingNumber();
32 | int arr[] = {2,2,1,3,1,2,0,3,0,0,0,4,5,4,4,4,4};
33 | System.out.println(mrn.maxRepeatingNumber(arr, 6));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/interview/array/MaximumMinimumArrangement.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * Date 04/16/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a sorted array of positive integers, rearrange the array alternately i.e first element should be maximum value,
8 | * second minimum value, third second max, fourth second min and so on.
9 | *
10 | * Time complexity O(n)
11 | * Space complexity O(1)
12 | *
13 | * http://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form/
14 | */
15 | public class MaximumMinimumArrangement {
16 |
17 | public void rearrange(int[] input) {
18 | for (int i = 0; i < input.length; i++) {
19 | int t = input[i];
20 | if (t < 0) {
21 | continue;
22 | }
23 | int i1 = i;
24 | while (true) {
25 | int j = i1 < input.length/2 ? 2 * i1 + 1 : (input.length - 1 - i1) * 2;
26 | if (j == i1) {
27 | break;
28 | }
29 | if (input[j] < 0) {
30 | break;
31 | }
32 | int t1 = input[j];
33 | input[j] = -t;
34 | t = t1;
35 | i1 = j;
36 | }
37 | }
38 |
39 | for (int i = 0; i < input.length; i++) {
40 | input[i] = Math.abs(input[i]);
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/interview/array/MoveAllZerosToEnd.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | public class MoveAllZerosToEnd {
4 |
5 | public void moveZeros(int arr[]){
6 | int slow =0;
7 | int fast =0;
8 | while(fast < arr.length){
9 | if(arr[fast] == 0){
10 | fast++;
11 | continue;
12 | }
13 | arr[slow] = arr[fast];
14 | slow++;
15 | fast++;
16 | }
17 | while(slow < arr.length){
18 | arr[slow++] = 0;
19 | }
20 | }
21 |
22 | public static void main(String args[]){
23 | MoveAllZerosToEnd maz = new MoveAllZerosToEnd();
24 | int arr[] = {0,0,1,2,0,5,6,7,0};
25 | maz.moveZeros(arr);
26 | for(int i=0; i < arr.length; i++){
27 | System.out.print(arr[i]);
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/interview/array/MultiplyAllFieldsExceptOwnPosition.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * https://leetcode.com/problems/product-of-array-except-self/
5 | */
6 | public class MultiplyAllFieldsExceptOwnPosition {
7 |
8 | public int[] multiply(int nums[]) {
9 | if (nums.length == 0) {
10 | return new int[0];
11 | }
12 | int[] output = new int[nums.length];
13 | output[0] = 1;
14 | for (int i = 1; i < nums.length; i++) {
15 | output[i] = output[i - 1] * nums[i - 1];
16 | }
17 |
18 | int mult = 1;
19 | for (int i = nums.length - 1; i >= 0; i--) {
20 | output[i] *= mult;
21 | mult *= nums[i];
22 | }
23 | return output;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/interview/array/NumberOfTrianglesInUnsortedArray.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * http://www.geeksforgeeks.org/find-number-of-triangles-possible/
7 | */
8 | public class NumberOfTrianglesInUnsortedArray {
9 |
10 | public int numberOfTriangles(int input[]){
11 | Arrays.sort(input);
12 |
13 | int count = 0;
14 | for(int i=0; i < input.length-2; i++){
15 | int k = i+2;
16 | for(int j=i+1; j < input.length; j++){
17 | while(k < input.length && input[i] + input[j] > input[k]){
18 | k++;
19 | }
20 | count += k - j -1;
21 | }
22 | }
23 | return count;
24 |
25 | }
26 |
27 | public static void main(String args[]){
28 | int input[] = {3, 4, 5, 6, 8, 9, 15};
29 | NumberOfTrianglesInUnsortedArray not = new NumberOfTrianglesInUnsortedArray();
30 | System.out.println(not.numberOfTriangles(input));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/array/RearrangeSuchThatArriBecomesArrArri.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/rearrange-given-array-place/
5 | */
6 | public class RearrangeSuchThatArriBecomesArrArri {
7 |
8 | public void rearrange(int arr[]){
9 | for(int i=0; i < arr.length; i++){
10 | int temp;
11 | if(arr[arr[i]] > arr.length-1){
12 | temp = arr[arr[i]]/arr.length-1;
13 | }else{
14 | temp = arr[arr[i]];
15 | }
16 | arr[i] = temp + arr.length*(arr[i]+1);
17 | }
18 |
19 | for(int i=0; i < arr.length;i++){
20 | arr[i] = arr[i] % arr.length;
21 | }
22 | }
23 |
24 | public static void main(String args[]){
25 | int arr[] = {4,2,0,1,3};
26 | RearrangeSuchThatArriBecomesArrArri rss = new RearrangeSuchThatArriBecomesArrArri();
27 | rss.rearrange(arr);
28 | for(int i=0; i < arr.length; i++){
29 | System.out.print(arr[i]);
30 | }
31 | }
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/src/com/interview/array/RepeatingAndMissingNumber.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/find-a-repeating-and-a-missing-number/
5 | */
6 | public class RepeatingAndMissingNumber {
7 |
8 | class Pair{
9 | int repeating;
10 | int missing;
11 | public String toString(){
12 | return repeating + " " + missing;
13 | }
14 | }
15 |
16 | public Pair findNumbers(int input[]){
17 | Pair p = new Pair();
18 | for(int i=0; i < input.length; i++){
19 | if(input[Math.abs(input[i])-1] < 0){
20 | p.repeating = Math.abs(input[i]);
21 | }else{
22 | input[Math.abs(input[i])-1] = -input[Math.abs(input[i])-1];
23 | }
24 | }
25 |
26 | for(int i=0; i < input.length; i++){
27 | if(input[i] < 0){
28 | input[i] = -input[i];
29 | }else{
30 | p.missing = i + 1;
31 | }
32 | }
33 | return p;
34 | }
35 |
36 | public static void main(String args[]){
37 | RepeatingAndMissingNumber rmn = new RepeatingAndMissingNumber();
38 | int input[] = {3,1,2,4,6,8,2,7};
39 | System.out.println(rmn.findNumbers(input));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/interview/array/RotationWithMaxSum.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * Date 12/30/2015
5 | * @author Tushar Roy
6 | *
7 | * Given an input array find which rotation will give max sum of i * arr[i]
8 | *
9 | * Time complexity - O(n)
10 | * Space complexity - O(1)
11 | *
12 | * http://www.geeksforgeeks.org/find-maximum-value-of-sum-iarri-with-only-rotations-on-given-array-allowed/
13 | */
14 | public class RotationWithMaxSum {
15 | int maxSum(int input[]) {
16 | int arrSum = 0;
17 | int rotationSum = 0;
18 | for (int i =0; i < input.length; i++) {
19 | arrSum += input[i];
20 | rotationSum += i*input[i];
21 | }
22 |
23 | int maxRotationSum = rotationSum;
24 |
25 | for (int i = 1; i < input.length; i++) {
26 | rotationSum += input.length*input[i - 1] - arrSum;
27 | maxRotationSum = Math.max(maxRotationSum, rotationSum);
28 | }
29 | return maxRotationSum;
30 | }
31 |
32 | public static void main(String args[]) {
33 | int input[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9};
34 | RotationWithMaxSum rms = new RotationWithMaxSum();
35 | System.out.print(rms.maxSum(input));
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/interview/array/SelfCrossing.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * Created by tushar_v_roy on 3/10/16.
5 | */
6 | public class SelfCrossing {
7 |
8 | public boolean isSelfCrossing(int[] x) {
9 | if (x.length < 4) {
10 | return false;
11 | }
12 | int v1 = -x[0];
13 | int v2 = -x[1];
14 |
15 | int i = 2;
16 | while (i < x.length) {
17 | if (i % 2 == 0) {
18 | if (i % 4 == 0) {
19 | v1 -= x[i];
20 | } else {
21 | v1 += x[i];
22 | }
23 | } else {
24 | if ((i + 1) % 4 == 0) {
25 | v2 += x[i];
26 | } else {
27 | v2 -= x[i];
28 | }
29 | }
30 | if (i % 2 != 0) {
31 | if ((v1 >= 0 && v2 <= 0) || (v1 <= 0 && v2 >= 0)) {
32 | return true;
33 | }
34 | }
35 | i++;
36 | }
37 | return false;
38 | }
39 |
40 | public static void main(String args[]) {
41 | SelfCrossing sc = new SelfCrossing();
42 | int input[] = {3, 3, 4, 2, 2};
43 | System.out.print(sc.isSelfCrossing(input));
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/com/interview/array/SortedArrayTransformation.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * Date 10/08/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a sorted array of integers nums and integer values a, b and c.
8 | * Apply a function of the form f(x) = ax2 + bx + c to each element x in the array.
9 | *
10 | * Time complexity O(n)
11 | *
12 | * https://leetcode.com/problems/sort-transformed-array/
13 | */
14 | public class SortedArrayTransformation {
15 | public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
16 | int start = 0;
17 | int end = nums.length - 1;
18 | int[] result = new int[nums.length];
19 | int index = (a >= 0 ? nums.length - 1 : 0);
20 | while (start <= end) {
21 | int x = apply(nums[start], a, b, c);
22 | int y = apply(nums[end], a, b, c);
23 | boolean condition = (a >= 0 ? x >= y : x <= y);
24 | if (condition) {
25 | result[index] = x;
26 | start++;
27 | } else {
28 | result[index] = y;
29 | end--;
30 | }
31 | index = index + (a >= 0 ? -1 : 1);
32 | }
33 | return result;
34 | }
35 |
36 | private int apply(int x, int a, int b, int c) {
37 | return a*x*x + b * x + c;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/array/SubarrayWithGivenSum.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/find-subarray-with-given-sum/
5 | */
6 | public class SubarrayWithGivenSum {
7 |
8 | class Pair{
9 | int start;
10 | int end;
11 |
12 | public String toString(){
13 | return start + " " + end;
14 | }
15 | }
16 | public Pair findSubArray(int input[],int sum){
17 | int currentSum = 0;
18 | Pair p = new Pair();
19 | p.start = 0;
20 | for(int i=0; i < input.length; i++){
21 | currentSum += input[i];
22 | p.end = i;
23 | if(currentSum == sum){
24 | return p;
25 | }else if(currentSum > sum){
26 | int s = p.start;
27 | while(currentSum > sum){
28 | currentSum -= input[s];
29 | s++;
30 | }
31 | p.start = s;
32 | if(currentSum == sum){
33 | return p;
34 | }
35 | }
36 | }
37 | return null;
38 | }
39 |
40 | public static void main(String args[]){
41 | SubarrayWithGivenSum sgs = new SubarrayWithGivenSum();
42 | int input[] = {6,3,9,11,1,3,5};
43 | System.out.println(sgs.findSubArray(input,15));
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/com/interview/array/ThreeSumSmallerThanTarget.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Given an array of n integers nums and a target, find the number of index triplets i, j, k
7 | * with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
8 | *
9 | * https://leetcode.com/problems/3sum-smaller/
10 | */
11 | public class ThreeSumSmallerThanTarget {
12 | public int threeSumSmaller(int[] nums, int target) {
13 | if (nums.length < 3) {
14 | return 0;
15 | }
16 | Arrays.sort(nums);
17 | int count = 0;
18 | for (int i = 0; i < nums.length; i++) {
19 | int j = i + 1;
20 | int k = nums.length - 1;
21 | while (j < k) {
22 | if (nums[i] + nums[j] + nums[k] >= target) {
23 | k--;
24 | } else {
25 | count += k - j;
26 | j++;
27 | }
28 | }
29 | }
30 | return count;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/array/TrappingWater.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 | /**
3 | * References
4 | * https://oj.leetcode.com/problems/trapping-rain-water/
5 | * https://leetcode.com/problems/trapping-rain-water/
6 | */
7 | public class TrappingWater {
8 |
9 | public int trap(int[] height) {
10 | if(height == null || height.length == 0) {
11 | return 0;
12 | }
13 | int len = height.length;
14 | int left[] = new int[len];
15 | int right[] = new int[len];
16 | left[0] = height[0];
17 | right[len-1] = height[len -1];
18 | for (int i = 1; i < len; i++) {
19 | left[i] = Math.max(height[i], left[i-1]);
20 | right[len - i - 1] = Math.max(height[len- i - 1], right[len-i]);
21 | }
22 |
23 | int maxWaterTrapped = 0;
24 | for (int i = 1; i < len - 1; i++) {
25 | int min = Math.min(left[i], right[i]);
26 | if (height[i] < min) {
27 | maxWaterTrapped += min - height[i];
28 | }
29 | }
30 | return maxWaterTrapped;
31 | }
32 |
33 | public static void main(String args[]){
34 | int input[] = {0,1,0,2,1,0,1,3,2,1,2,1};
35 | TrappingWater tw = new TrappingWater();
36 | System.out.println(tw.trap(input));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/interview/array/TripletSumLessThanTotal.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Date 12/29/2015
7 | * @author Tushar Roy
8 | *
9 | * Given array with unique numbers and a total, find all triplets whose sum is less than total
10 | *
11 | * http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/
12 | */
13 | public class TripletSumLessThanTotal {
14 |
15 | public int findAllTriplets(int input[], int total) {
16 | Arrays.sort(input);
17 | int result = 0;
18 | for (int i = 0; i < input.length - 2; i++) {
19 | int j = i + 1;
20 | int k = input.length - 1;
21 |
22 | while (j < k) {
23 | if (input[i] + input[j] + input[k] >= total) {
24 | k--;
25 | } else {
26 | result += k - j;
27 | j++;
28 | }
29 | }
30 | }
31 | return result;
32 | }
33 |
34 | public static void main(String args[]) {
35 | int input[] = {5, 1, 3, 4, 7};
36 | TripletSumLessThanTotal tt = new TripletSumLessThanTotal();
37 | System.out.print(tt.findAllTriplets(input, 12));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/array/WaterContainer.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | /**
4 | * Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
5 | * n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines,
6 | * which together with x-axis forms a container, such that the container contains the most water.
7 | *
8 | * https://leetcode.com/problems/container-with-most-water/
9 | */
10 | public class WaterContainer {
11 | public int maxArea(int[] height) {
12 | int i = 0;
13 | int j = height.length - 1;
14 | int maxArea = 0;
15 | while (i < j) {
16 | if (height[i] < height[j]) {
17 | maxArea = Math.max(maxArea, (height[i]) * (j - i));
18 | i++;
19 | } else {
20 | maxArea = Math.max(maxArea, height[j] * (j - i));
21 | j--;
22 | }
23 | }
24 | return maxArea;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/interview/array/ZigZagArrangement.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Date 12/30/2015
7 | * @author Tushar Roy
8 | *
9 | * Given an array of unique elements rearrange the array to be a < b > c < d > e form
10 | *
11 | * Time complexity - O(n)
12 | * Space complexity - O(1)
13 | *
14 | * http://www.geeksforgeeks.org/convert-array-into-zig-zag-fashion/
15 | */
16 | public class ZigZagArrangement {
17 |
18 | public void rearrange(int input[]) {
19 | boolean isLess = true;
20 | for (int i = 0; i < input.length - 1; i++) {
21 | if(isLess) {
22 | if (input[i] > input[i+1]) {
23 | swap(input, i, i+1);
24 | }
25 | } else {
26 | if (input[i] < input[i+1]) {
27 | swap(input, i, i+1);
28 | }
29 | }
30 | isLess = !isLess;
31 | }
32 | }
33 |
34 | private void swap(int input[], int i, int j) {
35 | int t = input[i];
36 | input[i] = input[j];
37 | input[j] = t;
38 | }
39 |
40 | public static void main(String args[]) {
41 | int input[] = {4, 3, 2, 6, 7, 1, 9};
42 | ZigZagArrangement zza = new ZigZagArrangement();
43 | zza.rearrange(input);
44 | Arrays.stream(input).forEach(i -> System.out.print(i + " "));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/ArithmeticProgressionSearch.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | /**
4 | * http://www.careercup.com/question?id=4798365246160896
5 | */
6 | public class ArithmeticProgressionSearch {
7 |
8 | public int search(int input[]){
9 | int low =0;
10 | int high = input.length-1;
11 | int ap = (input[high] - input[low])/(input.length);
12 | int middle = -1;
13 | while(low <= high){
14 | middle = (low + high)/2;
15 | if(input[middle] == input[0] + (middle)*ap){
16 | low = middle+1;
17 | }else if((input[middle] > input[0] + (middle)*ap) &&
18 | input[middle-1] == input[0] + (middle-1)*ap){
19 | return input[0] + (middle)*ap;
20 | }else{
21 | high = middle-1;
22 | }
23 | }
24 | return -1;
25 | }
26 | public static void main(String args[]){
27 | int input[] = {1,7,10,13,16,19,22};
28 | ArithmeticProgressionSearch aps = new ArithmeticProgressionSearch();
29 | System.out.println(aps.search(input));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/BinarySearch.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | /**
4 | * Regular binary search
5 | */
6 | public class BinarySearch {
7 |
8 | public int search(final int input[], int search) {
9 | int low = 0;
10 | int high = input.length - 1;
11 | int mid;
12 | while (low <= high) {
13 | mid = low + ((high - low) / 2);
14 | if (input[mid] == search) {
15 | return mid;
16 | } else if (input[mid] < search) {
17 | low = mid + 1;
18 | } else {
19 | high = mid - 1;
20 | }
21 | }
22 | return -1;
23 | }
24 |
25 | public static void main(String args[]) {
26 | BinarySearch bSearch = new BinarySearch();
27 | final int arr1[] = {1, 2, 4, 5, 7, 8};
28 | System.out.println(bSearch.search(arr1, -1));
29 | System.out.println(bSearch.search(arr1, 1));
30 | System.out.println(bSearch.search(arr1, 8));
31 | System.out.println(bSearch.search(arr1, 2));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/CountNDistinctPairsWithDifferenceK.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * http://www.geeksforgeeks.org/count-pairs-difference-equal-k/
7 | */
8 | public class CountNDistinctPairsWithDifferenceK {
9 |
10 | public int count(int arr[],int k){
11 | Arrays.sort(arr);
12 | int count = 0;
13 | for(int i=0; i < arr.length; i++){
14 | boolean result = binarySearch(arr, i+1, arr.length-1, arr[i] + k);
15 | if(result){
16 | count++;
17 | }
18 | }
19 | return count;
20 | }
21 |
22 | private boolean binarySearch(int arr[],int start,int end,int num){
23 | if(start > end){
24 | return false;
25 | }
26 | int mid = (start + end)/2;
27 | if(arr[mid] == num){
28 | return true;
29 | }
30 | else if(arr[mid] > num){
31 | return binarySearch(arr,start,mid-1,num);
32 | }else{
33 | return binarySearch(arr,mid+1,end,num);
34 | }
35 | }
36 |
37 | public static void main(String args[]){
38 | CountNDistinctPairsWithDifferenceK cn = new CountNDistinctPairsWithDifferenceK();
39 | int arr[] = {1,2,3,4,5,7,9};
40 | System.out.print(cn.count(arr, 3));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/FirstOccurrenceOfNumberInSortedArray.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/check-for-majority-element-in-a-sorted-array/
5 | */
6 | public class FirstOccurrenceOfNumberInSortedArray {
7 |
8 | public int firstOccurrence(int input[], int x){
9 | int low = 0;
10 | int high = input.length-1;
11 |
12 | while(low <= high){
13 | int middle = (low + high)/2;
14 | if(input[middle] == x && (middle == 0 || input[middle-1] < x)){
15 | return middle;
16 | }else if(input[middle] < x){
17 | low = middle+1;
18 | }else{
19 | high = middle-1;
20 | }
21 | }
22 | return -1;
23 | }
24 |
25 | public static void main(String args[]){
26 | FirstOccurrenceOfNumberInSortedArray fos = new FirstOccurrenceOfNumberInSortedArray();
27 | int input[] = {1,2,2,2,2,2,5,7,7};
28 | System.out.println(fos.firstOccurrence(input, 6));
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/MinimumInSortedRotatedArray.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | /**
4 | * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
5 | */
6 | public class MinimumInSortedRotatedArray {
7 | public int findMin(int[] nums) {
8 | int low = 0;
9 | int high = nums.length - 1;
10 | while (low < high) {
11 | int middle = (low + high)/2;
12 | if ((middle == 0 && nums[middle] < nums[middle + 1]) || (middle > 0 && nums[middle] < nums[middle - 1])) {
13 | return nums[middle];
14 | }
15 | else if (nums[middle] > nums[high]) {
16 | low = middle + 1;
17 | } else {
18 | high = middle - 1;
19 | }
20 | }
21 | return nums[low];
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/MissingNumberInConsecutiveNumbers.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | /**
4 | * Find missing number in consecutive numbers.
5 | */
6 | public class MissingNumberInConsecutiveNumbers {
7 |
8 | public Integer findMissing(int arr[]){
9 |
10 | int lowNum = arr[0];
11 | int low = 0;
12 | int high = arr.length -1;
13 | int middle = (low + high)/2;
14 | while(low <= high){
15 | middle = (low + high)/2;
16 | if(arr[middle] == (middle+1 + lowNum) && middle-1 >=0 && arr[middle-1] == (middle + lowNum-1)){
17 | return middle + lowNum;
18 | }
19 | else if((middle + lowNum) == arr[middle]){
20 | low = middle+1;
21 | }else {
22 | high = middle-1;
23 | }
24 | }
25 | return null;
26 | }
27 |
28 | public static void main(String args[]){
29 | int arr[] = {3,4,5,6,7,8,9,10,11,12};
30 | int arr1[] = {-5,-4,-3,-1,0,1,2,3};
31 | MissingNumberInConsecutiveNumbers mn = new MissingNumberInConsecutiveNumbers();
32 | System.out.println(mn.findMissing(arr1));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/MonotonicallyIncreasingFunctionBecomesPositive.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/find-the-point-where-a-function-becomes-negative/
5 | */
6 | public class MonotonicallyIncreasingFunctionBecomesPositive {
7 |
8 | private int f(int x){
9 | return x*x - 10*x - 20;
10 | }
11 |
12 | public int findPoint(){
13 | int i=1;
14 | while(f(i) <=0 ){
15 | i = i*2;
16 | }
17 | return binarySearch(i/2,i);
18 | }
19 |
20 | private int binarySearch(int start,int end){
21 | int mid = (start+end)/2;
22 | while(start < end){
23 | mid = (start+end)/2;
24 | if(f(mid) >0 && f(mid-1) <=0){
25 | return mid;
26 | }
27 | if(f(mid) <=0 && f(mid+1)>0){
28 | return mid+1;
29 | }
30 | if(f(mid) <= 0){
31 | start = mid+1;
32 | }else{
33 | end = mid-1;
34 | }
35 | }
36 | return mid;
37 | }
38 |
39 | public static void main(String args[]){
40 | MonotonicallyIncreasingFunctionBecomesPositive mif = new MonotonicallyIncreasingFunctionBecomesPositive();
41 | System.out.print(mif.findPoint());
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/SearchInsertPosition.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | /**
4 | * https://leetcode.com/problems/search-insert-position/
5 | */
6 | public class SearchInsertPosition {
7 | public int searchInsert(int[] nums, int target) {
8 | int low = 0;
9 | int high = nums.length - 1;
10 | while (low <= high) {
11 | int middle = (low + high)/2;
12 | if (nums[middle] == target) {
13 | return middle;
14 | }
15 | if (nums[middle] < target && (middle == nums.length - 1 || nums[middle + 1] > target)) {
16 | return middle + 1;
17 | }
18 | if (nums[middle] < target) {
19 | low = middle + 1;
20 | } else {
21 | high = middle - 1;
22 | }
23 | }
24 | return 0;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/interview/binarysearch/SquareRootOfNumber.java:
--------------------------------------------------------------------------------
1 | package com.interview.binarysearch;
2 |
3 | /**
4 | *
5 | * https://leetcode.com/problems/sqrtx/
6 | */
7 | public class SquareRootOfNumber {
8 | public int mySqrt(int x) {
9 | if (x == 0)
10 | return 0;
11 | int left = 1, right = x;
12 | while (true) {
13 | int mid = left + (right - left)/2;
14 | if (mid > x/mid) {
15 | right = mid - 1;
16 | } else {
17 | if (mid + 1 > x/(mid + 1))
18 | return mid;
19 | left = mid + 1;
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/interview/bits/BitRotation.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | /*
4 | * http://www.geeksforgeeks.org/rotate-bits-of-an-integer/
5 | */
6 | public class BitRotation {
7 |
8 | public byte rotateLeft(byte num, int d){
9 | return (byte)((num << d) | (num >>> (8-d)));
10 | }
11 |
12 | public static void main(String args[]){
13 | BitRotation br = new BitRotation();
14 | System.out.println(br.rotateLeft((byte)28, 2));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/interview/bits/ByteAsStorage.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | public class ByteAsStorage {
4 |
5 | void useByteAsBoolean(boolean[] visited){
6 | byte[] bytes = new byte[(int)(Math.ceil(visited.length*1.0/8))];
7 | for(int i=0; i < visited.length; i++){
8 | int row = i/8;
9 | int col = i%8;
10 | if(visited[i]){
11 | bytes[row] = (byte)(bytes[row] | (byte)(1<= 1){
21 | System.out.print("True");
22 | }else{
23 | System.out.print("False");
24 | }
25 | }
26 | }
27 | public static void main(String args[]){
28 | boolean visited[] = {true,false,true,true,false};
29 | ByteAsStorage bas = new ByteAsStorage();
30 | bas.useByteAsBoolean(visited);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/bits/CountingBitsTillNum.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | /**
4 | * Date 04/03/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate
8 | * the number of 1's in their binary representation and return them as an array.
9 | *
10 | * Time complexity O(n)
11 | * Space complexity O(n)
12 | *
13 | * https://leetcode.com/problems/counting-bits/
14 | */
15 | public class CountingBitsTillNum {
16 | public int[] countBits(int num) {
17 | if (num == 0) {
18 | return new int[1];
19 | }
20 | int[] count = new int[num + 1];
21 | count[0] = 0;
22 | int n = 1;
23 | int start = n;
24 | while (start <= num) {
25 | start = n;
26 | count[start++] = 1;
27 | int end = n<<1;
28 | while (start < end && start <= num) {
29 | count[start] = 1 + count[start - n];
30 | start++;
31 | }
32 | n = n<<1;
33 | }
34 | return count;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/com/interview/bits/FindNumberOccurringOnceOtherNumbers3Times.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/find-the-element-that-appears-once/
5 | */
6 | public class FindNumberOccurringOnceOtherNumbers3Times {
7 |
8 | public int getNumberOccurringOnce(int arr[]){
9 | int result = 0;
10 | for(int i=0; i < 32; i++){
11 | int sum = 0;
12 | for(int j=0; j < arr.length; j++){
13 | sum += (arr[j] & 1<>i;
14 | }
15 | result = result | (sum%3)< grayCode(int n) {
16 | List result = new LinkedList<>();
17 | for (int i = 0; i < 1<>1);
19 | }
20 | return result;
21 | }
22 |
23 | public static void main(String args[]) {
24 | GrayCode gc = new GrayCode();
25 | System.out.println(gc.grayCode(4));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/com/interview/bits/InsertMintoNiTojBits.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | /**
4 | * Exercise 5.1 150 qs
5 | */
6 | public class InsertMintoNiTojBits {
7 |
8 | public int insert(int M,int N, int i, int j){
9 | int mask = 1<<(j+1) -1;
10 | mask = mask< 0 && (num & (num-1)) == 0){
13 | return num;
14 | }
15 | while((num & (num-1)) > 0){
16 | num = num & (num-1);
17 | }
18 | return num<<1;
19 | }
20 | public static void main(String args[]){
21 | NextPowerOf2 np = new NextPowerOf2();
22 | System.out.println(np.nextPowerOf2(4));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/interview/bits/NumberOfBitsFlipToConvertNToM.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | /**
4 | * Exercise 5.5 150 qs
5 | */
6 | public class NumberOfBitsFlipToConvertNToM {
7 |
8 | public int number(int m, int n){
9 | int r = n^m;
10 | int count = 0;
11 | while(r != 0){
12 | r = r & (r-1);
13 | count++;
14 | }
15 | return count;
16 | }
17 | public static void main(String args[]){
18 | NumberOfBitsFlipToConvertNToM nb = new NumberOfBitsFlipToConvertNToM();
19 | System.out.println(nb.number(31, 14));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/com/interview/bits/RealNumberToBinary.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | /**
4 | * Exercise 5.2 150 qs
5 | */
6 | public class RealNumberToBinary {
7 |
8 | public void print(double num){
9 | if(num > 1 || num < 0){
10 | System.out.println("ERROR");
11 | return;
12 | }
13 |
14 | StringBuilder stringBuilder = new StringBuilder();
15 | stringBuilder.append("0.");
16 | while(num > 0){
17 | num = num*2;
18 | int r = (int)num ;
19 | stringBuilder.append(r);
20 | num = num -r;
21 | if(stringBuilder.length() > 32){
22 | System.out.println("ERROR");
23 | return;
24 | }
25 | }
26 | System.out.println(stringBuilder);
27 | }
28 | public static void main(String args[]){
29 | RealNumberToBinary rnb = new RealNumberToBinary();
30 | rnb.print(0.8125);
31 | rnb.print(0.72);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/interview/bits/ReverseBits.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/
5 | */
6 | public class ReverseBits {
7 |
8 | public int reverse(int num){
9 | //assuming int is 32 bits.
10 | int result = 0;
11 | int r1 = 1;
12 | for(int i=31; i >= 0; i--,r1<<=1){
13 | if((num & 1<> 1 & mask2);
12 | }
13 |
14 | public static void main(String args[]){
15 | SwapOddEvenBits soe = new SwapOddEvenBits();
16 | System.out.println(soe.swap(697));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/interview/bits/SwapTwoBits.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | /**
4 | * http://www.careercup.com/question?id=17542662
5 | */
6 | public class SwapTwoBits {
7 |
8 | public int swap(int num,int i, int j){
9 | int t1 = (num & 1<>i ^ (num & 1<>j) != 0){
20 | num ^= 1< 1001 -> 101 -> 11
8 | * 1010 -> 110 -> 101 -> 11
9 | *
10 | * No matter which route you take it leads to same result so just looking at swaps you can say
11 | * which player will win
12 | *
13 | */
14 | public class WinnerWithBeautifulNumber {
15 |
16 | public int winner(int n){
17 | int sum = 0;
18 | int i =1;
19 | int result = 0;
20 | while( i <= n){
21 | i = i*2;
22 | }
23 | i = i/2;
24 | while(i > 0){
25 | if((n & i) != 0){
26 | sum++;
27 | }else{
28 | result += sum;
29 | }
30 | i = i/2;
31 | }
32 | if(result % 2 == 0){
33 | return 2;
34 | }else{
35 | return 1;
36 | }
37 | }
38 |
39 | public static void main(String args[]){
40 | WinnerWithBeautifulNumber wwb = new WinnerWithBeautifulNumber();
41 | System.out.println(wwb.winner(37));
42 | System.out.println(wwb.winner(10));
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/interview/dynamic/CountAs.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/how-to-print-maximum-number-of-a-using-given-four-keys/
5 | * Test cases
6 | * Negative number
7 | * Number less than 7
8 | * Number greater than equal to 7
9 | */
10 | public class CountAs {
11 |
12 | public int countAsRec(int n){
13 |
14 | if(n < 7){
15 | return n;
16 | }
17 | int max = Integer.MIN_VALUE;
18 | int result = 0;
19 | for(int b=n-3; b > 0; b--){
20 | result = (n-b-1)*countAs(b);
21 | if(max < result){
22 | max = result;
23 | }
24 | }
25 | return max;
26 | }
27 |
28 | public int countAs(int n){
29 | if(n < 7){
30 | return n;
31 | }
32 |
33 | int T[] = new int[n+1];
34 | for(int i=1; i < 7 ; i++){
35 | T[i] = i;
36 | }
37 | for(int i=7; i <= n; i++){
38 | for(int b = i-3; b > 0; b--){
39 | T[i] = Math.max(T[i], T[b]*(i-b-1));
40 | }
41 | }
42 | return T[n];
43 | }
44 |
45 | public static void main(String args[]){
46 | CountAs ca =new CountAs();
47 | System.out.println(ca.countAsRec(25));
48 | System.out.println(ca.countAs(25));
49 |
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/com/interview/dynamic/CountNumberOfBinaryWithoutConsecutive1s.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
5 | * It is really a straight up fibonacci series with values
6 | * 1,2,3,5,8,13....
7 | * Look how we assign a[i] value of a[i-1] + b[i-1] and then b[i] becomes a[i]
8 | */
9 | public class CountNumberOfBinaryWithoutConsecutive1s {
10 |
11 | public int count(int n){
12 | int a[] = new int[n];
13 | int b[] = new int[n];
14 |
15 | a[0] = 1;
16 | b[0] = 1;
17 |
18 | for(int i=1; i < n; i++){
19 | a[i] = a[i-1] + b[i-1];
20 | b[i] = a[i-1];
21 | }
22 |
23 | return a[n-1] + b[n-1];
24 | }
25 |
26 | public int countSimple(int n){
27 | int a = 1;
28 | int b = 1;
29 |
30 | for(int i=1; i < n; i++){
31 | int tmp = a;
32 | a = a + b;
33 | b = tmp;
34 | }
35 |
36 | return a + b;
37 | }
38 |
39 | public static void main(String args[]){
40 | CountNumberOfBinaryWithoutConsecutive1s cnb = new CountNumberOfBinaryWithoutConsecutive1s();
41 | System.out.println(cnb.count(5));
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/interview/dynamic/CountNumberOfTreesInBST.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/program-nth-catalan-number/
5 | * Count number of binary search tree created for array of size n
6 | */
7 | public class CountNumberOfTreesInBST {
8 |
9 | int countTreesRec(int numKeys) {
10 | if (numKeys <=1) {
11 | return(1);
12 | }
13 | else {
14 | int sum = 0;
15 | int left, right, root;
16 | for (root=1; root<=numKeys; root++) {
17 | left = countTreesRec(root - 1);
18 | right = countTreesRec(numKeys - root);
19 | sum += left*right;
20 | }
21 | return(sum);
22 | }
23 | }
24 |
25 | public int countTrees(int n){
26 | int T[] = new int[n+1];
27 | T[0] = 1;
28 | T[1] = 1;
29 | for(int i=2; i <= n; i++){
30 | for(int j=0; j = l){
30 | T[i][j] += T[i-1][j-l];
31 | }
32 | }
33 | }
34 | }
35 | return T[n][k];
36 | }
37 |
38 | public static void main(String args[]){
39 | DiceThrowWays dtw = new DiceThrowWays();
40 | System.out.println(dtw.numberOfWays(3, 3, 6));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/interview/dynamic/DistinctSubsequence.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | /**
4 | * Date 03/20/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a string S and a string T, count the number of distinct subsequences of T in S.
8 | *
9 | * Time complexity O(n^2)
10 | * Space complexity O(n^2)
11 | *
12 | * https://leetcode.com/problems/distinct-subsequences/
13 | */
14 | public class DistinctSubsequence {
15 | public int numDistinct(String s, String t) {
16 | if (s.length() == 0 || t.length() == 0) {
17 | return 0;
18 | }
19 | int[][] T = new int[t.length() + 1][s.length() + 1];
20 | for (int i = 0; i < T[0].length; i++) {
21 | T[0][i] = 1;
22 | }
23 | for (int i = 1; i < T.length; i++) {
24 | for (int j = 1; j < T[0].length; j++) {
25 | if (s.charAt(j - 1) == t.charAt(i - 1)) {
26 | T[i][j] = T[i-1][j-1] + T[i][j-1];
27 | } else {
28 | T[i][j] = T[i][j-1];
29 | }
30 | }
31 | }
32 | return T[t.length()][s.length()];
33 | }
34 |
35 | public static void main(String args[]) {
36 | DistinctSubsequence ds = new DistinctSubsequence();
37 | System.out.println(ds.numDistinct("abdacgblc", "abc"));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/dynamic/MatrixMultiplicationCost.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/
5 | */
6 | public class MatrixMultiplicationCost {
7 |
8 | public int findCost(int arr[]){
9 | int temp[][] = new int[arr.length][arr.length];
10 | int q = 0;
11 | for(int l=2; l < arr.length; l++){
12 | for(int i=0; i < arr.length - l; i++){
13 | int j = i + l;
14 | temp[i][j] = 1000000;
15 | for(int k=i+1; k < j; k++){
16 | q = temp[i][k] + temp[k][j] + arr[i]*arr[k]*arr[j];
17 | if(q < temp[i][j]){
18 | temp[i][j] = q;
19 | }
20 | }
21 | }
22 | }
23 | return temp[0][arr.length-1];
24 | }
25 |
26 | public static void main(String args[]){
27 | MatrixMultiplicationCost mmc = new MatrixMultiplicationCost();
28 | int arr[] = {4,2,3,5,3};
29 | int cost = mmc.findCost(arr);
30 | System.out.print(cost);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/dynamic/MaximumProductCutting.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/dynamic-programming-set-36-cut-a-rope-to-maximize-product/
5 | */
6 | public class MaximumProductCutting {
7 |
8 | public int maxProduct(int num){
9 | int T[] = new int[num+1];
10 | T[0] = 1;
11 | for(int i=1; i <= num; i++){
12 | T[i] = i;
13 | }
14 | for(int i=2; i <= num; i++){
15 | for(int j=1; j <= i; j++){
16 | T[i] = Math.max(T[i],T[j]*T[i-j]);
17 | }
18 | }
19 | return T[num];
20 | }
21 |
22 | public static void main(String args[]){
23 | MaximumProductCutting mpc = new MaximumProductCutting();
24 | System.out.println(mpc.maxProduct(13));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/interview/dynamic/MinimumTriangleSum.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on
7 | * the row below.
8 | * https://leetcode.com/problems/triangle/
9 | */
10 | public class MinimumTriangleSum {
11 | public int minimumTotal(List> triangle) {
12 | int n = triangle.size();
13 | int[] dp = new int[n];
14 |
15 | for (int i = 0; i < triangle.get(n - 1).size(); i++) {
16 | dp[i] = triangle.get(n - 1).get(i);
17 | }
18 |
19 | for (int i = triangle.size() - 2; i >= 0; i--) {
20 | for (int j = 0; j < triangle.get(i).size(); j++) {
21 | dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j + 1]);
22 | }
23 | }
24 | return dp[0];
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/interview/dynamic/NumberOfPathsInMxNMatrix.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
5 | */
6 | public class NumberOfPathsInMxNMatrix {
7 |
8 | public int countPathsRecursive(int n, int m){
9 | if(n == 1 || m == 1){
10 | return 1;
11 | }
12 | return countPathsRecursive(n-1, m) + countPathsRecursive(n, m-1);
13 | }
14 |
15 | public int countPaths(int n,int m){
16 | int T[][] = new int[n][m];
17 | for(int i=0; i < n; i++){
18 | T[i][0] = 1;
19 | }
20 |
21 | for(int i=0; i < m; i++){
22 | T[0][i] = 1;
23 | }
24 | for(int i=1; i < n; i++){
25 | for(int j=1; j < m; j++){
26 | T[i][j] = T[i-1][j] + T[i][j-1];
27 | }
28 | }
29 | return T[n-1][m-1];
30 | }
31 |
32 | public static void main(String args[]){
33 | NumberOfPathsInMxNMatrix nop = new NumberOfPathsInMxNMatrix();
34 | System.out.print(nop.countPathsRecursive(3,3));
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/interview/linklist/DeleteDuplicateNodes.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | /**
4 | * Date 04/17/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct
8 | * numbers from the original list.
9 | *
10 | * For example,
11 | * Given 1->2->3->3->4->4->5, return 1->2->5.
12 | * Given 1->1->1->2->3, return 2->3.
13 | *
14 | * https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
15 | */
16 | public class DeleteDuplicateNodes {
17 | public Node deleteDuplicates(Node head) {
18 | Node dummyNode = new Node();
19 | dummyNode.next = head;
20 | Node current = head;
21 | Node prev = dummyNode;
22 | while (current != null) {
23 | while(current.next != null && current.data == current.next.data) {
24 | current = current.next;
25 | }
26 | if (prev.next == current) {
27 | prev = current;
28 | } else {
29 | prev.next = current.next;
30 | }
31 | current = current.next;
32 | }
33 | return dummyNode.next;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/interview/linklist/Flatten2DList.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | import java.util.Iterator;
4 | import java.util.List;
5 |
6 | /**
7 | * Date 10/10/2016
8 | * @author Tushar Roy
9 | *
10 | * Implement an iterator to flatten a 2d vector.
11 | *
12 | * https://leetcode.com/problems/flatten-2d-vector/
13 | *
14 | */
15 | public class Flatten2DList implements Iterator {
16 | private List> vector;
17 | private int currentList = 0;
18 | private int currentPos = 0;
19 | public Flatten2DList(List> vec2d) {
20 | vector = vec2d;
21 | }
22 |
23 | @Override
24 | public Integer next() {
25 | if (!hasNext()) {
26 | throw new IllegalArgumentException();
27 | }
28 | int data = vector.get(currentList).get(currentPos);
29 | currentPos++;
30 | if (currentPos == vector.get(currentList).size()) {
31 | currentPos = 0;
32 | currentList++;
33 | }
34 | return data;
35 | }
36 |
37 | @Override
38 | public boolean hasNext() {
39 | while (currentList < vector.size() && vector.get(currentList).size() == 0) {
40 | currentList++;
41 | }
42 | return currentList < vector.size();
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/interview/linklist/LRUCacheLeetCode.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Date 02/11/2016
8 | * @author Tushar Roy
9 | *
10 | * Reference
11 | * https://leetcode.com/problems/lru-cache/
12 | */
13 | public class LRUCacheLeetCode {
14 |
15 | private LinkedHashMap map;
16 | private int capacity;
17 | public LRUCacheLeetCode(int capacity) {
18 | this.capacity = capacity;
19 | this.map = new MyMap(capacity);
20 | }
21 |
22 | public int get(int key) {
23 | Integer val = map.get(key);
24 | return val == null ? -1 : val;
25 | }
26 |
27 | public void set(int key, int value) {
28 | map.put(key, value);
29 | }
30 |
31 | class MyMap extends LinkedHashMap {
32 | int capacity;
33 | MyMap(int capacity) {
34 | super(capacity, 0.75f, true);
35 | this.capacity = capacity;
36 | }
37 | @Override
38 | protected boolean removeEldestEntry(Map.Entry entry) {
39 | return size() > capacity;
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/interview/linklist/LinkListIsPalindrome.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
5 | * Test cases:
6 | * odd number of nodes
7 | * even number of nodes
8 | * 0 1 or more nodes
9 | * palindrome list
10 | * non palindrom list
11 | */
12 | public class LinkListIsPalindrome {
13 |
14 | public boolean isPalindrome(NodeRef head,Node end){
15 | if(end == null){
16 | return true;
17 | }
18 | boolean r = isPalindrome(head,end.next);
19 | r = r && head.node.data == end.data;
20 | head.next();
21 | return r;
22 | }
23 |
24 | public static void main(String args[]){
25 | LinkList ll = new LinkList();
26 | Node head = null;
27 | head = ll.addNode(1, head);
28 | head = ll.addNode(2, head);
29 | head = ll.addNode(3, head);
30 | head = ll.addNode(4, head);
31 | head = ll.addNode(3, head);
32 | head = ll.addNode(2, head);
33 | head = ll.addNode(1, head);
34 | NodeRef nodeRef = new NodeRef();
35 | nodeRef.node = head;
36 | LinkListIsPalindrome llp = new LinkListIsPalindrome();
37 | System.out.println(llp.isPalindrome(nodeRef, head));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/linklist/MiddleElementOfLinkList.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | /**
4 | * Find middle element in linklist.
5 | * Use two pointer approach.
6 | * Test cases
7 | * 0,1,2,3,4 and so on nodes
8 | * @author tusroy
9 | *
10 | */
11 | public class MiddleElementOfLinkList {
12 |
13 | public int middle(Node head){
14 | if(head == null || head.next == null){
15 | return head.data;
16 | }
17 |
18 | Node slow = head;
19 | Node fast = head.next;
20 | while(fast != null && fast.next != null){
21 | slow = slow.next;
22 | fast = fast.next.next;
23 | }
24 | return slow.data;
25 | }
26 |
27 | public static void main(String args[]){
28 | MiddleElementOfLinkList mle = new MiddleElementOfLinkList();
29 | LinkList ll = new LinkList();
30 | Node head = null;
31 | head = ll.addNode(1, head);
32 | System.out.println(mle.middle(head));
33 | head = ll.addNode(2, head);
34 | System.out.println(mle.middle(head));
35 | head = ll.addNode(3, head);
36 | System.out.println(mle.middle(head));
37 | head = ll.addNode(4, head);
38 | System.out.println(mle.middle(head));
39 | head = ll.addNode(5, head);
40 | System.out.println(mle.middle(head));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/interview/linklist/ReverseAlternateNodeAndAppendAtEnd.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/given-linked-list-reverse-alternate-nodes-append-end/
5 | * Test case
6 | * Even and odd number of nodes
7 | */
8 | public class ReverseAlternateNodeAndAppendAtEnd {
9 |
10 | public void act(Node head){
11 |
12 | Node result = null;
13 | LinkList ll = new LinkList();
14 | while(head != null && head.next != null){
15 | Node temp = head.next;
16 | head.next = head.next.next;
17 | temp.next = null;
18 | result = ll.addAtFront(temp,result);
19 | if(head.next == null){
20 | break;
21 | }
22 | head = head.next;
23 | }
24 | head.next = result;
25 | }
26 |
27 | public static void main(String args[]){
28 | LinkList ll = new LinkList();
29 | Node head = null;
30 | head = ll.addNode(1, head);
31 | head = ll.addNode(2, head);
32 | head = ll.addNode(3, head);
33 | head = ll.addNode(4, head);
34 | head = ll.addNode(5, head);
35 | head = ll.addNode(6, head);
36 | ReverseAlternateNodeAndAppendAtEnd ran = new ReverseAlternateNodeAndAppendAtEnd();
37 | ran.act(head);
38 | ll.printList(head);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/com/interview/linklist/ReverseKNodes.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list/
5 | * Test case
6 | * odd or even number of k
7 | * odd or even number of nodes in the list
8 | */
9 | public class ReverseKNodes {
10 |
11 | public Node reverse(Node head,int k){
12 | if(head == null){
13 | return null;
14 | }
15 | Node front = null;
16 | Node middle = head;
17 | Node end = null;
18 | int i=0;
19 | while(middle != null && i < k){
20 | end = middle.next;
21 | middle.next = front;
22 | front = middle;
23 | middle = end;
24 | i++;
25 | }
26 | head.next = reverse(middle,k);
27 | return front;
28 | }
29 |
30 |
31 | public static void main(String args[]){
32 | LinkList ll = new LinkList();
33 | Node head = null;
34 | head = ll.addNode(1, head);
35 | head = ll.addNode(2, head);
36 | head = ll.addNode(3, head);
37 | head = ll.addNode(4, head);
38 | head = ll.addNode(5, head);
39 | head = ll.addNode(6, head);
40 | head = ll.addNode(7, head);
41 | head = ll.addNode(8, head);
42 | ReverseKNodes rn = new ReverseKNodes();
43 | head = rn.reverse(head, 3);
44 | ll.printList(head);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/com/interview/linklist/RotateList.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | /**
4 | * Date 10/10/2016
5 | * @author Tushar Roy
6 | * Given a list, rotate the list to the right by k places, where k is non-negative.
7 | *
8 | * Time complexity O(min(n, k))
9 | *
10 | * https://leetcode.com/problems/rotate-list/
11 | */
12 | public class RotateList {
13 | public Node rotateRight(Node head, int k) {
14 | if (head == null || k == 0) {
15 | return head;
16 | }
17 | Node slow = head;
18 | Node fast = head;
19 | int i = 0;
20 | while (i < k && fast != null) {
21 | fast = fast.next;
22 | i++;
23 | }
24 |
25 | if (fast == null) {
26 | return rotateRight(head, k % i);
27 | }
28 | while (fast.next != null) {
29 | fast = fast.next;
30 | slow = slow.next;
31 | }
32 | Node next = slow.next;
33 | slow.next = null;
34 | fast.next = head;
35 | return next;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/interview/misc/AngleBetweenHourAndMinuteHand.java:
--------------------------------------------------------------------------------
1 | package com.interview.misc;
2 |
3 | /**
4 | * Find small angle between hour and minute hand in analog clock
5 | */
6 | public class AngleBetweenHourAndMinuteHand {
7 |
8 | public double angle(int hour, int min){
9 | double hourAngle = (hour%12)*360/12 + ((double)min/60)*(360/12);
10 | double minAngle = min*360/60;
11 |
12 | double angleDiff = Math.abs(hourAngle - minAngle);
13 | return angleDiff < 360 - angleDiff ? angleDiff : 360 - angleDiff;
14 | }
15 |
16 | public static void main(String args[]){
17 | AngleBetweenHourAndMinuteHand abm = new AngleBetweenHourAndMinuteHand();
18 | System.out.println(abm.angle(10, 15));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/interview/misc/BulbSwitcher.java:
--------------------------------------------------------------------------------
1 | package com.interview.misc;
2 |
3 | /**
4 | * There are n bulbs that are initially off. You first turn on all the bulbs.
5 | * Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's
6 | * off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only
7 | * toggle the last bulb. Find how many bulbs are on after n rounds.
8 | *
9 | * https://leetcode.com/problems/bulb-switcher/
10 | */
11 | public class BulbSwitcher {
12 | public int bulbSwitch(int n) {
13 | int count = 0;
14 | while (count*count <= n) {
15 | count++;
16 | }
17 | return count - 1;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/interview/misc/DifferenceBetweenTwoTime.java:
--------------------------------------------------------------------------------
1 | package com.interview.misc;
2 |
3 | /**
4 | * Given two times in four digits number e.g 10:10 is 1010 find difference between them
5 | * Test cases
6 | * Time 1 better be less than equal to time 2
7 | * First 2 digits better be between 0 and 23
8 | * Last 2 digits of number better be between 0 to 59
9 | */
10 | public class DifferenceBetweenTwoTime {
11 |
12 | public int diff(int time1, int time2){
13 | if(time2 < time1){
14 | throw new IllegalArgumentException();
15 | }
16 |
17 | int hourDiff = time2/100 - time1/100 -1;
18 | int minDiff = time2%100 + (60 - time1%100);
19 | if(minDiff >= 60){
20 | hourDiff++;
21 | minDiff = minDiff - 60;
22 | }
23 | return hourDiff*100 + minDiff;
24 | }
25 |
26 | public static void main(String args[]){
27 | DifferenceBetweenTwoTime dbtt = new DifferenceBetweenTwoTime();
28 | int time = dbtt.diff(1400, 1645);
29 | System.out.println(time);
30 | time = dbtt.diff(1223, 1246);
31 | System.out.println(time);
32 | time = dbtt.diff(1500, 1620);
33 | System.out.println(time);
34 | time = dbtt.diff(344, 936);
35 | System.out.println(time);
36 | time = dbtt.diff(1000, 1234);
37 | System.out.println(time);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/misc/FindingCelebrity.java:
--------------------------------------------------------------------------------
1 | package com.interview.misc;
2 |
3 | /**
4 | * Find the Celebrity
5 | * https://leetcode.com/problems/find-the-celebrity/
6 | */
7 | class Relation {
8 | boolean knows(int a, int b) {
9 | return false;
10 | }
11 | }
12 |
13 | public class FindingCelebrity extends Relation {
14 |
15 | public int findCelebrity(int n) {
16 | int celebrity = 0;
17 | for (int i = 1; i < n; i++) {
18 | if (knows(celebrity, i)) {
19 | celebrity = i;
20 | }
21 | }
22 | for (int i = 0; i < n; i++) {
23 | if (i == celebrity) {
24 | continue;
25 | }
26 | if (knows(celebrity, i) || !knows(i, celebrity)) {
27 | return -1;
28 | }
29 | }
30 | return celebrity;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/misc/HammingDistanceBetweenPair.java:
--------------------------------------------------------------------------------
1 | package com.interview.misc;
2 |
3 | /**
4 | * http://www.glassdoor.com/Interview/-a-first-write-a-function-to-calculate-the-hamming-distance-between-two-binary-numbers-b-write-a-function-that-takes-QTN_450885.htm
5 | * Test cases
6 | * Not equal length strings
7 | * String containing anything other than 0 and 1
8 | */
9 | public class HammingDistanceBetweenPair {
10 |
11 | public int hammingDistance(String input[]){
12 | int size = input[0].length();
13 | int total = 0;
14 | for(int i=0; i < size; i++){
15 | int count0s = 0;
16 | int count1s = 0;
17 | for(String str : input){
18 | if(str.charAt(i) == '0'){
19 | count0s++;
20 | }else{
21 | count1s++;
22 | }
23 | }
24 | total += count0s * count1s;
25 | }
26 | return total;
27 | }
28 |
29 | public static void main(String args[]){
30 | String input[] = {"10011","00011","11101","01010"};
31 | HammingDistanceBetweenPair hdb = new HammingDistanceBetweenPair();
32 | System.out.println(hdb.hammingDistance(input));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/interview/misc/PrimeNumbersBeforeN.java:
--------------------------------------------------------------------------------
1 | package com.interview.misc;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * All prime numbers before n
8 | */
9 | public class PrimeNumbersBeforeN {
10 |
11 | public List primeNumbers(int n){
12 | List result = new ArrayList();
13 | result.add(2);
14 | boolean flag = false;
15 | for(int i=3; i < n; i+=2){
16 | for(int r : result){
17 | if(2*r > i){
18 | break;
19 | }
20 | if(i % r == 0){
21 | flag = true;
22 | break;
23 | }
24 | }
25 | if(!flag){
26 | result.add(i);
27 | }
28 | flag = false;
29 | }
30 | return result;
31 | }
32 |
33 | public static void main(String args[]){
34 | PrimeNumbersBeforeN pnb = new PrimeNumbersBeforeN();
35 | List result = pnb.primeNumbers(150);
36 | result.forEach(i -> System.out.print(i + " "));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/interview/multiarray/Fill2DMatrixWith1.java:
--------------------------------------------------------------------------------
1 | package com.interview.multiarray;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/a-boolean-matrix-question/
5 | */
6 | public class Fill2DMatrixWith1 {
7 |
8 | public void fill(int input[][]){
9 | boolean row[] = new boolean[input.length];
10 | boolean col[] = new boolean[input[0].length];
11 | for(int i=0; i < input.length; i++){
12 | for(int j=0; j < input[i].length; j++){
13 | if(input[i][j] == 1){
14 | row[i] = true;
15 | col[j] = true;
16 | }
17 | }
18 | }
19 | for(int i=0; i < input.length; i++){
20 | for(int j=0; j < input[i].length; j++){
21 | if(row[i] || col[j]){
22 | input[i][j] = 1;
23 | }
24 | }
25 | }
26 | }
27 |
28 | public static void main(String args[]){
29 | int input[][] = {{0,0,1,0,0,0},{0,0,0,0,0,0},{1,0,0,0,0,0}};
30 | Fill2DMatrixWith1 fd = new Fill2DMatrixWith1();
31 | fd.fill(input);
32 | for(int i=0; i < input.length; i++){
33 | for(int j=0; j < input[i].length; j++){
34 | System.out.print(input[i][j] + " ");
35 | }
36 | System.out.println();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/multiarray/MatrixInDiagonalOrder.java:
--------------------------------------------------------------------------------
1 | package com.interview.multiarray;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/print-matrix-diagonally/
5 | */
6 | public class MatrixInDiagonalOrder {
7 |
8 | public void printMatrix(int [][]matrix){
9 | for(int i=0; i < matrix.length; i++){
10 | int start =i;
11 | int end =0;
12 | while(start >= 0 && end < matrix[0].length){
13 | System.out.print(matrix[start][end] + " ");
14 | start--;
15 | end++;
16 | }
17 | System.out.print("\n");
18 | }
19 |
20 | for(int i=1; i < matrix[0].length; i++){
21 | int start = matrix.length-1;
22 | int end =i;
23 | while(start >= 0 && end < matrix[0].length){
24 | System.out.print(matrix[start][end] + " ");
25 | start--;
26 | end++;
27 | }
28 | System.out.print("\n");
29 | }
30 | }
31 |
32 | public static void main(String args[]){
33 | int arr[][] = {{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}};
34 | MatrixInDiagonalOrder mdo = new MatrixInDiagonalOrder();
35 | mdo.printMatrix(arr);
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/interview/number/ArithemeticProgressionExists.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/length-of-the-longest-arithmatic-progression-in-a-sorted-array/
5 | */
6 | public class ArithemeticProgressionExists {
7 |
8 | public boolean exists(int input[]){
9 |
10 | for(int i=1; i < input.length-1; i++){
11 | int j = i-1;
12 | int k = i+1;
13 | while(j >=0 && k <= input.length-1){
14 | if(input[i]*2 == input[j] + input[k]){
15 | return true;
16 | }else if(input[i]*2 > input[j] + input[k]){
17 | k++;
18 | }else{
19 | j--;
20 | }
21 | }
22 | }
23 | return false;
24 | }
25 | public static void main(String args[]){
26 | int input[] = {1,3,6,7,10,11,15};
27 | ArithemeticProgressionExists ape = new ArithemeticProgressionExists();
28 | System.out.println(ape.exists(input));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/interview/number/BinomialCoefficient.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/
5 | * Test cases
6 | * k is 0
7 | * k or n are negative
8 | * k greater than n
9 | */
10 | public class BinomialCoefficient {
11 |
12 | public int calculate(int n, int k){
13 | if(k > n-k){
14 | k = n-k;
15 | }
16 | int result = 1;
17 | for(int i=0; i < k; i++){
18 | result *= (n-i);
19 | result /= (i+1);
20 | }
21 | return result;
22 | }
23 |
24 | public static void main(String args[]){
25 | BinomialCoefficient bc = new BinomialCoefficient();
26 | System.out.print(bc.calculate(8, 3));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/interview/number/ConvertToBaseN.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | public class ConvertToBaseN {
4 |
5 | int baseN(int num,int base){
6 | if(base > 10){
7 | throw new IllegalArgumentException();
8 | }
9 | int result =0;
10 | int pow = 1;
11 | while(num > 0){
12 | result += pow*(num%base);
13 | pow = pow*10;
14 | num /= base;
15 | }
16 | return result;
17 | }
18 |
19 | public static void main(String args[]){
20 | ConvertToBaseN ctb = new ConvertToBaseN();
21 | System.out.println(ctb.baseN(13, 9));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/interview/number/CountNoOf2s.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * 150 qs 18.4
5 | */
6 | public class CountNoOf2s {
7 |
8 | public int count2s(int n){
9 | if(n < 2){
10 | return 0;
11 | }else if(n <= 9){
12 | return 1;
13 | }
14 | int pow = 1;
15 | while(pow <= n){
16 | pow *= 10;
17 | }
18 | pow = pow/10;
19 |
20 | if(n/pow == 2){
21 | //e.g 2105 becomes 1 + 105 + count2s(105) + count2s(1999)
22 | return 1 + n%pow + count2s(n%pow) + count2s((n/pow)*pow -1);
23 | }else{
24 | //e.g 3856 becomes 1000*count2s(3) + count2s(856) + 3*counts(999)
25 | return pow*count2s(n/pow) + count2s(n%pow) + (n/pow)*count2s(pow-1);
26 | }
27 | }
28 |
29 | public static void main(String args[]){
30 | CountNoOf2s cn2 = new CountNoOf2s();
31 | System.out.println(cn2.count2s(255));
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/interview/number/CountNumbersNotIncluding4.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/count-numbers-that-dont-contain-3/
5 | */
6 | public class CountNumbersNotIncluding4 {
7 |
8 | public int count(int n){
9 | if(n < 4){
10 | return n;
11 | }
12 | if( n >=4 && n <=10){
13 | return n-1;
14 | }
15 |
16 | int pow = 1;
17 | while(n/pow > 9){
18 | pow = pow*10;
19 | }
20 |
21 | int msd = n/pow;
22 | if(msd == 4){
23 | return count(msd*pow -1);
24 | }else{
25 | //suppose number is 276. So this becomes count(2)*count(99) +
26 | //count(2) + count(76)
27 | //reason we split this way rather than count(2)*count(100) is because
28 | //count(100) can go into infinite loop
29 | return count(msd)*count(pow-1) + count(msd) + count(n%pow);
30 | }
31 | }
32 |
33 | public static void main(String args[]){
34 | CountNumbersNotIncluding4 cn = new CountNumbersNotIncluding4();
35 | int c = cn.count(44);
36 | System.out.print(c);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/interview/number/EuclideanAlgoForGCD.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * GCD greatest common divisor
5 | * Co prime numbers if GCD of both the numbers is 1
6 | */
7 | public class EuclideanAlgoForGCD {
8 |
9 | public int gcd(int num1, int num2){
10 | if(num1 > num2){
11 | int temp = num1;
12 | num1 = num2;
13 | num2 = temp;
14 | }
15 | while(num1 != 0){
16 | int temp = num1;
17 | num1 = num2 % num1;
18 | num2 = temp;
19 | }
20 | return num2;
21 | }
22 |
23 | /**
24 | * assumption that num1 is less than num2 as initial parameter
25 | */
26 | public int gcdRec(int num1, int num2){
27 | if(num1 == 0){
28 | return num2;
29 | }
30 | return gcdRec(num2%num1, num1);
31 | }
32 |
33 | public static void main(String args[]){
34 | EuclideanAlgoForGCD ea = new EuclideanAlgoForGCD();
35 | int gcd = ea.gcd(956,1044);
36 | if(gcd == 1){
37 | System.out.println("Co prime numbers");
38 | }else{
39 | System.out.println("No coprime numbers " + gcd);
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/interview/number/LuckyNumbers.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/lucky-numbers/
5 | */
6 | public class LuckyNumbers {
7 |
8 | public boolean isLuck(int n,int counter){
9 | if(n < counter){
10 | return true;
11 | }
12 | if(n % counter == 0){
13 | return false;
14 | }
15 |
16 | return isLuck( n - n/counter,counter+1);
17 | }
18 |
19 | public static void main(String args[]){
20 | LuckyNumbers ln = new LuckyNumbers();
21 | System.out.println(ln.isLuck(19, 2));
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/interview/number/NBy2PairSumToK.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * Write a program to determine whether n/2 distinctive pairs can be formed
5 | * from given n integers where n is even and each pair's sum is divisible by given k.
6 | * Numbers cannot be repeated in the pairs, that means only you can form total n/2 pairs.
7 | */
8 | public class NBy2PairSumToK {
9 |
10 | //assuming input is from 1 to n. If input can contain 0 special logic will be needed
11 | //to handle that.
12 | public boolean pair(int input[],int k){
13 | int count[] = new int[k];
14 | for(int i=0; i < input.length; i++){
15 | count[input[i]%k]++;
16 | }
17 |
18 | if(count[0]%2 != 0){
19 | return false;
20 | }
21 | if(k%2==0){
22 | if(count[k/2]%2 != 0){
23 | return false;
24 | }
25 | }
26 | for(int i=1; i <= k/2; i++){
27 | if(count[i] != count[k-i]){
28 | return false;
29 | }
30 | }
31 | return true;
32 | }
33 |
34 | public static void main(String args[]){
35 | int input[] = {5,7,6,8,2,6,10,4};
36 | NBy2PairSumToK nb = new NBy2PairSumToK();
37 | System.out.println(nb.pair(input, 6));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/number/NotIncluding4.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * http://saikatd.wordpress.com/author/saikatd/page/4/
5 | * In a number system where 4 is not there, how do you convert such a number system to decimal
6 | * Here basically we have base 9 and convert it to base 10. Just be careful when you convert
7 | * anything from 5 to 9 because they are basically 4 to 8 in base 9 system. So subtract them
8 | * by 1 when doing multiplications.
9 | */
10 | public class NotIncluding4 {
11 |
12 | public int number(int chinaNumber){
13 |
14 | int result = 0;
15 | int mul = 1;
16 | while(chinaNumber > 0){
17 | int r = chinaNumber % 10;
18 | chinaNumber /= 10;
19 | if(r == 4){
20 | throw new IllegalArgumentException();
21 | }
22 | if(r >=5){
23 | r--;
24 | }
25 | result += r*mul;
26 | mul = mul*9;
27 | }
28 | return result;
29 | }
30 |
31 | public static void main(String args[]){
32 | NotIncluding4 ni = new NotIncluding4();
33 | System.out.print(ni.number(16));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/interview/number/RussianPeasantMultiplication.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/fast-multiplication-method-without-using-multiplication-operator-russian-peasants-algorithm/
5 | * Test cases
6 | * Division by 0
7 | * Negative numbers
8 | */
9 | public class RussianPeasantMultiplication {
10 |
11 | public int multiply(int a,int b){
12 | int res = 0;
13 | while(b > 0){
14 | if(b % 2 != 0){
15 | res += a;
16 | }
17 | a = a<<1;
18 | b = b>>1;
19 | }
20 | return res;
21 | }
22 |
23 | public static void main(String args[]){
24 | RussianPeasantMultiplication rpm = new RussianPeasantMultiplication();
25 | System.out.println(rpm.multiply(7, 13));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/com/interview/number/SquareRoot.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * Babylonian method for calculating square root
5 | */
6 | public class SquareRoot {
7 |
8 | double findRoot(int num){
9 | double start =0;
10 | double end = num;
11 | while(Math.abs(start - end) > 0.01){
12 | end = (start + end)/2;
13 | start = num/end;
14 | }
15 |
16 | return end;
17 | }
18 |
19 | public static void main(String args[]){
20 | SquareRoot sr = new SquareRoot();
21 | System.out.println(sr.findRoot(144));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/interview/number/StrobogrammaticNumber.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
5 | * https://leetcode.com/problems/strobogrammatic-number/
6 | */
7 | public class StrobogrammaticNumber {
8 | public boolean isStrobogrammatic(String num) {
9 |
10 | for (int i = 0; i <= num.length()/2; i++) {
11 | char ch1 = num.charAt(i);
12 | char ch2 = num.charAt(num.length() - i - 1);
13 |
14 | if (ch1 != ch2) {
15 | if ((ch1 != '9' || ch2 != '6') && (ch1 != '6' || ch2 != '9')) {
16 | return false;
17 | }
18 | } else {
19 | if (ch1 != '0' && ch1 != '1' && ch1 != '8') {
20 | return false;
21 | }
22 | }
23 | }
24 | return true;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/interview/number/Trailing0sinFactorial.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | /**
4 | * 150qs hard section
5 | * lets consider 625. First we divide 625 by 5 and that takes care of one 5
6 | * till 625. Then we divide 625 with 25 and that takes care of numbers with 2
7 | * 5s. We keep doing this till divisor becomes greater than number.
8 | */
9 | public class Trailing0sinFactorial {
10 |
11 | public int trailing0s(int num){
12 | int pow = 5;
13 | int count = 0;
14 | while(pow <= num){
15 | count += num/pow;
16 | pow *= 5;
17 | }
18 | return count;
19 | }
20 |
21 | public static void main(String args[]){
22 | Trailing0sinFactorial t0 = new Trailing0sinFactorial();
23 | System.out.println(t0.trailing0s(625));
24 | System.out.println(t0.trailing0s(146));
25 | System.out.println(t0.trailing0s(1046));
26 | System.out.println(t0.trailing0s(4617));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/interview/number/UniquePartitionOfInteger.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * http://www.geeksforgeeks.org/generate-unique-partitions-of-an-integer/
8 | * Test cases:
9 | * 0 or negative number
10 | */
11 | public class UniquePartitionOfInteger {
12 |
13 | public void partition(int n){
14 | List result = new ArrayList();
15 | partition(n,n,result);
16 | }
17 |
18 | private void partition(int n, int max,List result){
19 | if(n < 0){
20 | return ;
21 | }
22 | if(n == 0){
23 | result.forEach(i -> System.out.print(i + " "));
24 | System.out.println();
25 | return;
26 | }
27 | for(int i=Math.min(n, max); i > 0 && i <= max; i--){
28 | result.add(i);
29 | partition(n-i,i, result);
30 | result.remove(result.size()-1);
31 | }
32 | }
33 |
34 | public static void main(String args[]){
35 | UniquePartitionOfInteger upi = new UniquePartitionOfInteger();
36 | upi.partition(12);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/interview/playground/TestInnerClass.java:
--------------------------------------------------------------------------------
1 | package com.interview.playground;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * Created by tushar_v_roy on 5/18/16.
7 | */
8 | public class TestInnerClass {
9 |
10 | int t = 20;
11 | Random random;
12 | public Okay test() {
13 | final int r = 10;
14 | return
15 | random::nextInt;
16 |
17 | }
18 |
19 | public void test1() {
20 | random = new Random();
21 | Okay o1 = test();
22 | System.out.print(o1.next());
23 | Okay o2 = test();
24 | random = null;
25 | System.out.print(o2.next());
26 | }
27 |
28 | public static void main(String args[]) {
29 | TestInnerClass testInnerClass = new TestInnerClass();
30 | testInnerClass.test1();
31 | }
32 | }
33 |
34 | interface Okay {
35 | int next();
36 | }
37 |
--------------------------------------------------------------------------------
/src/com/interview/random/Rand7UsingRand5.java:
--------------------------------------------------------------------------------
1 | package com.interview.random;
2 |
3 | public class Rand7UsingRand5 {
4 |
5 | public int rand7(){
6 | int r = (rand5()-1)*5 + rand5();
7 | while(r > 21){ // I just need to ignore [22, 25]
8 | r = (rand5()-1)*5 + rand5();
9 | }
10 | return (r%7) + 1;
11 | }
12 |
13 | private int rand5(){
14 | return (int)(Math.ceil(Math.random()*5));
15 | }
16 |
17 | public static void main(String args[]){
18 | Rand7UsingRand5 rr = new Rand7UsingRand5();
19 | for(int i=0; i < 10; i++){
20 | System.out.print(rr.rand7());
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/interview/random/RandomCountrySelectionByPopluation.java:
--------------------------------------------------------------------------------
1 | package com.interview.random;
2 |
3 | public class RandomCountrySelectionByPopluation {
4 |
5 | public int getRandom(int []arr){
6 | int sum[] = new int[arr.length];
7 | sum[0] = arr[0];
8 | int n = arr[0];
9 | for(int i=1; i < sum.length; i++){
10 | sum[i] = sum[i-1] + arr[i];
11 | n += arr[i];
12 | }
13 |
14 | int ran = (int)(Math.random()*n + 1);
15 |
16 | int low = 0;
17 | int high = arr.length-1;
18 | int mid = (high + low)/2;
19 | while(true){
20 | if(sum[mid] >= ran && (mid-1 == -1 || sum[mid-1] < ran)){
21 | break;
22 | }
23 | if(sum[mid] > ran){
24 | high = mid-1;
25 | }else{
26 | low = mid+1;
27 | }
28 | mid = (high + low)/2;
29 | }
30 | return mid;
31 | }
32 |
33 | public static void main(String args[]){
34 |
35 | RandomCountrySelectionByPopluation rcsp = new RandomCountrySelectionByPopluation();
36 | int arr[] = {5,5,2,3,7,1};
37 | for(int i=0; i < 10; i++){
38 | System.out.print(rcsp.getRandom(arr));
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/interview/random/SelectMRandomNumbersInStream.java:
--------------------------------------------------------------------------------
1 | package com.interview.random;
2 |
3 | /**
4 | * Reservoir Sampling
5 | * 150qs 18.3
6 | */
7 | public class SelectMRandomNumbersInStream {
8 |
9 | public int[] selectRandom(int arr[],int m){
10 | int result[] = new int[m];
11 | for(int i=0; i < m ;i++){
12 | result[i] = arr[i];
13 | }
14 |
15 | for(int i=m ; i < arr.length; i++){
16 | int random = (int)(Math.random()*i) + 1;
17 | if(random <= m){
18 | result[random-1] = arr[i];
19 | }
20 | }
21 | return result;
22 | }
23 |
24 | public static void main(String args[]){
25 | SelectMRandomNumbersInStream srn = new SelectMRandomNumbersInStream();
26 | int arr[] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
27 | int result[] = srn.selectRandom(arr, 5);
28 | for(int i=0; i < result.length; i++){
29 | System.out.print(result[i] + " ");
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/random/ShuffleArray.java:
--------------------------------------------------------------------------------
1 | package com.interview.random;
2 |
3 | /**
4 | * Shuffle deck of cards
5 | * 150 qs 18.2
6 | */
7 | public class ShuffleArray {
8 |
9 | public void shuffle(int arr[]){
10 | for(int i=arr.length-1; i>=0; i--){
11 | int random = (int)(Math.random()*(i+1)) ;
12 | System.out.print(random + " ");
13 | swap(arr,random,i);
14 | }
15 | }
16 |
17 | private void swap(int arr[],int a,int b){
18 | int temp = arr[a];
19 | arr[a] = arr[b];
20 | arr[b] = temp;
21 | }
22 |
23 | public static void main(String args[]){
24 | int arr[] = {1,2,3,4,5,6,7,8};
25 | ShuffleArray sa = new ShuffleArray();
26 | sa.shuffle(arr);
27 | System.out.println();
28 | for(int i=0; i < arr.length; i++){
29 | System.out.print(arr[i] + " ");
30 | }
31 |
32 | for(int i=0; i < arr.length; i++){
33 | System.out.println((int)(Math.random()*10) + 1);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/com/interview/recursion/AllAdjacentCombination.java:
--------------------------------------------------------------------------------
1 | package com.interview.recursion;
2 |
3 | /**
4 | * Generate all combination of size k and less of adjacent numbers
5 | * e.g 1,2,3,4 k = 2
6 | * 1 2 3 4
7 | * 12 3 4
8 | * 1 23 4
9 | * 1 2 3 34
10 | * 12 34
11 | * @author tusroy
12 | *
13 | */
14 | public class AllAdjacentCombination {
15 |
16 | public void combination(int input[],int result[],int k,int pos,int r){
17 |
18 | if(pos == input.length){
19 | for(int i=0; i < r ; i++){
20 | System.out.print(result[i] + " ");
21 | }
22 | System.out.println();
23 | return;
24 | }
25 | for(int i=pos; i < pos + k && i < input.length; i++ ){
26 | result[r] = formNumber(input,pos,i);
27 | combination(input,result,k,i+1,r+1);
28 | }
29 | }
30 |
31 | private int formNumber(int input[], int start, int end){
32 | int num = 0;
33 | for(int i=start; i <=end; i++){
34 | num = num*10 + input[i];
35 | }
36 | return num;
37 | }
38 |
39 | public static void main(String args[]){
40 | AllAdjacentCombination adc = new AllAdjacentCombination();
41 | int input[] = {1,2,3,4,5};
42 | int result[] = new int[input.length];
43 | adc.combination(input,result,3,0,0);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/com/interview/recursion/CombinationOfSizeK.java:
--------------------------------------------------------------------------------
1 | package com.interview.recursion;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/
5 | */
6 | public class CombinationOfSizeK {
7 |
8 | public void combination(int arr[],int k){
9 | int result[] = new int[k];
10 | combinationUtil(arr,k,0,result,0);
11 | }
12 |
13 | private void combinationUtil(int arr[],int k, int pos,int result[],int start){
14 | if(pos == k){
15 | for(int i=0; i < k; i++){
16 | System.out.print(result[i] + " ");
17 | }
18 | System.out.print("\n");
19 | return;
20 | }
21 | for(int i=start; i < arr.length; i++){
22 | result[pos] = arr[i];
23 | combinationUtil(arr,k,pos+1,result,i+1);
24 | }
25 | }
26 |
27 | public static void main(String args[]){
28 | CombinationOfSizeK kk = new CombinationOfSizeK();
29 | int arr[] = {1,2,3,4};
30 | kk.combination(arr, 2);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/recursion/CombinationWithStar.java:
--------------------------------------------------------------------------------
1 | package com.interview.recursion;
2 |
3 | /**
4 | * e.g a, b c
5 | * * * *
6 | * a * *
7 | * a b *
8 | * a b c
9 | * * b *
10 | * * b c
11 | * * * c
12 | *
13 | * Idea is to store the index of values in used[] array. So just
14 | * like regular combination if used is set print it else print *
15 | */
16 | public class CombinationWithStar {
17 |
18 | public void combine(char input[], int pos, boolean used[]){
19 | printArray(input, used);
20 | for(int i= pos; i < input.length; i++){
21 | used[i] = true;
22 | combine(input, i+1, used);
23 | used[i] = false;
24 | }
25 | }
26 |
27 | private void printArray(char result[], boolean used[]){
28 | for(int i=0; i < used.length; i++){
29 | if(used[i]){
30 | System.out.print(result[i] + " ");
31 | }else{
32 | System.out.print("* ");
33 | }
34 | }
35 | System.out.println();
36 | }
37 |
38 | public static void main(String args[]){
39 | char input[] = {'a','b','c','d'};
40 | CombinationWithStar cws = new CombinationWithStar();
41 | boolean used[] = new boolean[input.length];
42 | cws.combine(input, 0, used);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/interview/recursion/PrintAllPathFromTopLeftToBottomRight.java:
--------------------------------------------------------------------------------
1 | package com.interview.recursion;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | http://www.geeksforgeeks.org/print-all-possible-paths-from-top-left-to-bottom-right-of-a-mxn-matrix/
7 | */
8 | public class PrintAllPathFromTopLeftToBottomRight {
9 |
10 |
11 | public void print(int arr[][],int row, int col,int result[],int pos){
12 | if(row == arr.length-1 && col == arr[0].length-1){
13 | result[pos] = arr[row][col];
14 | System.out.println(Arrays.toString(result));
15 | return;
16 | }
17 | if(row >= arr.length || col >= arr[0].length){
18 | return;
19 | }
20 |
21 | result[pos] = arr[row][col];
22 | print(arr,row,col+1,result,pos+1);
23 | print(arr,row+1,col,result,pos+1);
24 | }
25 |
26 | public static void main(String args[]){
27 | PrintAllPathFromTopLeftToBottomRight pam = new PrintAllPathFromTopLeftToBottomRight();
28 | int arr[][] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
29 | int result[] = new int[arr.length + arr[0].length-1];
30 | pam.print(arr, 0, 0, result,0);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/recursion/PrintAllSubsequence.java:
--------------------------------------------------------------------------------
1 | package com.interview.recursion;
2 |
3 | /**
4 | * Date 02/25/2016
5 | * @author Tushar Roy
6 | *
7 | * Print all subsequence of a given array.
8 | *
9 | * Time complexity is exponential
10 | * Space complexity is O(n)
11 | */
12 | public class PrintAllSubsequence {
13 | public void print(int[] input) {
14 | int[] output = new int[input.length];
15 | for (int i = 0; i < input.length; i++) {
16 | output[0] = input[i];
17 | print(input, output, 1, i + 1, true);
18 | }
19 | }
20 |
21 | private void print(int[] input, int[] output, int len, int current, boolean print) {
22 |
23 | if (print) {
24 | for (int i = 0; i < len; i++) {
25 | System.out.print(output[i] + " ");
26 | }
27 | System.out.println();
28 | }
29 | if (current == input.length) {
30 | return;
31 | }
32 |
33 |
34 | output[len] = input[current];
35 | print(input, output, len + 1, current + 1, true);
36 | print(input, output, len, current + 1, false);
37 | }
38 |
39 | public static void main(String args[]) {
40 | PrintAllSubsequence ps = new PrintAllSubsequence();
41 | int[] input = {1, 2, 3, 4};
42 | ps.print(input);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/interview/recursion/StringInterleaving.java:
--------------------------------------------------------------------------------
1 | package com.interview.recursion;
2 |
3 | public class StringInterleaving {
4 |
5 | private void printArray(char[] str){
6 | for(int i=0; i < str.length; i++){
7 | System.out.print(str[i]);
8 | }
9 | System.out.println();
10 | }
11 |
12 | public void interleaving(char[] str1,char[] str2,int len1,int len2,int current, char []result){
13 |
14 | if(current == result.length){
15 | printArray(result);
16 | return;
17 | }
18 |
19 | if(len1 < str1.length){
20 | result[current] = str1[len1];
21 | interleaving(str1, str2, len1+1, len2, current+1, result);
22 | }
23 | if(len2 < str2.length){
24 | result[current] = str2[len2];
25 | interleaving(str1,str2,len1,len2+1,current+1,result);
26 | }
27 | }
28 |
29 | public static void main(String args[]){
30 |
31 | StringInterleaving si = new StringInterleaving();
32 | String str1 ="AB";
33 | String str2 = "CDE";
34 | char[] result = new char[str1.length() + str2.length()];
35 | si.interleaving(str1.toCharArray(), str2.toCharArray(), 0, 0, 0, result);
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/interview/recursion/StringPermutationRotation.java:
--------------------------------------------------------------------------------
1 | package com.interview.recursion;
2 |
3 | public class StringPermutationRotation {
4 |
5 | private void swap(char arr[],int i, int j){
6 | char temp = arr[i];
7 | arr[i] = arr[j];
8 | arr[j] =temp;
9 | }
10 |
11 | private void printArray(char str[]){
12 | for(int i=0; i< str.length; i++){
13 | System.out.print(str[i]);
14 | }
15 | System.out.print("\n");
16 | }
17 |
18 | public void permute(char[] str,int pos){
19 | if(pos == str.length){
20 | printArray(str);
21 | return;
22 | }
23 | for(int i=pos; i < str.length; i++){
24 | swap(str,pos,i);
25 | permute(str,pos+1);
26 | swap(str,pos,i);
27 | }
28 | }
29 |
30 | public static void main(String args[]){
31 | String str = "ABC";
32 | StringPermutationRotation sp = new StringPermutationRotation();
33 | sp.permute(str.toCharArray(),0);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/interview/regex/MultiSpaceReplacement.java:
--------------------------------------------------------------------------------
1 | package com.interview.regex;
2 |
3 | import java.util.regex.Matcher;
4 | import java.util.regex.Pattern;
5 |
6 | public class MultiSpaceReplacement {
7 |
8 | public void replace(String str){
9 | Pattern pattern = Pattern.compile("^ +| +| +$");
10 | Matcher matcher = pattern.matcher(str);
11 | System.out.println(matcher.replaceAll(""));
12 |
13 | }
14 |
15 | public static void main(String args[]){
16 | String str = " This is Tushar Roy ";
17 | MultiSpaceReplacement mrs = new MultiSpaceReplacement();
18 | mrs.replace(str);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/interview/sort/Sort0toN3.java:
--------------------------------------------------------------------------------
1 | package com.interview.sort;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/sort-n-numbers-range-0-n2-1-linear-time/
5 | */
6 | public class Sort0toN3 {
7 |
8 | public void sort(int arr[],int n){
9 |
10 | sort(arr,n,1);
11 | sort(arr,n,n);
12 | sort(arr,n,n*n);
13 | }
14 |
15 | private void sort(int arr[],int n, int exp){
16 | int count[] = new int[n];
17 | for(int i=0; i < arr.length;i++){
18 | count[(arr[i]/exp)%n]++;
19 | }
20 |
21 | for(int i=1; i < arr.length; i++){
22 | count[i] += count[i-1];
23 | }
24 |
25 | int output[] = new int[n];
26 |
27 | for(int i=arr.length-1;i>=0; i--){
28 | output[count[(arr[i]/exp)%n]-1] = arr[i];
29 | count[(arr[i]/exp)%n]--;
30 | }
31 | for(int i=0; i < arr.length; i++){
32 | arr[i] = output[i];
33 | }
34 | }
35 |
36 | public static void main(String args[]){
37 | int arr[] = {100,2,124,18,36};
38 | Sort0toN3 sn = new Sort0toN3();
39 | sn.sort(arr,arr.length);
40 | for(int i=0; i < arr.length; i++){
41 | System.out.print(arr[i] + " ");
42 | }
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/src/com/interview/stackqueue/RealTimeCounter.java:
--------------------------------------------------------------------------------
1 | package com.interview.stackqueue;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 |
6 | public class RealTimeCounter {
7 |
8 | private Queue secQueue = new LinkedList();
9 | private long secCount;
10 |
11 | public void add(long currentTimeInMills){
12 | while(secQueue.size() > 0 && currentTimeInMills - 1000 > secQueue.peek()){
13 | secCount--;
14 | secQueue.poll();
15 | }
16 |
17 | secCount++;
18 | secQueue.offer(currentTimeInMills);
19 | }
20 |
21 | public long getCallsInLastSec(long currentTimeInMills){
22 | while(secQueue.size() > 0 && currentTimeInMills - 1000 > secQueue.peek()){
23 | secCount--;
24 | secQueue.poll();
25 | }
26 | return secCount;
27 | }
28 |
29 | public static void main(String args[]){
30 | RealTimeCounter rtc = new RealTimeCounter();
31 | rtc.add(100);
32 | rtc.add(300);
33 | rtc.add(550);
34 | System.out.println(rtc.getCallsInLastSec(780));
35 | System.out.println(rtc.getCallsInLastSec(1280));
36 | rtc.add(1540);
37 | System.out.println(rtc.getCallsInLastSec(1551));
38 | rtc.add(1570);
39 | System.out.println(rtc.getCallsInLastSec(2651));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/interview/string/CycleLeaderIteration.java:
--------------------------------------------------------------------------------
1 | package com.interview.string;
2 |
3 | public class CycleLeaderIteration {
4 |
5 | //assumption that size is going to be 3^k +1 from start to end
6 | public void iterate(char str[],int start,int end){
7 | int len = end - start +1;
8 | int power = 1;
9 | while(power < len){
10 | int index = power;
11 | int newIndex = -1;
12 | char temp = str[start+index];
13 | char temp1;
14 | while(newIndex != power){
15 | if(index % 2 ==0){
16 | newIndex = index/2;
17 | }else{
18 | newIndex = len/2 + index/2;
19 | }
20 | temp1 = str[start + newIndex];
21 | str[start+newIndex] = temp;
22 | temp = temp1;
23 | index = newIndex;
24 | }
25 | power = power*3;
26 | }
27 | }
28 |
29 | public static void main(String args[]){
30 | String str = "1a2b3c4d5e6f7g8h9iAjBkClDmEn";
31 | char[] str1 = str.toCharArray();
32 | CycleLeaderIteration cli = new CycleLeaderIteration();
33 | cli.iterate(str1, 0, str1.length);
34 | for(char ch: str1){
35 | System.out.print(ch + " ");
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/string/GroupAnagramsTogether.java:
--------------------------------------------------------------------------------
1 | package com.interview.string;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * https://leetcode.com/problems/anagrams/
7 | */
8 | public class GroupAnagramsTogether {
9 | public List> groupAnagrams(String[] strs) {
10 | if (strs == null || strs.length == 0)
11 | return new ArrayList>();
12 |
13 | int listIndex = 0;
14 | List> result = new ArrayList<>();
15 | Map anagramGroup = new HashMap<>();
16 |
17 | for (String str : strs) {
18 | char[] chars = str.toCharArray();
19 | Arrays.sort(chars);
20 | String sorted = new String(chars);
21 | if (anagramGroup.containsKey(sorted)) {
22 | int index = anagramGroup.get(sorted);
23 | List listResult = result.get(index);
24 | listResult.add(str);
25 | } else {
26 | List resultList = new ArrayList<>();
27 | resultList.add(str);
28 | result.add(listIndex, resultList);
29 | anagramGroup.put(sorted, listIndex);
30 | listIndex++;
31 | }
32 | }
33 | return result;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/interview/string/LexicographicRankInPermutation.java:
--------------------------------------------------------------------------------
1 | package com.interview.string;
2 |
3 | public class LexicographicRankInPermutation {
4 |
5 | //you can create a AVL tree to efficiently find total
6 | //number of smaller characters.
7 | //You can keep size of subtree at root and keep moving left or right
8 | //depending on the character you looking for
9 | private int findNumberOfSmallerCharactersOnRight(int index,char []str){
10 | int count=0;
11 | for(int i=index+1; i < str.length; i++){
12 | if(str[i] < str[index]){
13 | count++;
14 | }
15 | }
16 | return count;
17 | }
18 |
19 | private int factorial(int n){
20 | int fact = 1;
21 | for(int i =1; i <=n; i++){
22 | fact = i*fact;
23 | }
24 | return fact;
25 | }
26 |
27 | public int rank(char []str){
28 |
29 | int rank =0;
30 | for(int i=0; i < str.length;i++){
31 | int num = findNumberOfSmallerCharactersOnRight(i, str);
32 | rank += factorial(str.length -i-1)*num;
33 | }
34 | return rank+1;
35 |
36 | }
37 |
38 | public static void main(String args[]){
39 | LexicographicRankInPermutation lrp = new LexicographicRankInPermutation();
40 | int rank = lrp.rank("STRING".toCharArray());
41 | System.out.println(rank);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/interview/string/RemoveConsecutiveDuplicate.java:
--------------------------------------------------------------------------------
1 | package com.interview.string;
2 |
3 | /**
4 | * Remove consecutive duplicate characters
5 | * e.g
6 | * AABBCDDAAB -> ABCDAB
7 | * ABBBCCD -> ABCD
8 | * Test cases
9 | * Empty string
10 | * all unique
11 | * all duplicates
12 | * duplicates at certain different places
13 | */
14 | public class RemoveConsecutiveDuplicate {
15 |
16 | public int removeDuplicates(char input[]){
17 | int slow = 0;
18 | int fast = 0;
19 | int index = 0;
20 | while(fast < input.length){
21 | while(fast < input.length && input[slow] == input[fast]){
22 | fast++;
23 | }
24 | input[index++] = input[slow];
25 | slow = fast;
26 | }
27 | return index;
28 | }
29 |
30 | public static void main(String args[]){
31 | String str = "AAABBCCDDDEFGH";
32 | char input[] = str.toCharArray();
33 | RemoveConsecutiveDuplicate rcd = new RemoveConsecutiveDuplicate();
34 | int len = rcd.removeDuplicates(input);
35 | for(int i=0; i < len; i++){
36 | System.out.print(input[i] + " ");
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/string/ValidPalindrome.java:
--------------------------------------------------------------------------------
1 | package com.interview.string;
2 |
3 | /**
4 | * Date 04/09/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
8 | * For example,
9 | * "A man, a plan, a canal: Panama" is a palindrome.
10 | * "race a car" is not a palindrome.
11 | *
12 | * https://leetcode.com/problems/valid-palindrome/
13 | */
14 | public class ValidPalindrome {
15 | public boolean isPalindrome(String s) {
16 | int start = 0;
17 | int end = s.length() - 1;
18 | while (start < end) {
19 | if (!isAlphaNum(s.charAt(start))) {
20 | start++;
21 | } else if (!isAlphaNum(s.charAt(end))) {
22 | end--;
23 | } else {
24 | if (Character.toLowerCase(s.charAt(start++)) != Character.toLowerCase(s.charAt(end--))) {
25 | return false;
26 | }
27 | }
28 | }
29 | return true;
30 | }
31 |
32 | private boolean isAlphaNum(char ch) {
33 | if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
34 | return true;
35 | }
36 | return false;
37 | }
38 | }
--------------------------------------------------------------------------------
/src/com/interview/tree/AddGreaterValueNodeToEveryNode.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/add-greater-values-every-node-given-bst/
5 | * Test cases:
6 | * Empty tree
7 | * One node tree
8 | * Two node tree
9 | */
10 |
11 | class IntegerRef{
12 | int val;
13 | }
14 |
15 | public class AddGreaterValueNodeToEveryNode {
16 |
17 | public void add(Node root,IntegerRef ref){
18 | if(root == null){
19 | return ;
20 | }
21 | add(root.right,ref);
22 | root.data += ref.val;
23 | ref.val = root.data;
24 | add(root.left,ref);
25 | }
26 |
27 | public static void main(String args[]){
28 | BinaryTree bt = new BinaryTree();
29 | Node root = null;
30 | root = bt.addNode(10, root);
31 | root = bt.addNode(5, root);
32 | root = bt.addNode(20, root);
33 | root = bt.addNode(15, root);
34 | root = bt.addNode(25, root);
35 | AddGreaterValueNodeToEveryNode agv = new AddGreaterValueNodeToEveryNode();
36 | IntegerRef ir = new IntegerRef();
37 | ir.val = 0;
38 | agv.add(root, ir);
39 | TreeTraversals tt = new TreeTraversals();
40 | tt.inOrder(root);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/interview/tree/BSTOneChildPreOrderTraversal.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/check-if-each-internal-node-of-a-bst-has-exactly-one-child/
5 | */
6 | public class BSTOneChildPreOrderTraversal {
7 |
8 | public boolean isBST(int input[]){
9 | int max = Integer.MAX_VALUE;
10 | int min = Integer.MIN_VALUE;
11 | for(int i = 0; i < input.length-1; i++){
12 | if(input[i] > min && input[i] < max){
13 | if(input[i+1] < input[i]){
14 | max = input[i];
15 | }else{
16 | min = input[i];
17 | }
18 | }else{
19 | return false;
20 | }
21 | }
22 | if(input[input.length-1] < max && input[input.length-1] > min){
23 | return true;
24 | }else{
25 | return false;
26 | }
27 | }
28 |
29 | public static void main(String args[]){
30 | int input[] = {20,10,14,15,17};
31 | BSTOneChildPreOrderTraversal boc = new BSTOneChildPreOrderTraversal();
32 | System.out.println(boc.isBST(input));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/interview/tree/BinaryTreeMaximumPathSum.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 03/22/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes
8 | * from some starting node to any node in the tree along the parent-child connections.
9 | *
10 | * Time complexity O(n)
11 | * Space complexity depends on depth of tree.
12 | *
13 | * https://leetcode.com/problems/binary-tree-maximum-path-sum/
14 | */
15 | public class BinaryTreeMaximumPathSum {
16 | int max = 0;
17 |
18 | public int maxPathSum(Node root) {
19 | max = Integer.MIN_VALUE;
20 | maxPathSumUtil(root);
21 | return max;
22 | }
23 |
24 | private int maxPathSumUtil(Node root) {
25 | if (root == null) {
26 | return 0;
27 | }
28 | int left = maxPathSumUtil(root.left);
29 | int right = maxPathSumUtil(root.right);
30 | if (left < 0) {
31 | left = 0;
32 | }
33 | if (right < 0) {
34 | right = 0;
35 | }
36 | max = Math.max(max, root.data + left + right);
37 | return root.data + Math.max(left, right);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/tree/ClosestValueBinaryTree.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
5 | * https://leetcode.com/problems/closest-binary-search-tree-value/
6 | */
7 | public class ClosestValueBinaryTree {
8 | public int closestValue(Node root, double target) {
9 | int r = target > 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
10 | return closestValueUtil(root, target, r);
11 | }
12 |
13 | private int closestValueUtil(Node root, double target, int result) {
14 | if (root == null) {
15 | return (int)result;
16 | }
17 | if (target == root.data) {
18 | return root.data;
19 | }
20 | if (Math.abs(root.data - target) < Math.abs(result - target)) {
21 | result = root.data;
22 | }
23 | if (target < root.data) {
24 | return closestValueUtil(root.left, target, result);
25 | } else {
26 | return closestValueUtil(root.right, target, result);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/com/interview/tree/ConstructTreeFromInOrderPreOrder.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
5 | * Test cases:
6 | * Empty tree
7 | * One node tree
8 | * All left side tree
9 | * All right side tree
10 | * Mixed tree
11 | * Full tree
12 | * complete tree
13 | */
14 | public class ConstructTreeFromInOrderPreOrder {
15 |
16 | private int index = 0;
17 | public Node createTree(int inorder[],int preorder[]){
18 | Node result = createTree(inorder,preorder,0,inorder.length-1);
19 | index = 0;
20 | return result;
21 | }
22 |
23 | private Node createTree(int inorder[],int preorder[], int start, int end){
24 | if(start > end){
25 | return null;
26 | }
27 | int i;
28 | for(i=start; i <= end; i++){
29 | if(preorder[index] == inorder[i]){
30 | break;
31 | }
32 | }
33 | Node node = Node.newNode(preorder[index]);
34 | index++;
35 | node.left = createTree(inorder,preorder,start,i-1);
36 | node.right = createTree(inorder,preorder,i+1,end);
37 | return node;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/interview/tree/ContructTreeFromInorderPostOrder.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Given inorder and postorder traversal of a tree, construct the binary tree.
5 | *
6 | * https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
7 | */
8 | public class ContructTreeFromInorderPostOrder {
9 | public Node buildTree(int[] inorder, int[] postorder) {
10 | return buildTree(inorder, postorder, 0, inorder.length - 1, postorder.length - 1);
11 | }
12 |
13 | public Node buildTree(int[] inorder, int[] postorder, int start, int end, int index) {
14 | if (start > end) {
15 | return null;
16 | }
17 |
18 | int i;
19 | for (i = start; i <= end; i++) {
20 | if (postorder[index] == inorder[i]) {
21 | break;
22 | }
23 | }
24 |
25 | Node tn = Node.newNode(postorder[index]);
26 | tn.left = buildTree(inorder, postorder, start, i - 1, index - (end - i + 1));
27 | tn.right = buildTree(inorder, postorder, i + 1, end, index - 1);
28 | return tn;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/interview/tree/CountNodesCompleteTree.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 10/06/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a complete binary tree, count the number of nodes.
8 | *
9 | * Time complexity O(log(n) ^ 2)
10 | *
11 | * Reference
12 | * https://leetcode.com/problems/count-complete-tree-nodes/
13 | */
14 | public class CountNodesCompleteTree {
15 |
16 | public int countNodes(Node root) {
17 | if (root == null) {
18 | return 0;
19 | }
20 | int lh = leftHeight(root.left);
21 | int rh1 = rightHeight(root.left);
22 | int rh = rightHeight(root.right);
23 |
24 | if (lh == rh) {
25 | return (1< map = new HashMap<>();
12 | map.put(0, 1);
13 | return countPathSum(root, sum, map, 0);
14 | }
15 |
16 | private int countPathSum(Node root, int sum, Map map, int prefixSum) {
17 | if (root == null) {
18 | return 0;
19 | }
20 |
21 | prefixSum += root.data;
22 | int count = map.getOrDefault(prefixSum - sum,0);
23 | map.put(prefixSum, map.getOrDefault(prefixSum, 0) + 1);
24 | count += countPathSum(root.left, sum, map, prefixSum) + countPathSum(root.right, sum, map, prefixSum);
25 | map.put(prefixSum, map.getOrDefault(prefixSum, 1) - 1);
26 | return count;
27 | }
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/src/com/interview/tree/CountUnivalueTree.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 10/07/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a binary tree, count the number of uni-value subtrees.
8 | * A Uni-value subtree means all nodes of the subtree have the same value.
9 | *
10 | * https://leetcode.com/problems/count-univalue-subtrees/
11 | */
12 | public class CountUnivalueTree {
13 | private int count = 0;
14 | public int countUnivalSubtrees(Node root) {
15 | countUnivalSubtreesUtil(root, 0);
16 | return count;
17 | }
18 |
19 | private int countUnivalSubtreesUtil(Node root, int val) {
20 | if (root == null) {
21 | return val;
22 | }
23 | int left = countUnivalSubtreesUtil(root.left, root.data);
24 | int right = countUnivalSubtreesUtil(root.right, root.data);
25 | if (left == right && left == root.data) {
26 | count++;
27 | return root.data;
28 | } else {
29 | return Integer.MAX_VALUE;
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/interview/tree/HeightBalanced.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 10/06/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a binary tree, determine if it is height-balanced.
8 | *
9 | * Time complexity O(logn)
10 | *
11 | * Reference
12 | * https://leetcode.com/problems/balanced-binary-tree/
13 | */
14 | public class HeightBalanced {
15 | public boolean isBalanced(Node root) {
16 | return isBalancedUtil(root) >= 0;
17 | }
18 |
19 | private int isBalancedUtil(Node root) {
20 | if (root == null) {
21 | return 0;
22 | }
23 | int left = isBalancedUtil(root.left);
24 | if (left < 0) {
25 | return -1;
26 | }
27 | int right = isBalancedUtil(root.right);
28 | if (right < 0) {
29 | return -1;
30 | }
31 | int diff = Math.abs(left - right);
32 | return diff <= 1 ? (Math.max(left, right) + 1) : -1;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/interview/tree/InorderSuccessor.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 03/27/2016
5 | * @author Tushar Roy
6 | *
7 | * Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
8 | *
9 | * Time complexity O(h)
10 | * Space complexity O(h)
11 | *
12 | * https://leetcode.com/problems/inorder-successor-in-bst/
13 | */
14 | public class InorderSuccessor {
15 | public Node inorderSuccessor(Node root, Node p) {
16 | if (p.right != null) {
17 | p = p.right;
18 | while (p.left != null) {
19 | p = p.left;
20 | }
21 | return p;
22 | } else {
23 | return succ(root, p.data);
24 | }
25 | }
26 |
27 | private Node succ(Node root, int data) {
28 | if (root.data == data) {
29 | return null;
30 | }
31 | if (root.data < data) {
32 | return succ(root.right, data);
33 | } else {
34 | Node s = succ(root.left, data);
35 | return s == null ? root : s;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/com/interview/tree/LongestConsecutiveSequence.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Created by tushar_v_roy on 4/1/16.
5 | */
6 | public class LongestConsecutiveSequence {
7 | int max = 0;
8 | public int longestConsecutive(Node root) {
9 | if (root == null) {
10 | return 0;
11 | }
12 | max = 0;
13 | longestConsecutiveUtil(root, root.data - 1, 0);
14 | return max;
15 | }
16 |
17 | public void longestConsecutiveUtil(Node root, int prevData, int current) {
18 | if (root == null) {
19 | return;
20 | }
21 |
22 | if (root.data == prevData + 1) {
23 | current = current + 1;
24 | } else {
25 | current = 1;
26 | }
27 | max = Math.max(current, max);
28 | longestConsecutiveUtil(root.left, root.data, current);
29 | longestConsecutiveUtil(root.right, root.data, current);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/interview/tree/LowestCommonAncestorInBinaryTree.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 04/27/2016
5 | * @author Tushar Roy
6 | *
7 | * Find lowest common ancestor in binary tree.
8 | *
9 | * Time complexity O(n)
10 | * Space complexity O(h)
11 | */
12 | public class LowestCommonAncestorInBinaryTree {
13 |
14 | public Node lca(Node root, Node n1, Node n2){
15 | if(root == null){
16 | return null;
17 | }
18 | if(root == n1 || root == n2){
19 | return root;
20 | }
21 |
22 | Node left = lca(root.left, n1, n2);
23 | Node right = lca(root.right, n1, n2);
24 |
25 | if(left != null && right != null){
26 | return root;
27 | }
28 | return left != null ? left : right;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/interview/tree/LowestCommonAncestoryBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 05/04/2016
5 | * @author Tushar Roy
6 | *
7 | * Lowest common ancestor in binary search tree.
8 | *
9 | * Time complexity O(height of tree)
10 | * Space complexity O(height of tree)
11 | *
12 | * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
13 | */
14 | public class LowestCommonAncestoryBinarySearchTree {
15 |
16 | public Node lowestCommonAncestor(Node root, int p, int q) {
17 | if (root.data > Math.max(p, q)) {
18 | return lowestCommonAncestor(root.left, p, q);
19 | } else if (root.data < Math.min(p, q)) {
20 | return lowestCommonAncestor(root.right, p, q);
21 | } else {
22 | return root;
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/interview/tree/NodesWithNoSibling.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/print-nodes-dont-sibling-binary-tree/
5 | * This does not print root node even though it has no sibling
6 | * Test cases:
7 | * Null tree
8 | * Only one node tree
9 | * All left side tree
10 | * All right side tree
11 | * Regular mix tree
12 | */
13 | public class NodesWithNoSibling {
14 |
15 | public void printNodes(Node root){
16 | if(root == null){
17 | return;
18 | }
19 | if(root.left == null || root.right == null){
20 | if(root.left != null){
21 | System.out.print(root.left.data + " ");
22 | }
23 | if(root.right != null){
24 | System.out.print(root.right.data + " ");
25 | }
26 | }
27 | printNodes(root.left);
28 | printNodes(root.right);
29 | }
30 |
31 | public static void main(String args[]){
32 | BinaryTree bt = new BinaryTree();
33 | Node root = null;
34 | root = bt.addNode(10, root);
35 | root = bt.addNode(5, root);
36 | root = bt.addNode(-1, root);
37 | root = bt.addNode(-5, root);
38 | root = bt.addNode(20, root);
39 | root = bt.addNode(25, root);
40 | NodesWithNoSibling nws = new NodesWithNoSibling();
41 | nws.printNodes(root);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/com/interview/tree/SizeOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 03/05/2015
5 | * @author tusroy
6 | *
7 | * Given a root of binary tree, return size of binar tree
8 | *
9 | * Solution:
10 | * Recursively find size of left side, right side and add one to them and return that to calling function.
11 | *
12 | * Time complexity - O(n)
13 | * Space complexity(because of recursion stack) - height of binary tree. Worst case O(n)
14 | *
15 | * Test cases:
16 | * Null tree
17 | * 1 node tree
18 | * multi node tree
19 | */
20 | public class SizeOfBinaryTree {
21 |
22 | public int size(Node root){
23 | if(root == null){
24 | return 0;
25 | }
26 | return size(root.left) + size(root.right) + 1;
27 | }
28 |
29 | public static void main(String args[]){
30 | BinaryTree bt = new BinaryTree();
31 | Node head = null;
32 | head = bt.addNode(10, head);
33 | head = bt.addNode(15, head);
34 | head = bt.addNode(5, head);
35 | head = bt.addNode(7, head);
36 | head = bt.addNode(19, head);
37 | head = bt.addNode(20, head);
38 | head = bt.addNode(-1, head);
39 | SizeOfBinaryTree sbt = new SizeOfBinaryTree();
40 | System.out.println(sbt.size(head));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/interview/tree/SortedArrayToBST.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Date 10/06/2016
5 | * @author Tushar Roy
6 | *
7 | * Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
8 | *
9 | * Time complexity O(n)
10 | *
11 | * Reference
12 | * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
13 | */
14 | public class SortedArrayToBST {
15 | public Node sortedArrayToBST(int[] nums) {
16 | return toBST(nums, 0, nums.length - 1);
17 | }
18 |
19 | private Node toBST(int[] nums, int low, int high) {
20 | if (low > high) {
21 | return null;
22 | }
23 | int mid = (low + high)/2;
24 | Node n = Node.newNode(nums[mid]);
25 | n.left = toBST(nums, low, mid - 1);
26 | n.right = toBST(nums, mid + 1, high);
27 | return n;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/com/interview/tree/SortedOrderPrintCompleteTreeArray.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/sorted-order-printing-of-an-array-that-represents-a-bst/
5 | * Test case
6 | * empty array
7 | * 1 element array
8 | * multi element array
9 | */
10 | public class SortedOrderPrintCompleteTreeArray {
11 |
12 | private void print(int arr[],int current){
13 | if(current >= arr.length){
14 | return;
15 | }
16 | print(arr,2*current+1);
17 | System.out.println(arr[current]);
18 | print(arr,2*current+2);
19 | }
20 |
21 | public void print(int arr[]){
22 | print(arr,0);
23 | }
24 |
25 | public static void main(String args[]){
26 | int arr[] = {4, 2, 5, 1, 3};
27 | SortedOrderPrintCompleteTreeArray sop = new SortedOrderPrintCompleteTreeArray();
28 | sop.print(arr);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/interview/tree/UpsidedownBinaryTree.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | /**
4 | * Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that
5 | * shares the same parent node) or empty, flip it upside down and turn it into a tree where the original
6 | * right nodes turned into left leaf nodes. Return the new root.
7 | *
8 | * https://leetcode.com/problems/binary-tree-upside-down/
9 | */
10 | public class UpsidedownBinaryTree {
11 | public Node upsideDownBinaryTree(Node root) {
12 | if (root == null) {
13 | return null;
14 | }
15 | return upsideDownBinaryTree(root, null, null);
16 | }
17 |
18 | public Node upsideDownBinaryTree(Node root, Node parent, Node rightChild) {
19 | if (root == null) {
20 | return parent;
21 | }
22 | Node left = root.left;
23 | Node right = root.right;
24 |
25 | root.right = parent;
26 | root.left = rightChild;
27 |
28 | return upsideDownBinaryTree(left, root, right);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/test/com/interview/TestUtil.java:
--------------------------------------------------------------------------------
1 | package com.interview;
2 |
3 | import org.junit.Assert;
4 |
5 | import java.util.List;
6 |
7 | public class TestUtil {
8 | public void compareList(List expected, List actual) {
9 | int i = 0;
10 | for (T str : expected) {
11 | Assert.assertEquals("Failed at index " + i, str, actual.get(i++));
12 | }
13 | }
14 |
15 | public void compareListOfList(List> expected, List> actual) {
16 | Assert.assertEquals(expected.size(), actual.size());
17 | for (int i = 0; i < expected.size(); i++) {
18 | List a1 = expected.get(i);
19 | List a2 = expected.get(i);
20 | compareList(a1, a2);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/test/com/interview/array/AdditiveNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import org.junit.Assert;
4 |
5 | public class AdditiveNumberTest {
6 | public static void main(String args[]) {
7 | AdditiveNumber additiveNumber = new AdditiveNumber();
8 | Assert.assertTrue(additiveNumber.isAdditiveNumber("12351174"));
9 | Assert.assertFalse(additiveNumber.isAdditiveNumber("1023"));
10 | Assert.assertTrue(additiveNumber.isAdditiveNumber("198019823962"));
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/test/com/interview/array/ArrayAdditionTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class ArrayAdditionTest {
7 |
8 | @Test
9 | public void testAddSimple() {
10 | ArrayAddition arrayAddition = new ArrayAddition();
11 | int arr1[] = {9,9,9,9,9,9,9};
12 | int arr2[] = {1,6,8,2,6,7};
13 | int[] result = arrayAddition.add(arr1, arr2);
14 | int[] expected = {1, 0, 1, 6, 8, 2, 6, 6};
15 | Assert.assertArrayEquals(expected, result);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/test/com/interview/array/MaximumMinimumArrangementTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class MaximumMinimumArrangementTest {
7 | @Test
8 | public void differentCases() {
9 | MaximumMinimumArrangement maximumMinimumArrangement = new MaximumMinimumArrangement();
10 | int[] input1 = {1, 2, 3, 4, 5, 6, 7};
11 | maximumMinimumArrangement.rearrange(input1);
12 | int[] expected1 = {7, 1, 6, 2, 5, 3, 4};
13 | Assert.assertArrayEquals(expected1, input1);
14 |
15 | int[] input2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
16 | maximumMinimumArrangement.rearrange(input2);
17 | int[] expected2 = {10, 1, 9, 2, 8, 3, 7, 4, 6, 5};
18 | Assert.assertArrayEquals(expected2, input2);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/test/com/interview/array/MeetingRoomsTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | import java.util.Arrays;
7 |
8 | public class MeetingRoomsTest {
9 |
10 | @Test
11 | public void testDifferentCases() {
12 | MeetingRooms meetingRooms = new MeetingRooms();
13 | MeetingRooms.Interval[] interval = new MeetingRooms.Interval[4];
14 | interval[0] = new MeetingRooms.Interval(0,3);
15 | interval[1] = new MeetingRooms.Interval(2,5);
16 | interval[2] = new MeetingRooms.Interval(6,8);
17 | interval[3] = new MeetingRooms.Interval(8,10);
18 | Assert.assertEquals(2, meetingRooms.minMeetingRooms(interval));
19 | Assert.assertEquals(2, meetingRooms.minMeetingRooms1(interval));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/test/com/interview/array/MultiplyAllFieldsExceptOwnPositionTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class MultiplyAllFieldsExceptOwnPositionTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | MultiplyAllFieldsExceptOwnPosition mop = new MultiplyAllFieldsExceptOwnPosition();
11 | int[] input1 = {0, 9, -2};
12 | int[] output1 = {-18, 0, 0};
13 | Assert.assertArrayEquals(output1, mop.multiply(input1));
14 |
15 | int[] input2 = {1, 1};
16 | int[] output2 = {1, 1};
17 | Assert.assertArrayEquals(output2, mop.multiply(input2));
18 |
19 | int[] input3 = {3, 1, -3, 6};
20 | int[] output3 = {-18, -54, 18, -9};
21 | Assert.assertArrayEquals(output3, mop.multiply(input3));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/test/com/interview/array/NumberOfTriangledInUnsortedArrayTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class NumberOfTriangledInUnsortedArrayTest {
7 |
8 | @Test
9 | public void testSimpleCase() {
10 | NumberOfTrianglesInUnsortedArray numberOfTrianglesInUnsortedArray = new NumberOfTrianglesInUnsortedArray();
11 | int[] input = {3, 4, 5, 6, 8, 9, 15};
12 | int result = numberOfTrianglesInUnsortedArray.numberOfTriangles(input);
13 | Assert.assertEquals(15, result);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/test/com/interview/array/ThreeSumSmallerThanTargetTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.array;
2 |
3 | import junit.framework.Assert;
4 | import org.junit.Test;
5 |
6 | public class ThreeSumSmallerThanTargetTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | ThreeSumSmallerThanTarget threeSumSmallerThanTarget = new ThreeSumSmallerThanTarget();
11 | int[] input = {-2, 0, 1, 3};
12 | Assert.assertEquals(2, threeSumSmallerThanTarget.threeSumSmaller(input, 2));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/test/com/interview/bits/CountingBitsTillNumTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | /**
7 | * Created by tushar_v_roy on 4/3/16.
8 | */
9 | public class CountingBitsTillNumTest {
10 |
11 | @Test
12 | public void testDifferentCases() {
13 | CountingBitsTillNum countingBitsTillNum = new CountingBitsTillNum();
14 | int[] expected1 = {0, 1, 1};
15 | int[] expected2 = {0, 1, 1, 2, 1, 2};
16 | int[] expected3 = {0, 1, 1, 2, 1, 2, 2, 3, 1};
17 | int[] expected4 = {0, 1, 1, 2, 1, 2, 2, 3 ,1, 2, 2, 3};
18 |
19 | Assert.assertArrayEquals(expected1, countingBitsTillNum.countBits(2));
20 | Assert.assertArrayEquals(expected2, countingBitsTillNum.countBits(5));
21 | Assert.assertArrayEquals(expected3, countingBitsTillNum.countBits(8));
22 | Assert.assertArrayEquals(expected4, countingBitsTillNum.countBits(11));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/test/com/interview/bits/MaxProductWordLengthTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.bits;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class MaxProductWordLengthTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | MaxProductWordLength maxProductWordLength = new MaxProductWordLength();
11 | String[] words1 = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
12 | Assert.assertEquals(16, maxProductWordLength.maxProduct(words1));
13 |
14 | String[] words2 = {"a", "ab", "abc", "d", "cd", "bcd", "abcd"};
15 | Assert.assertEquals(4, maxProductWordLength.maxProduct(words2));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/test/com/interview/dynamic/DecodeWaysTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | import org.junit.Test;
4 |
5 | public class DecodeWaysTest {
6 | @Test
7 | public void testDifferentCases() {
8 | DecodeWays decodeWays = new DecodeWays();
9 | System.out.println(decodeWays.numDecodings("20320"));
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/test/com/interview/dynamic/PalindromePartitionTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.dynamic;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | public class PalindromePartitionTest {
10 |
11 | @Test
12 | public void testAllPartitions() {
13 | PalindromePartition palindromePartition = new PalindromePartition();
14 | List> result = palindromePartition.partition("aab");
15 |
16 | List> expected = new ArrayList<>();
17 | List r1 = new ArrayList<>();
18 | r1.add("a");
19 | r1.add("a");
20 | r1.add("b");
21 |
22 | expected.add(r1);
23 | r1 = new ArrayList<>();
24 | r1.add("aa");
25 | r1.add("b");
26 | expected.add(r1);
27 | int index = 0;
28 | for (List r : result) {
29 | Assert.assertEquals(expected.get(index++), r);
30 | }
31 | }
32 |
33 | @Test
34 | public void palindromePartitionMinCuts() {
35 | PalindromePartition palindromePartition = new PalindromePartition();
36 | Assert.assertEquals(3, palindromePartition.minCut("ABCCDCCLMLCCD"));
37 | Assert.assertEquals(0, palindromePartition.minCut("bb"));
38 | Assert.assertEquals(0, palindromePartition.minCut("b"));
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/test/com/interview/graph/CourseScheduleTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.graph;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class CourseScheduleTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | CourseSchedule cs = new CourseSchedule();
11 | int[][] courses = {{1,0},{2,0},{3,1},{3,2}};
12 | int[] output = cs.findOrder(4, courses);
13 | int[] expected = {0, 2, 1, 3};
14 | Assert.assertArrayEquals(expected, output);
15 |
16 |
17 | int[][] courses1 = {{1,0},{2,0},{3,1},{3,2}, {0, 3}};
18 | int[] output1 = cs.findOrder(4, courses1);
19 | int[] expected1 = {};
20 | Assert.assertArrayEquals(expected1, output1);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/test/com/interview/graph/TravelingSalesmanHeldKarpTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.graph;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class TravelingSalesmanHeldKarpTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | TravelingSalesmanHeldKarp tsp = new TravelingSalesmanHeldKarp();
11 | int[][] distance = {{0, 12, 3, 9, 6, 1, 2},
12 | {12, 0, 6, 1, 8, 2, 10},
13 | {3, 6, 0, 6, 7, 11, 7},
14 | {9, 1, 6, 0, 9, 10, 3},
15 | {6, 8, 7, 9, 0, 1, 11},
16 | {1, 2, 11, 10, 1, 0, 12},
17 | {2, 10, 7, 3, 11, 12, 0}};
18 |
19 | int cost = tsp.minCost(distance);
20 | Assert.assertEquals(19, cost);
21 |
22 | int[][] distance1 = {{0, 1, 15, 6},
23 | {2, 0, 7, 3},
24 | {9, 6, 0, 12},
25 | {10, 4, 8, 0},
26 | };
27 |
28 | cost = tsp.minCost(distance1);
29 | Assert.assertEquals(21, cost);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/test/com/interview/graph/WallsAndGatesTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.graph;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class WallsAndGatesTest {
7 |
8 | @Test
9 | public void testDifferentScenarios() {
10 | WallsAndGates wallsAndGates = new WallsAndGates();
11 | int INF = Integer.MAX_VALUE;
12 | int[][] rooms = {{INF, -1, 0, INF},
13 | {INF, INF, INF, -1},
14 | {INF, -1, INF, -1},
15 | {0, -1, INF, INF}};
16 |
17 | int[][] output = {{3, -1, 0, 1},
18 | {2, 2, 1, -1},
19 | {1, -1, 2, -1},
20 | {0, -1, 3, 4}};
21 |
22 | wallsAndGates.wallsAndGates(rooms);
23 | int i = 0;
24 | for (int[] o : output) {
25 | Assert.assertArrayEquals(o, rooms[i++]);
26 | }
27 | }
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/test/com/interview/linklist/DeleteDuplicateNodesTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.linklist;
2 |
3 | import org.junit.Test;
4 |
5 | public class DeleteDuplicateNodesTest {
6 |
7 | @Test
8 | public void testDifferentCases() {
9 | DeleteDuplicateNodes deleteDuplicateNodes = new DeleteDuplicateNodes();
10 | LinkList linkList = new LinkList();
11 | Node node = null;
12 | node = linkList.addNode(1, node);
13 | node = linkList.addNode(2, node);
14 | node = linkList.addNode(2, node);
15 | deleteDuplicateNodes.deleteDuplicates(node);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/test/com/interview/multiarray/Mutable2DSumRangeQueryTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.multiarray;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class Mutable2DSumRangeQueryTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | int[][] input = {{2, 3, 6}, {-1, 2, 4}, {-3, 2, 5}};
11 | Mutable2DSumRangeQuery mutable2DSumRangeQuery = new Mutable2DSumRangeQuery(input);
12 | int total = mutable2DSumRangeQuery.sumRegion(1, 1, 2, 2);
13 | Assert.assertEquals(13, total);
14 |
15 | total = mutable2DSumRangeQuery.sumRegion(0, 1, 2, 1);
16 | Assert.assertEquals(7, total);
17 |
18 | mutable2DSumRangeQuery.update(1, 1, 4);
19 | total = mutable2DSumRangeQuery.sumRegion(1, 1, 2, 2);
20 | Assert.assertEquals(15, total);
21 |
22 | total = mutable2DSumRangeQuery.sumRegion(0, 1, 2, 1);
23 | Assert.assertEquals(9, total);
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/test/com/interview/number/AllStrobogrammaticNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class AllStrobogrammaticNumberTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | AllStrobogrammaticNumber allStrobogrammaticNumber = new AllStrobogrammaticNumber();
11 | Assert.assertEquals(19, allStrobogrammaticNumber.strobogrammaticInRange("0", "1000"));
12 | Assert.assertEquals(34171, allStrobogrammaticNumber.strobogrammaticInRange("1011010", "2210101121121"));
13 |
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/test/com/interview/number/BasicCalculatorTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.number;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class BasicCalculatorTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | BasicCalculator basicCalculator = new BasicCalculator();
11 | Assert.assertEquals(0, basicCalculator.calculate("0"));
12 | Assert.assertEquals(9, basicCalculator.calculate("0 + 9"));
13 | Assert.assertEquals(19, basicCalculator.calculate("1 + 9 * 2"));
14 | Assert.assertEquals(15, basicCalculator.calculate("3 + 9/2 * 3"));
15 | Assert.assertEquals(6, basicCalculator.calculate("8 -2 + 3/ 5 "));
16 |
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/test/com/interview/recursion/RestoreIPAddressesTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.recursion;
2 |
3 | import com.interview.TestUtil;
4 | import org.junit.Test;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | public class RestoreIPAddressesTest {
10 |
11 | @Test
12 | public void testDifferenceCases() {
13 | RestoreIPAddresses restoreIPAddresses = new RestoreIPAddresses();
14 | List result = restoreIPAddresses.restoreIpAddresses("25525511135");
15 | List expected = new ArrayList<>();
16 | expected.add("255.255.11.135");
17 | expected.add("255.255.111.35");
18 | TestUtil t = new TestUtil<>();
19 | t.compareList(expected, result);
20 |
21 | List result1 = restoreIPAddresses.restoreIpAddresses("0000");
22 | expected = new ArrayList<>();
23 | expected.add("0.0.0.0");
24 | t.compareList(expected, result1);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/test/com/interview/string/StringEncoderDecoderTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.string;
2 |
3 | import com.interview.TestUtil;
4 | import org.junit.Test;
5 |
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | public class StringEncoderDecoderTest {
10 |
11 | @Test
12 | public void testDifferentCases() {
13 | StringEncoderDecoder stringEncoderDecoder = new StringEncoderDecoder();
14 | List input = new ArrayList<>();
15 | input.add("Tushar");
16 | input.add("Roy");
17 | input.add("");
18 | String encoded = stringEncoderDecoder.encode(input);
19 | List result = stringEncoderDecoder.decode(encoded);
20 | TestUtil testUtil = new TestUtil();
21 | testUtil.compareList(input, result);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/test/com/interview/string/ValidPalindromeTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.string;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class ValidPalindromeTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | ValidPalindrome validPalindrome = new ValidPalindrome();
11 | Assert.assertTrue(validPalindrome.isPalindrome("A man, a plan, a canal: Panama"));
12 | Assert.assertFalse(validPalindrome.isPalindrome("race a car"));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/test/com/interview/suffixprefix/TrieTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.suffixprefix;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | public class TrieTest {
7 |
8 | @Test
9 | public void testDifferentCases() {
10 | Trie trie = new Trie();
11 |
12 | trie.insert("abcd");
13 | trie.insert("abgl");
14 | trie.insertRecursive("lmn");
15 | trie.insertRecursive("lmnpq");
16 | trie.insert("cdeg");
17 | trie.insert("ghijk");
18 |
19 | Assert.assertFalse(trie.search("ab"));
20 | Assert.assertFalse(trie.search("abc"));
21 | Assert.assertTrue(trie.search("abcd"));
22 | Assert.assertFalse(trie.search("abg"));
23 | Assert.assertTrue(trie.search("abgl"));
24 | Assert.assertFalse(trie.search("lm"));
25 | Assert.assertTrue(trie.search("lmn"));
26 | Assert.assertFalse(trie.search("lmnp"));
27 | Assert.assertTrue(trie.search("lmnpq"));
28 |
29 | trie.delete("abcd");
30 | Assert.assertTrue(trie.search("abgl"));
31 | Assert.assertFalse(trie.search("abcd"));
32 |
33 | trie.delete("lmn");
34 | Assert.assertFalse(trie.search("lmn"));
35 | Assert.assertTrue(trie.search("lmnpq"));
36 |
37 | trie.delete("lmnpq");
38 | Assert.assertFalse(trie.search("lmnpq"));
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/test/com/interview/tree/KClosestValueInBinaryTreeTest.java:
--------------------------------------------------------------------------------
1 | package com.interview.tree;
2 |
3 | import com.interview.TestUtil;
4 | import org.junit.Test;
5 |
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | public class KClosestValueInBinaryTreeTest {
10 |
11 | @Test
12 | public void testDifferentCases() {
13 | Node root = null;
14 | BinaryTree bt = new BinaryTree();
15 | root = bt.addNode(10, root);
16 | root = bt.addNode(20, root);
17 | root = bt.addNode(30, root);
18 | root = bt.addNode(0, root);
19 | root = bt.addNode(6, root);
20 | root = bt.addNode(-6, root);
21 | root = bt.addNode(16, root);
22 | root = bt.addNode(19, root);
23 |
24 | KClosestValueInBinaryTree kClosestValueInBinaryTree = new KClosestValueInBinaryTree();
25 | List result = kClosestValueInBinaryTree.closestKValues(root, 18, 2);
26 | TestUtil testUtil = new TestUtil();
27 | testUtil.compareList(Arrays.asList(19, 20), result);
28 |
29 | result = kClosestValueInBinaryTree.closestKValues(root, 18, 4);
30 | testUtil.compareList(Arrays.asList(19, 20, 16, 10), result);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------