Showing preview only (1,394K chars total). Download the full file or copy to clipboard to get everything.
Repository: mission-peace/interview
Branch: master
Commit: 94be5deb0c0d
Files: 646
Total size: 1.2 MB
Directory structure:
gitextract_ew93x48r/
├── .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
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
interview.iml
interview.ipr
interview.iws
build/
.gradle/
.classpath
.project
.settings/
/bin/
/out
.DS_Store
python/graph/__pycache__/
python/.idea
target/
================================================
FILE: .idea/misc.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_9" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK" />
</project>
================================================
FILE: .idea/vcs.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
================================================
FILE: C++/Arrays/Trapping the rain water.cpp
================================================
#include <iostream>
using namespace std;
int trapped_water(int array[],int size){
int amount = 0;
int left[size],right[size];
left[0] = array[0]; right[size-1] = array[size-1];
for(int i = 1; i < size; i++){
left[i] = max(left[i-1],array[i]);
}
for(int i = size-2; i >=0; i--){
right[i] = max(right[i+1],array[i]);
}
for(int i = 0 ; i < size;i++){
amount += min(left[i],right[i]) - array[i];
}
return amount;
}
int main(){
int array[] = {1,0,3,4,5,0,5,7,7,8,9,0};
int size = sizeof(array) / sizeof(int);
cout << trapped_water(array,size);
return 0;
}
================================================
FILE: C++/Bit Manipulation/Checking Whether K-th Bit is Set or Not.cpp
================================================
#include<iostream>
using namespace std;
int main(){
int n,k;
cout << "Enter the number and the value of K : ";
cin >> n >> k;
int mask = 1 << (k-1);
if(n & mask){
cout << "Yes K-th bit is set" << endl;
}
else{
cout << "No K-th bit is not set" << endl;
}
return 0;
}
================================================
FILE: C++/Bit Manipulation/Clearing the K-th bit of a number.cpp
================================================
#include<iostream>
using namespace std;
int main(){
int n,k,mask;
cout << "Enter the number and the value of K : ";
cin >> n >> k;
mask = ~(1 << (k-1));
n = n&mask;
cout << "The number after clearing the K-th bit is : " << n << endl;
return 0;
}
================================================
FILE: C++/Bit Manipulation/Setting the K-th bit of a number.cpp
================================================
#include<iostream>
using namespace std;
int main(){
int n,k;
cout << "Enter the number and the value of K :";
cin >> n >> k;
int mask = 1 << (k - 1);
n = n | mask;
cout << "The number after setting the K-th bit is:" << n;
return 0;
}
================================================
FILE: C++/Bit Manipulation/Toggling Rightmost Set Bit of a number.cpp
================================================
#include<iostream>
using namespace std;
int main(){
int n;
cout << "Enter the number : ";
cin >> n ;
n = n & (n-1);
cout << "The number after toggling right most set bit : " << n << endl;
return 0;
}
================================================
FILE: C++/Bit Manipulation/Toggling the K-th bit of a number.cpp
================================================
#include<iostream>
using namespace std;
int main(){
int n,k,mask;
cout << "Enter the number and the value of K : ";
cin >> n >> k;
mask = 1 << (k-1);
n = n ^ mask;
cout << "The number after toggling the K-th bit is : " << n << endl;
return 0;
}
================================================
FILE: C++/Dynamic Programming/Edit Distance.cpp
================================================
int editDistance(string s1, string s2){
int m = s1.length();
int n = s2.length();
int dp[m+1][n+1];
for (int i = 0; i <= m; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= n; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i-1] == s2[j-1]) dp[i][j] = dp[i-1][j-1];
else dp[i][j] = 1 + min(min(dp[i][j-1],dp[i-1][j]),dp[i-1][j-1]);
}
}
return dp[m][n];
}
================================================
FILE: C++/Dynamic Programming/Longest Common Subsequence.cpp
================================================
int lcs(string x,string y){
int m = x.size(),n = y.size();
int dp[m+1][n+1];
for(int i=0;i<=m;i++){
dp[i][0] = 0;
}
for(int j=0;j<=m;j++){
dp[0][j] = 0;
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(x[i-1] == y[j-1]){
dp[i][j] = dp[i-1][j-1]+1;
}
else{
dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
}
}
}
return dp[m][n];
}
================================================
FILE: C++/Dynamic Programming/Longest Common Substring.cpp
================================================
#include <iostream>
using namespace std;
int longest_common_substring(string x,string y){
int m = x.size();
int n = y.size();
int lcs[m+1][n+1];
for(int i = 0 ; i < m; i++){
lcs[i][0] = 0;
}
for(int j = 0; j < n; j++){
lcs[0][j] = 0;
}
for(int i = 1; i <= m; i++){
for(int j = 1; j <=n; j++){
if(x[i-1] == y[j-1]){
lcs[i][j] = 1 + lcs[i-1][j-1];
}
else{
lcs[i][j] = 0;
}
}
}
return lcs[m][n];
}
int main(){
string x,y;
cin >> x >> y;
cout << longest_common_substring(x,y);
return 0;
}
================================================
FILE: C++/Dynamic Programming/Longest Increasing Subsequence.cpp
================================================
int lis(int array[],int n){
int dp[n],lis_value = -1;
for(int i=0;i<n;i++){
dp[i] = 1;
}
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(array[i] > array[j] and dp[i] < dp[j]+1){
dp[i] = dp[j] + 1;
}
}
}
for(int i=0;i<n;i++){
if(lis_value < dp[i]){
lis_value = dp[i];
}
}
return lis_value;
}
================================================
FILE: C++/Dynamic Programming/Longest palindromic Subsequence.cpp
================================================
#include <iostream>
using namespace std;
int longest_palindromic_subsequence(string str){
int table[str.size()][str.size()];
for(int i = 0 ; i < str.size(); i++){
table[i][i] = 1;
}
for(int l = 1 ; l < str.size() ; l++){
int i = 0, j = l;
while(j != str.size()){
if(str[i] == str[j]){
table[i][j] = 2 + table[i+1][j-1];
}
else{
table[i][j] = max(table[i+1][j],table[i][j-1]);
}
i++;j++;
}
}
return table[0][str.size()-1];
}
int main(){
string str;
cin >> str;
cout << longest_palindromic_subsequence(str);
return 0;
}
================================================
FILE: C++/Dynamic Programming/Matrix Chain Multiplication.cpp
================================================
int mcm(int p[], int n){
int m[n][n];
int i, j, k, L, q;
for (i = 1; i < n; i++)
m[i][i] = 0;
for (L=2; L<n; L++) {
for (i=1; i<=n-L+1; i++){
j = i+L-1;
m[i][j] = INT_MAX;
for (k=i; k<=j-1; k++){
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
m[i][j] = q;
}
}
}
return m[1][n-1];
}
================================================
FILE: C++/Graph Algorithms/All Pair Shortest Path Problem.cpp
================================================
#include<iostream>
#include<vector>
using namespace std;
void floydWarshall(vector<vector<int>> &graph){
for (int k=0; k<graph.size(); ++k){
for (int i=0; i<graph.size(); ++i){
for (int j=0; j<graph.size(); ++j){
graph[i][j] = min (graph[i][j], graph[i][k] + graph[k][j]);
}
}
}
}
int main(){
vector<vector<int>> graph;
int v,e,src,des,weight;
cin >> v >> e;
graph.resize(v,vector<int>(v,0));
while(e--){
cin >> src >> des >> weight;
graph[src][des] = weight;
}
floydWarshall(graph);
for(int i=0;i<v;i++){
for(int j=0;j<v;j++){
cout << graph[i][j] << " ";
}
cout << endl;
}
return 0;
}
================================================
FILE: C++/Graph Algorithms/Breadth First Search.cpp
================================================
#include<iostream>
#include<vector>
#include<list>
#include<queue>
using namespace std;
void breadth_first_search(vector<list<int>> graph,int src){
vector<bool>visited(graph.size(),false);
queue<int>Q;
Q.push(src);
visited[src] = true;
while(!Q.empty()){
int vertex = Q.front(); Q.pop();
cout << vertex << " ";
for(list<int>::iterator itr = graph[vertex].begin();itr!=graph[vertex].end();itr++){
if(!visited[*itr])
Q.push(*itr);
visited[*itr] = true;
}
}
}
int main(){
vector<list<int>> graph;
int v,e,src,des;
cin >> v >> e;
graph.resize(v);
while(e--){
cin >> src >> des;
graph[src].push_back(des);
graph[des].push_back(src);
}
cin >> src;
breadth_first_search(graph,src);
return 0;
}
================================================
FILE: C++/Graph Algorithms/Connected Components Algorithm DFS.cpp
================================================
#include<iostream>
#include<vector>
#include<list>
using namespace std;
void connectedComponentsDFS(vector<list<int>> graph,int src,vector<bool> &visited){
if(!visited[src]){
visited[src] = true;
for(list<int>::iterator itr = graph[src].begin();itr != graph[src].end();itr++){
connectedComponentsDFS(graph,*itr,visited);
}
}
}
int connectedComponents(vector<list<int>> graph){
int components = 0;
vector<bool> visited(graph.size(),false);
for(int src = 0; src < graph.size();src++){
if(!visited[src]){
components++;
connectedComponentsDFS(graph,src,visited);
}
}
return components;
}
int main(){
vector<list<int>> graph;
int v,e,src,des;
cin >> v >> e;
graph.resize(v);
while(e--){
cin >> src >> des;
graph[src].push_back(des);
}
cout << connectedComponents(graph);
return 0;
}
================================================
FILE: C++/Graph Algorithms/Depth First Search.cpp
================================================
#include<iostream>
#include<vector>
#include<list>
#include<stack>
using namespace std;
void depth_first_search(vector<list<int>> graph,int src){
vector<bool>visited(graph.size(),false);
stack<int>S;
S.push(src);
visited[src] = true;
while(!S.empty()){
int vertex = S.top(); S.pop();
cout << vertex << " ";
for(list<int>::iterator itr = graph[vertex].begin();itr!=graph[vertex].end();itr++){
if(!visited[*itr])
S.push(*itr);
visited[*itr] = true;
}
}
}
int main(){
vector<list<int>> graph;
int v,e,src,des;
cin >> v >> e;
graph.resize(v);
while(e--){
cin >> src >> des;
graph[src].push_back(des);
graph[des].push_back(src);
}
cin >> src;
depth_first_search(graph,src);
return 0;
}
================================================
FILE: C++/Graph Algorithms/Kruskal's Minimum Spanning Tree Algorithm.cpp
================================================
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct edge{int src,des,weight;};
class UnionFind {
int *parent, *ranks, _size;
public:
UnionFind(){
}
UnionFind(int size){
parent = new int[size]; ranks = new int[size];
for(int element = 0 ; element < size ; element++){
parent[element] = element , ranks[element] = 0 ;
}
_size = size;
}
void resize(int size){
parent = new int[size]; ranks = new int[size];
for(int element = 0 ; element < size ; element++){
parent[element] = element , ranks[element] = 0 ;
}
_size = size;
}
int find(int element){
if(parent[element] == element){
return element;
}
else{
return parent[element] = find(parent[element]); // Path Compression algorithm
}
}
bool connected(int x,int y){
if(find(x) == find(y)){
return true;
}
else{
return false;
}
}
void merge(int x,int y){
x = find(x);
y = find(y);
if(x != y){ // Union by Rank algorithm
if(ranks[x] > ranks[y]){
parent[y] = x;
}
else if(ranks[x] < ranks[y]){
parent[x] = y;
}
else{
parent[x] = y; ranks[y] ++ ;
}
_size--;
}
}
void clear(){
delete [] parent; delete [] ranks;
}
int size(){
return _size;
}
};
bool comparator(const edge &a,const edge &b){
return a.weight < b.weight;
}
vector<edge> kruskalsAlgorithm(vector<edge>graph,int vertices){
UnionFind uf(vertices);
vector<edge>spanningTree;
sort(graph.begin(),graph.end(),comparator);
spanningTree.push_back(graph[0]);
uf.merge(graph[0].src,graph[0].des);
for(int i=1;i<graph.size();i++){
if(!uf.connected(graph[i].src,graph[i].des)){
uf.merge(graph[i].src,graph[i].des);
spanningTree.push_back(graph[i]);
}
}
return spanningTree;
}
int main(){
vector<edge>graph;
int e,v;
cin >> e >> v;
graph.resize(e);
for(int i=0;i<e;i++){
cin >> graph[i].src >> graph[i].des >> graph[i].weight;
}
vector<edge> spanningTree = kruskalsAlgorithm(graph,v);
for(edge x : spanningTree){
cout << x.src << " " << x.des << " " << x.weight << endl;
}
return 0;
}
================================================
FILE: C++/Graph Algorithms/Prims Minimum Spanning Tree Algorithm.cpp
================================================
#include<iostream>
#include<climits>
#include<vector>
#include<queue>
#include<list>
using namespace std;
const int INF = INT_MAX;
class edge{ public: int src,des,weight; edge(){}edge(int s,int d,int w): src(s),des(d),weight(w){}};
class compare { public: bool operator()(const edge &a,const edge &b){ return a.weight < b.weight; }};
vector<edge> primsAlgorithm(vector<list<pair<int,int>>> graph,edge minEdge){
vector<edge>spanningTree;
priority_queue<edge,vector<edge>,compare> Q;
while(spanningTree.size() == graph.size()-1){
spanningTree.push_back(minEdge);
for(list<pair<int,int>>::iterator it = graph[minEdge.src].begin();it!=graph[minEdge.src].end();it++){
Q.push(edge(minEdge.src,it->first,it->second));
}
for(list<pair<int,int>>::iterator it = graph[minEdge.des].begin();it!=graph[minEdge.des].end();it++){
Q.push(edge(minEdge.des,it->first,it->second));
}
minEdge = Q.top(); Q.pop();
}
return spanningTree;
}
int main(){
vector<list<pair<int,int>>>graph;
int v,e,src,des,weight;
cin >> v >> e;
graph.resize(v);
edge minEdge;
minEdge.weight = INF;
while(e--){
cin >> src >> des >> weight;
graph[src].push_back(make_pair(des,weight));
graph[des].push_back(make_pair(src,weight));
if(weight < minEdge.weight){
minEdge.src = src, minEdge.des = des, minEdge.weight = weight;
}
}
vector<edge> spanningTree = primsAlgorithm(graph,minEdge);
for(edge x : spanningTree){
cout << x.src << " " << x.des << " " << x.weight << endl;
}
return 0;
}
================================================
FILE: C++/Graph Algorithms/Recursive Depth First Search.cpp
================================================
#include<iostream>
#include<vector>
#include<list>
using namespace std;
void depth_first_search(vector<list<int>> graph,int src,vector<bool> &visited){
if(!visited[src]){
cout << src << " ";
visited[src] = true;
for(list<int>::iterator itr = graph[src].begin();itr != graph[src].end();itr++){
depth_first_search(graph,*itr,visited);
}
}
}
int main(){
vector<list<int>> graph;
vector<bool> visited;
int v,e,src,des;
cin >> v >> e;
graph.resize(v);
visited.resize(v,false);
while(e--){
cin >> src >> des;
graph[src].push_back(des);
}
cin >> src;
depth_first_search(graph,src,visited);
return 0;
}
================================================
FILE: C++/Graph Algorithms/Single Shortest Path Bellman Ford Algorithm.cpp
================================================
#include<iostream>
#include<vector>
#include<climits>
using namespace std;
struct edge {int src, des, weight;};
pair<bool,vector<int>> bellmanFord(vector<edge> graph,int vertex,int source){
vector<int> distances(vertex,INT_MAX);
distances[source] = 0;
for(int i=0;i<vertex-1;i++){
for(int j=0;j<graph.size();j++){
if(distances[graph[j].des] > distances[graph[j].src] + graph[j].weight){
distances[graph[j].des] = distances[graph[j].src] + graph[j].weight;
}
}
}
for(int j=0;j<graph.size();j++){
if(distances[graph[j].des] > distances[graph[j].src] + graph[j].weight){
return make_pair(false,vector<int>());
}
}
return make_pair(true,distances);
}
int main(){
int edges,source,vertex;
vector<edge> graph;
cin >> edges >> vertex;
for(int i = 0; i < edges; i++){
cin >> graph[i].src >> graph[i].des >> graph[i].weight;
}
cin >> source;
pair<bool,vector<int>> result = bellmanFord(graph,vertex,source);
if(result.first == true){
cout << "No Cycle Exist ! " << endl;
for(vector<int>::iterator itr = (result.second).begin();itr!=(result.second).end();itr++){
cout << *itr << " ";
}
}
else{
cout << "Graph Has Negative Weight Cycle" << endl;
}
return 0;
}
================================================
FILE: C++/Graph Algorithms/Single Source Shortest Path Dijkstra Algorithm.cpp
================================================
#include<iostream>
#include<queue>
#include<vector>
#include<list>
#include<climits>
using namespace std;
struct compare{
bool operator()(const pair<int,int> &a,const pair<int,int> &b){
return a.second > b.second;
}
};
vector<int> dijkshtra(vector<list<pair<int,int>>> graph,int src){
priority_queue<pair<int,int>,vector<pair<int,int>>,compare> Q;
vector<int> distances(graph.size(),INT_MAX);
vector<bool> visited(graph.size(),false);
distances[src] = 0;
Q.push(make_pair(src,0));
while(!Q.empty()){
pair<int,int> current = Q.top(); Q.pop();
cout << "Currently at" << current.first << endl;
if(!visited[current.first]){
visited[current.first] = true;
for(list<pair<int,int>> :: iterator vertex = graph[current.first].begin();vertex != graph[current.first].end();vertex++){
if(current.second + vertex->second < distances[vertex->first]){
distances[vertex->first] = current.second + vertex->second;
Q.push(make_pair(vertex->first,distances[vertex->first]));
}
}
}
}
return distances;
}
int main(){
vector<list<pair<int,int>>> graph;
int v,e,src,des,weight;
cin >> v >> e;
graph.resize(v);
while(e--){
cin >> src >> des >> weight;
graph[src].push_back(make_pair(des,weight));
}
cin >> src;
vector<int> distances = dijkshtra(graph,src);
for(vector<int> :: iterator itr = distances.begin();itr != distances.end();itr++){
cout << *itr << " ";
}
return 0;
}
================================================
FILE: C++/Graph Algorithms/Topological Sorting.cpp
================================================
#include<iostream>
#include<vector>
#include<list>
using namespace std;
void topologicalSortDFS(vector<list<int>> graph,int src,vector<bool> &visited,list<int> &topologicalSortedList){
if(!visited[src]){
visited[src] = true;
for(list<int>::iterator itr = graph[src].begin();itr != graph[src].end();itr++){
topologicalSortDFS(graph,*itr,visited,topologicalSortedList);
}
topologicalSortedList.push_front(src);
}
}
list<int> topologicalSort(vector<list<int>> graph){
list<int> topologicalSortedList;
vector<bool> visited(graph.size(),false);
for(int src = 0; src < graph.size();src++){
topologicalSortDFS(graph,src,visited,topologicalSortedList);
}
return topologicalSortedList;
}
int main(){
vector<list<int>> graph;
int v,e,src,des;
cin >> v >> e;
graph.resize(v);
while(e--){
cin >> src >> des;
graph[src].push_back(des);
}
list<int> topologicalSortedList = topologicalSort(graph);
for(list<int>::iterator itr = topologicalSortedList.begin();itr!=topologicalSortedList.end();itr++){
cout << *itr << " ";
}
return 0;
}
================================================
FILE: C++/Heaps - Priority Queues/K-th Largest element of the stream.cpp
================================================
#include <iostream>
#include <queue>
using namespace std;
int main(){
int n,k;
priority_queue<int,vector<int>,greater<int>>Q;
cout << "Enter the the value of K : ";
cin >> k;
while(cin >> n){
cout << k << "-th largest element of the stream : ";
if(Q.size() < k){
Q.push(n);
if(Q.size() == k){
cout << Q.top() 3<< endl;
}
else{
cout << "NULL" << endl;
}
}
else{
if(Q.top() < n){
Q.pop();
Q.push(n);
}
cout << Q.top() << endl;
}
cout << "Enter next element of the stream : ";
}
return 0;
}
================================================
FILE: C++/Linked List/Reverse a linked list recursively.cpp
================================================
void reverse_list(list_node *head){
list_node *
}
================================================
FILE: C++/Number Theory Algorithms/Divisors.cpp
================================================
#include<iostream>
#include<set>
using namespace std;
set<int> generateDivisors(long long int num){
set<int> divisors;
for(int i = 1 ; i*i <= num; i++ ){
if(num % i == 0){
divisors.insert(i);
if( i != num/i ){
divisors.insert(num/i);
}
}
}
return divisors;
}
int main(){
set<int> d = generateDivisors(23);
for(int x : d){
cout << x << " ";
}
return 0;
}
================================================
FILE: C++/Number Theory Algorithms/Sieve of Eratosthenes.cpp
================================================
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int MAX = 1000*1000;
const int LMT = 1000;
vector<bool> prime(MAX+1,true);
int seiveEratosthenes(){
prime[0] = prime[1] = false;
for(int i = 2; i <= LMT; i++){
if(prime[i]){
for(int j = i + i; j <= MAX ; j += i){
prime[j] = false;
}
}
}
return count_if(prime.begin(),prime.end(),[](bool p){ return p == true;});
}
int main(){
cout << seiveEratosthenes();
return 0;
}
================================================
FILE: C++/Recursion/Partition of array on the pivot.cpp
================================================
#include<iostream>
using namespace std;
void partition(int array[],int low,int high){
int i = low-1, pivot = array[high-1];
for(int j = low ; j < high ; j++){
if(array[j] <= pivot){
i++;
swap(array[i],array[j]);
}
}
swap(array[i+1],array[high-1]);
}
int main(){
int n;
cin >> n;
int array[n];
partition(array,0,n);
return 0;
}
================================================
FILE: C++/Recursion/Permutation of a string.cpp
================================================
#include <iostream>
using namespace std;
void permutation(char str[],int k,int n){
if(k == n){
for(int j = 0; j < n; j++){
cout << str[j];
}
cout << endl;
}
else{
for(int i = k ; i < n; i++){
swap(str[i],str[k]);
permutation(str,k+1,n);
swap(str[i],str[k]);
}
}
}
int main(){
char str[] = {'A','B','C','D'};
permutation(str,0,4);
return 0;
}
================================================
FILE: C++/Segment Tree/Segment Tree.cpp
================================================
void buildTree (int tree[],int array[], int index, int low, int high) {
if (low == high)
tree[index] = array[low];
else {
int mid = (low + high) >> 1;
buildTree (tree,array, index*2, low, mid);
buildTree (tree,array, index*2+1, mid+1, high);
tree[index] = tree[index*2] + tree[index*2+1];
}
}
int rangeQuery (int tree[],int index, int low, int high, int l, int r) {
if (l > r)
return 0;
if (l == low && r == high)
return tree[index];
int mid = (low + high) >> 1;
return rangeQuery (tree,index*2, low, mid, l, min(r,mid))
+ rangeQuery (tree,index*2+1, mid+1, high, max(l,mid+1), r);
}
void updateQuery (int tree[],int index, int low, int high, int pos, int delta) {
if (low == high)
tree[index] = delta;
else {
int mid = (low + high) >> 1;
if (pos <= mid)
updateQuery (tree,index*2, low, mid, pos, delta);
else
updateQuery (tree,index*2+1, mid+1, high, pos, delta);
tree[index] = tree[index*2] + tree[index*2+1];
}
}
================================================
FILE: C++/Stacks - Queue/CircularQueue.cpp
================================================
#include <iostream>
using namespace std;
class circular_queue
{
private :
int *array ;
int front, back ;
int MAX;
public :
circular_queue( int maxsize = 10 ) ;
void enqueue ( int item ) ;
int dequeue( ) ;
void display( ) ;
} ;
circular_queue :: circular_queue( int maxsize )
{
MAX = maxsize ;
array = new int [ MAX ];
front = back = -1 ;
for ( int i = 0 ; i < MAX ; i++ )
array[i] = 0 ;
}
void circular_queue :: enqueue(int item){
if((back+1)%MAX == front){
cout << "Queue is full" << endl;
return ;
}
back = ( back + 1 ) % MAX;
array[back] = item ;
if ( front == -1 )
front = 0 ;
}
int circular_queue :: dequeue(){
int data ;
if ( front == -1 )
{
cout << "\nQueue is empty" ;
return NULL ;
}
data = array[front] ;
array[front] = 0 ;
if ( front == back )
{
front = -1 ;
back = -1 ;
}
else
front = ( front + 1 ) % MAX;
return data ;
}
void circular_queue :: display()
{
cout << endl ;
for ( int i = 0 ; i < MAX ; i++ )
cout << array[i] << " " ;
cout << endl ;
}
int main(){
circular_queue cq(10) ;
cq.enqueue(14);
cq.enqueue(22);
cq.enqueue(13);
cq.enqueue(-6);
cq.enqueue(25);
cout << "\nElements in the circular queue: " ;
cq.display();
int i = cq.dequeue() ;
cout << "Item deleted: " << i ;
i = cq.dequeue();
cout << "\nItem deleted: " << i ;
cout << "\nElements in the circular queue after deletion: " ;
cq.display();
cq.enqueue(21);
cq.enqueue(17);
cq.enqueue(18);
cq.enqueue(9);
cq.enqueue(20);
cout << "Elements in the circular queue after addition: " ;
cq.display();
cq.enqueue(32);
cout << "Elements in the circular queue after addition: " ;
cq.display();
return 0;
}
================================================
FILE: C++/String Algorithms/KMP.cpp
================================================
vector<int> computePrefix(string pat){
int m = pat.size();
vector<int> longestPrefix(m);
for(int i = 1, k = 0; i < m; i++){
while(k > 0 && pat[k] != pat[i]){
k = longestPrefix[k - 1];
}
if(pat[i] == pat[k]){
longestPrefix[i] = ++k;
}
else{
longestPrefix[i] = k;
}
}
return longestPrefix;
}
void KMP(string str,string pat){
int n = str.size();
int m = pat.size();
vector<int> longestPrefix = computePrefix(pat);
for(int i = 0, k = 0; i < n; i++){
while(k > 0 && pat[k] != str[i]){
k = longestPrefix[k - 1];
}
if(str[i] == pat[k]){
k++;
}
if(k == m){
cout << i - m + 1 << "\n";
k = longestPrefix[k - 1];
}
}
}
================================================
FILE: C++/String Algorithms/Trie.cpp
================================================
struct Trie {
Trie* child[26];
bool isLeaf;
Trie() {
memset(child, 0, sizeof(child));
isLeaf = 0;
}
void pushWord(char *str) {
if(*str == '\0')
isLeaf = 1;
else {
int cur = *str - 'a';
if(child[cur] == 0 )
child[cur] = new Trie();
child[cur]->pushWord(str+1);
}
}
bool wordExist(char* str) {
if(*str == '\0')
return isLeaf;
int cur = *str - 'a';
if(child[cur] == 0 )
return false;
return child[cur]->wordExist(str+1);
}
bool prefixExist(char* str) {
if(*str == '\0')
return true;
int cur = *str - 'a';
if(child[cur] == 0 )
return false;
return child[cur]->prefixExist(str+1);
}
};
================================================
FILE: C++/Union Find/Union Find.cpp
================================================
#include<iostream>
using namespace std;
class UnionFind {
int *parent, *ranks, _size;
public:
UnionFind(){
}
UnionFind(int size){
parent = new int[size]; ranks = new int[size];
for(int element = 0 ; element < size ; element++){
parent[element] = element , ranks[element] = 0 ;
}
_size = size;
}
void resize(int size){
parent = new int[size]; ranks = new int[size];
for(int element = 0 ; element < size ; element++){
parent[element] = element , ranks[element] = 0 ;
}
_size = size;
}
int find(int element){
if(parent[element] == element){
return element;
}
else{
return parent[element] = find(parent[element]); // Path Compression algorithm
}
}
bool connected(int x,int y){
if(find(x) == find(y)){
return true;
}
else{
return false;
}
}
void merge(int x,int y){
x = find(x);
y = find(y);
if(x != y){ // Union by Rank algorithm
if(ranks[x] > ranks[y]){
parent[y] = x;
}
else if(ranks[x] < ranks[y]){
parent[x] = y;
}
else{
parent[x] = y; ranks[y] ++ ;
}
_size--;
}
}
void clear(){
delete [] parent; delete [] ranks;
}
int size(){
return _size;
}
};
int main(){
UnionFind uf(5);
cout << uf.size() << endl; // 5 disjoint sets are there
uf.merge(0,1);
cout << uf.size() << endl; // 4 disjoint sets are there
uf.merge(0,2);
cout << uf.size() << endl; // 3 disjoint sets are there
uf.merge(1,2);
cout << uf.size() << endl; // 3 disjoint sets are there
uf.clear();
return 0;
}
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
<h2>Please visit my wiki link for full list of questions</h2>
<h3>https://github.com/mission-peace/interview/wiki</h3>
<h2> Like my facebook page for latest updates on my youtube channel</h2>
<h3>https://www.facebook.com/tusharroy25</h3>
<h2> Contribution </h2>
Please contribute to this repository to help it make better. Any change like new question, code improvement, doc improvement etc. is very welcome. Just send me a pull request and I will review the request and approve it if it looks good.
<h2> How to use this repository </h2>
<h3> Softwares to install </h3>
* Install JDK8 https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html
* Install Git https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
* Install either Intellij https://www.jetbrains.com/idea/download/
* If you like eclipse instead of intellij install eclipse https://eclipse.org/downloads/
<h3> Set up your desktop </h3>
* Pull the git repository. Go to command line and type git clone https://github.com/mission-peace/interview.git
* Go to root directory of checked out project.
* Run ./gradlew idea to generate idea related classes
* Fire up intellij. Go to Open. Go to git repo folder and open interview.ipr . On file menu go to project structure. Update language level support to 8
* If you use eclipse, do ./gradlew eclipse . This will generate eclipse related files. Go to eclipse and open up folder containing this repo.
* Go to any program and run that program
* Go to any test and run the junit test.
* Run ./gradlew build to create classes, run tests and create jar.
================================================
FILE: build.gradle
================================================
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: "jacoco"
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.12'
}
sourceSets {
main {
java {
srcDir 'src'
}
}
test {
java {
srcDir 'test'
}
}
}
jacocoTestReport {
reports {
xml.enabled false
csv.enabled false
html.destination "${buildDir}/jacocoHtml"
}
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Sat Apr 02 16:59:09 PDT 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-bin.zip
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: python/array/arrayaddition.py
================================================
def add(arr1, arr2):
l = max(len(arr1), len(arr2))
result = [0 for j in range(l)]
c = 0
i = len(arr1) - 1
j = len(arr2) - 1
r = 0
l -= 1
while i >= 0 and j >= 0:
r = arr1[i] + arr2[j] + c
i -= 1
j -= 1
c = r // 10
result[l] = r % 10
l -= 1
while i >= 0:
r = arr1[i] + c
i -= 1
c = r // 10
result[l] = r % 10
l -= 1
while j >= 0:
r = arr1[j] + c
j -= 1
c = r // 10
result[l] = r % 10
l -= 1
if c != 0:
new_result = [0 for j in range(len(result) + 1)]
t = len(new_result) - 1
while t > 0:
new_result[t] = result[t - 1]
t -= 1
new_result[0] = c
return new_result
return result
arr1 = [9, 9, 9, 9, 9, 9, 9]
arr2 = [1, 6, 8, 2, 6, 7]
result = add(arr1, arr2)
print(result)
================================================
FILE: python/array/commonthreesortedarray.py
================================================
# http://www.geeksforgeeks.org/find-common-elements-three-sorted-arrays/
def common_elements(input1, input2, input3):
result = []
i = 0
j = 0
k = 0
while i < len(input1) and j < len(input2) and k < len(input3):
if input1[i] == input2[j] and input2[j] == input3[k]:
result.append(input1[i])
i = i + 1
j = j + 1
k = k + 1
elif input1[i] < input2[j]:
i = i + 1
elif input2[j] < input3[k]:
j = j + 1
else:
k = k + 1
return result
if __name__ == '__main__':
input1 = [1, 5, 10, 20, 40, 80]
input2 = [6, 7, 20, 80, 100]
input3 = [3, 4, 15, 20, 30, 70, 80, 120]
print(common_elements(input1, input2, input3))
================================================
FILE: python/array/countinversionofsize3.py
================================================
# http://www.geeksforgeeks.org/count-inversions-of-size-three-in-a-give-array/
def find_inversions(input):
inversion = 0
for i in range(1, len(input) - 1):
larger = 0
for k in range(0, i):
if input[k] > input[i]:
larger = larger + 1
smaller = 0
for k in range(i+1, len(input)):
if input[k] < input[i]:
smaller = smaller + 1
inversion += larger*smaller
return inversion
if __name__ == '__main__':
input = [9, 6, 4, 5, 8]
print(find_inversions(input))
================================================
FILE: python/array/flip0smaximum1s.py
================================================
# http://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/
def flip_0s_to_maximize_consecutive_1s(input, flips_allowed):
window_start = 0
count_zero = 0
result = 0
for i in range(len(input)):
if input[i] == 1:
result = max(result, i - window_start + 1)
else:
if count_zero < flips_allowed:
count_zero = count_zero + 1
result = max(result, i - window_start + 1)
else:
while True:
if input[window_start] == 0:
window_start = window_start + 1
break
window_start = window_start + 1
return result
if __name__ == '__main__':
input = [0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1]
print(flip_0s_to_maximize_consecutive_1s(input, 1))
================================================
FILE: python/array/longestsamesumspan.py
================================================
# http://www.geeksforgeeks.org/longest-span-sum-two-binary-arrays/
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/array/LongestSameSumSpan.java
def longest_span(input1, input2):
if len(input1) != len(input2):
raise ValueError;
diff = {}
prefix1 = 0
prefix2 = 0
max_span = 0
diff[0] = -1
for i in range(len(input1)):
prefix1 += input1[i]
prefix2 += input2[i]
curr_diff = prefix1 - prefix2
if curr_diff in diff:
max_span = max(max_span, i - diff[curr_diff])
else:
diff[curr_diff] = i
return max_span
if __name__ == '__main__':
input1 = [1, 0, 0, 1, 1, 0]
input2 = [0, 1, 1, 0, 1, 1]
print(longest_span(input1, input2))
================================================
FILE: python/array/maximumsumpathtwoarrays.py
================================================
# http://www.geeksforgeeks.org/maximum-sum-path-across-two-arrays/
def max_sum(input1, input2):
max_sum = 0
i = 0
j = 0
sum1 = 0
sum2 = 0
while i < len(input1) and j < len(input2):
if input1[i] == input2[j]:
if sum1 > sum2:
max_sum += sum1 + input1[i]
else:
max_sum += sum2 + input2[j]
i = i + 1
j = j + 1
sum1 = 0
sum2 = 0
elif input1[i] < input2[j]:
sum1 += input1[i]
i = i + 1
else:
sum2 += input2[j]
j = j + 1
while i < len(input1):
sum1 += input1[i]
i = i + 1
while j < len(input2):
sum2 += input2[j]
j = j + 1
if sum1 > sum2:
max_sum += sum1
else:
max_sum += sum2
return max_sum
if __name__ == '__main__':
input1 = [2, 3, 7, 10, 12, 15, 30, 34]
input2 = [1, 5, 7, 8, 10, 15, 16, 19]
print(max_sum(input1, input2))
================================================
FILE: python/array/maxproductsubarray.py
================================================
# http://www.geeksforgeeks.org/maximum-product-subarray/
def max_product(input):
max_ending = 1
min_ending = 1
max_so_far = 1
for i in input:
if i > 0:
max_ending = max_ending * i
min_ending = min(min_ending*i, 1)
elif i == 0:
max_ending = 1
min_ending = 1
else:
t = max_ending
max_ending = max(min_ending*i, 1)
min_ending = t * i
if max_so_far < max_ending:
max_so_far = max_ending
return max_so_far
if __name__ == '__main__':
input = [-6,-3,8,-9,-1,-1,3,6,9,0,3,-1]
print(max_product(input))
================================================
FILE: python/array/numberoftrianglesunsortedarray.py
================================================
# http://www.geeksforgeeks.org/find-number-of-triangles-possible/
def number_of_triangles(input):
input.sort()
count = 0
for i in range(len(input)-2):
k = i + 2
for j in range(i+1, len(input)):
while k < len(input) and input[i] + input[j] > input[k]:
k = k + 1
count += k - j - 1
return count
if __name__ == '__main__':
input = [15, 9, 8, 3, 4, 5, 6]
print(number_of_triangles(input))
================================================
FILE: python/array/positiveandnegativealternativelymaintainingorder.py
================================================
# http://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/
def rearrange(input):
for i in range (len(input)):
if i%2 == 0 and input[i] >= 0:
index_of_next_negative = find_next(input, i+1, False)
if index_of_next_negative == -1:
return
else:
right_rotate(input, i, index_of_next_negative)
elif i % 2 != 0 and input[i] < 0:
index_of_next_positive = find_next(input, i+1, True)
if index_of_next_positive == -1:
return
else:
right_rotate(input, i, index_of_next_positive)
def find_next(input, start, isPositive):
for i in range(start, len(input)):
if (isPositive and input[i] >= 0) or (not isPositive and input[i] < 0):
return i;
return -1
def right_rotate(input, start, end):
t = input[end]
for i in range(end, start -1, -1):
input[i] = input[i-1]
input[start] = t
if __name__ == '__main__':
input = [-5, -2, 5, 2, 4, 7, 1, 8, 0, -8];
rearrange(input)
print(input)
================================================
FILE: python/array/rearrangearrayperindex.py
================================================
# http://www.geeksforgeeks.org/rearrange-array-arrj-becomes-arri-j/
def rearrange(input):
for i in range(len(input)):
input[i] += 1
for i in range(len(input)):
if input[i] > 0:
rearrange_util(input, i)
for i in range(len(input)):
input[i] = -input[i] - 1
def rearrange_util(input, start):
i = start + 1
v = input[start]
while v > 0:
t = input[v-1]
input[v-1] = -i
i = v
v = t
if __name__ == '__main__':
input = [1, 2, 0, 5, 3, 4];
rearrange(input)
print(input)
================================================
FILE: python/array/reorderarraybyindex.py
================================================
# http://www.geeksforgeeks.org/reorder-a-array-according-to-given-indexes/
def reorder(input, index):
if len(input) != len(index):
raise ValueError
for i in range(len(index)):
while index[i] != i:
s_index = index[index[i]]
s_val = input[index[i]]
index[index[i]] = index[i]
input[index[i]] = input[i]
index[i] = s_index
input[i] = s_val
if __name__ == '__main__':
input = [50, 40, 70, 60, 90]
index = [3, 0, 4, 1, 2]
reorder(input, index)
print(input)
print(index)
================================================
FILE: python/array/rotationwithmaxsum.py
================================================
# http://www.geeksforgeeks.org/find-maximum-value-of-sum-iarri-with-only-rotations-on-given-array-allowed/
def max_sum(input):
arr_sum = 0
rotation_sum = 0
for i in range(len(input)):
arr_sum += input[i]
rotation_sum += i*input[i]
max_rotation_sum = rotation_sum
for i in range(1, len(input)):
rotation_sum += len(input)*input[i-1] - arr_sum
max_rotation_sum = max(max_rotation_sum, rotation_sum)
return max_rotation_sum
if __name__ == '__main__':
input = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(max_sum(input))
================================================
FILE: python/array/smallestintegernotrepresentedbysubsetsum.py
================================================
# http://www.geeksforgeeks.org/find-smallest-value-represented-sum-subset-given-array/
def find_smallest_integer(input):
result = 1
for i in range(len(input)):
if input[i] <= result:
result += input[i]
else:
break
return result
if __name__ == '__main__':
input = [1, 2, 3, 8]
print(find_smallest_integer(input))
================================================
FILE: python/array/tripletsumlessthantotal.py
================================================
# http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/
def find_all_triplet(input, total):
input.sort()
result = 0
for i in range(len(input) - 2):
j = i + 1
k = len(input) - 1
while j < k:
if input[i] + input[j] + input[k] >= total:
k = k - 1
else:
result += k - j
j = j + 1
return result
if __name__ == '__main__':
input = [5, 1, 3, 4, 7]
print(find_all_triplet(input, 12))
================================================
FILE: python/array/zigzagarrangement.py
================================================
# http://www.geeksforgeeks.org/convert-array-into-zig-zag-fashion/
def rearrange(input):
is_less = True
for i in range(len(input)-1):
if is_less:
if input[i] > input[i+1]:
swap(input, i, i+1)
else:
if input[i] < input[i+1]:
swap(input, i, i+1)
is_less = not is_less
def swap(input, i, j):
t = input[i]
input[i] = input[j]
input[j] = t
if __name__ == '__main__':
input = [4, 3, 2, 6, 7, 1, 9]
rearrange(input)
print(input)
================================================
FILE: python/dynamic/bitonicsequence.py
================================================
"""
Problem Statement
=================
Find the length of the longest Bitonic Sequence in a given sequence of numbers. A Bitonic sequence is a sequence of
numbers which are increasing and then decreasing.
Video
-----
* https://youtu.be/TWHytKnOPaQ
Analysis
--------
* Runtime O(n)
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-15-longest-bitonic-subsequence/
"""
def longest_bitonic(sequence):
length_of_input = len(sequence)
increasing_sequence = [1] * length_of_input
decreasing_sequence = [1] * length_of_input
for i in range(1, length_of_input):
for j in range(0, i):
if sequence[i] > sequence[j]:
increasing_sequence[i] = max(increasing_sequence[i], increasing_sequence[j] + 1)
for i in range(length_of_input - 2, -1, -1):
for j in range(length_of_input - 1, i, -1):
if sequence[i] > sequence[j]:
decreasing_sequence[i] = max(decreasing_sequence[i], decreasing_sequence[j] + 1)
max_value = 0
for i in range(len(sequence)):
bitonic_sequence_length = increasing_sequence[i] + decreasing_sequence[i] - 1
max_value = max(max_value, bitonic_sequence_length)
return max_value
if __name__ == '__main__':
max_value = longest_bitonic([1, 4, 3, 7, 2, 1, 8, 11, 13, 0])
assert 7 == max_value # 1, 4, 7, 8, 11, 13, 0
================================================
FILE: python/dynamic/boxstacking.py
================================================
"""
Problem Statement
=================
Given different dimensions and unlimited supply of boxes for each dimension, stack boxes on top of each other such that
it has maximum height but with caveat that length and width of box on top should be strictly less than length and width
of box under it. You can rotate boxes as you like.
1) Create all rotations of boxes such that length is always greater or equal to width
2) Sort boxes by base area in non increasing order (length * width). This is because box
with more area will never ever go on top of box with less area.
3) Take T[] and result[] array of same size as total boxes after all rotations are done
4) Apply longest increasing subsequence type of algorithm to get max height.
Analysis
--------
If n number of dimensions are given total boxes after rotation will be 3n.
* Space complexity is O(n)
* Time complexity - O(nlogn) to sort boxes. O(n^2) to apply DP on it So really O(n^2)
Video
-----
* https://youtu.be/9mod_xRB-O0
References
----------
* http://www.geeksforgeeks.org/dynamic-programming-set-21-box-stacking-problem/
* http://people.cs.clemson.edu/~bcdean/dp_practice/
"""
from collections import namedtuple
from itertools import permutations
dimension = namedtuple("Dimension", "height length width")
def create_rotation(given_dimensions):
"""
A rotation is an order wherein length is greater than or equal to width. Having this constraint avoids the
repetition of same order, but with width and length switched.
For e.g (height=3, width=2, length=1) is same the same box for stacking as (height=3, width=1, length=2).
:param given_dimensions: Original box dimensions
:return: All the possible rotations of the boxes with the condition that length >= height.
"""
for current_dim in given_dimensions:
for (height, length, width) in permutations((current_dim.height, current_dim.length, current_dim.width)):
if length >= width:
yield dimension(height, length, width)
def sort_by_decreasing_area(rotations):
return sorted(rotations, key=lambda dim: dim.length * dim.width, reverse=True)
def can_stack(box1, box2):
return box1.length < box2.length and box1.width < box2.width
def box_stack_max_height(dimensions):
boxes = sort_by_decreasing_area([rotation for rotation in create_rotation(dimensions)])
num_boxes = len(boxes)
T = [rotation.height for rotation in boxes]
R = [idx for idx in range(num_boxes)]
for i in range(1, num_boxes):
for j in range(0, i):
if can_stack(boxes[i], boxes[j]):
stacked_height = T[j] + boxes[i].height
if stacked_height > T[i]:
T[i] = stacked_height
R[i] = j
max_height = max(T)
start_index = T.index(max_height)
# Prints the dimensions which were stored in R list.
while True:
print boxes[start_index]
next_index = R[start_index]
if next_index == start_index:
break
start_index = next_index
return max_height
if __name__ == '__main__':
d1 = dimension(3, 2, 5)
d2 = dimension(1, 2, 4)
assert 11 == box_stack_max_height([d1, d2])
================================================
FILE: python/dynamic/breakword.py
================================================
"""
Problem Statement
=================
Given a string and a dictionary, split the string in to multiple words so that each word belongs to the dictionary.
Video
-----
* https://youtu.be/WepWFGxiwRs
Analysis
--------
* word_break_recursive: Exponential
* word_break_dp : O(n^3)
Solution
--------
if input[i..j] belongs in a dictionary:
DP[i][j] = True
else:
DP[i][j] = True if DP[i][k-1] and DP[k][j] for any k between i to j.
Multiple different implementations are given below.
"""
def word_break_recursive(given_string, dictionary):
""""Returns None if the given string cannot be broken into words, otherwise returns space separate words."""
given_string_length = len(given_string)
if given_string_length == 0:
return ""
string = ""
for i in range(given_string_length):
string += given_string[i]
if string in dictionary:
r = word_break_recursive(given_string[i + 1:], dictionary)
if r is not None:
string += " " + r
return string
return None
def word_break_dp(given_string, dictionary):
"""Returns None if the given string cannot be broken into words, otherwise returns space separated words."""
given_string_length = len(given_string)
# -1 indicates the word cannot be split.
DP = [[-1 for _ in range(given_string_length)] for _ in range(given_string_length)]
for substring_length in range(1, given_string_length + 1):
for start in range(0, given_string_length - substring_length + 1):
end = start + substring_length - 1
substring = given_string[start: end + 1]
if substring in dictionary:
DP[start][end] = start
continue
for split in range(start + 1, end + 1):
if DP[start][split - 1] != -1 and DP[split][end] != -1:
DP[start][end] = split
break
if DP[0][-1] == -1:
return None
words = []
start_index = 0
end_index = given_string_length - 1
while start_index < given_string_length:
split_index = DP[start_index][end_index]
if start_index == split_index:
words.append(given_string[start_index: end_index + 1])
break
else:
words.append(given_string[start_index: split_index])
start_index = split_index
return " ".join(words)
def is_word_break_possible(given_string, dictionary):
"""Returns if any word break is possible amongst the multiple word breaks in the sentence."""
DP = dict()
max_word_length = len(max(dictionary, key=len))
return is_word_break_possible_recursive_helper(given_string, dictionary, 0, max_word_length, DP)
def is_word_break_possible_recursive_helper(given_string, dictionary, start, max_word_length, DP):
if start == len(given_string):
return True
if start in DP:
return DP[start]
for i in range(start, start + max_word_length):
if i < len(given_string):
new_word = given_string[start: i + 1]
if new_word in dictionary:
continue
if is_word_break_possible_recursive_helper(given_string, dictionary, i + 1, max_word_length, DP):
DP[start] = True
return True
DP[start] = False
return False
def all_possible_word_break_helper(given_string, dictionary, start, max_word_length, DP):
""""Returns all possible word breaks in a given sentence."""
if start == len(given_string):
return [""]
if start in DP:
return DP[start]
words = []
for i in range(start, start + max_word_length):
if i < len(given_string):
new_word = given_string[start: i + 1]
if new_word not in dictionary:
continue
sub_words = all_possible_word_break_helper(given_string, dictionary, i + 1, max_word_length, DP)
for word in sub_words:
extra_space = "" if len(word) == 0 else " "
words.append(new_word + extra_space + word)
DP[start] = words
return words
def all_possible_word_breaks(given_string, dictionary):
DP = dict()
max_word_length = len(max(dictionary, key=len))
return all_possible_word_break_helper(given_string, dictionary, 0, max_word_length, DP)
if __name__ == '__main__':
dictionary = {"joy", "likes", "to", "play"}
given_string = "joylikestoplay"
assert True == is_word_break_possible(given_string, dictionary)
assert "joy likes to play " == word_break_recursive(given_string, dictionary)
assert "joy likes to play" == word_break_dp(given_string, dictionary)
dictionary = {"pea", "nut", "peanut", "butter"}
given_string = "peanutbutter"
assert ['pea nut butter', 'peanut butter'] == all_possible_word_breaks(given_string, dictionary)
================================================
FILE: python/dynamic/coin_change_num_ways.py
================================================
"""
Problem Statement
=================
Given a total and coins of certain denominations find number of ways total can be formed from coins assuming infinity
supply of coins.
Analysis
--------
* Runtime : O(num_of_coins * total)
Video
-----
* https://youtu.be/_fgjrs570YE
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
"""
def coin_changing_num_ways(coins, total):
cols = total + 1 # 1 for value 0 in total
rows = len(coins)
T = [[1 if col == 0 else 0 for col in range(cols)] for _ in range(rows)]
for i in range(rows):
for j in range(cols):
if (i - 1) < 0:
continue
if j < coins[i]:
T[i][j] = T[i - 1][j]
else:
T[i][j] = T[i - 1][j] + T[i][j - coins[i]]
return T[rows - 1][cols - 1]
def coin_changing_num_ways2(coins, total):
cols = total + 1
num_coins = len(coins)
# Using 1-D Array instead of 2-D Array. Approach is same as coin_changing_num_ways.
T = [1 if col == 0 else 0 for col in range(cols)]
for i in range(num_coins):
for col in range(1, cols):
if col >= coins[i]:
T[col] += T[col - coins[i]]
return T[cols - 1]
def print_coin_changes_recursive(coins, total, results_stack, pos):
if total == 0:
for coin in results_stack:
print "%d " % coin,
print
for idx in range(pos, len(coins)):
if total >= coins[idx]:
results_stack.append(coins[idx])
print_coin_changes_recursive(coins, total - coins[idx], results_stack, idx)
results_stack.pop() # Remove last inserted coin from stack to use new coin with different index.
def print_coin_changes(coins, total):
print_coin_changes_recursive(coins, total, list(), 0)
if __name__ == '__main__':
coins = [1, 2, 3]
total = 5
expected = 5
assert expected == coin_changing_num_ways(coins, total)
assert expected == coin_changing_num_ways2(coins, total)
print_coin_changes(coins, total)
================================================
FILE: python/dynamic/coinchangingmincoins.py
================================================
"""
Problem Statement
=================
Given coins of certain denominations with infinite supply find minimum number of coins it takes to form given total
Video
-----
* Topdown DP - https://youtu.be/Kf_M7RdHr1M
* Bottom Up DP - https://youtu.be/Y0ZqKpToTic (Approach 1. 2D array.)
* Bottom up DP - https://youtu.be/NJuKJ8sasGk (Same as Approach 1. Uses 1D array since 2D array is not required.)
Analysis
--------
* Time complexity - O(len(coins) * total)
* Space complexity - O(len(coins) * total)
"""
def min_coins(coins, total):
cols = total + 1
rows = len(coins)
T = [[0 if col == 0 else float("inf") for col in range(cols)] for _ in range(rows)]
for i in range(rows):
for j in range(1, cols):
if j < coins[i]:
T[i][j] = T[i - 1][j]
else:
T[i][j] = min(T[i - 1][j], 1 + T[i][j - coins[i]])
return T[rows - 1][cols - 1]
def print_coins(R, coins):
start = len(R) - 1
if R[start] == -1:
print "No Solution Possible."
return
print "Coins:",
while start != 0:
coin = coins[R[start]]
print "%d " % coin,
start = start - coin
def min_coins2(coins, total):
cols = total + 1
T =[0 if idx == 0 else float("inf") for idx in range(cols)]
R = [-1 for _ in range(total + 1)]
for j in range(len(coins)):
for i in range(1, cols):
coin = coins[j]
if i >= coins[j]:
if T[i] > 1 + T[i - coin]:
T[i] = 1 + T[i - coin]
R[i] = j
print_coins(R, coins)
return T[cols - 1]
def min_coins_top_down(coins, total, memo):
if total == 0:
return 0
if total in memo:
return memo[total]
min_value = float("inf")
for i in range(len(coins)):
coin = coins[i]
if coin > total:
continue
val = min_coins_top_down(coins, total - coin, memo)
min_value = min(min_value, val)
min_value += 1
memo[total] = min_value
return min_value
if __name__ == '__main__':
coins = [1, 5, 6, 8]
total = 11
expected = 2
assert expected == min_coins(coins, total)
assert expected == min_coins2(coins, total)
assert expected == min_coins_top_down(coins, total, dict())
================================================
FILE: python/dynamic/count_num_A.py
================================================
"""
Problem Statement
=================
Imagine you have a special keyboard with the following keys:
Key 1: Prints 'A' on screen
Key 2: (Ctrl-A): Select screen
Key 3: (Ctrl-C): Copy selection to buffer
Key 4: (Ctrl-V): Print buffer on screen appending it
after what has already been printed.
If you can only press the keyboard for N times (with the above four
keys), write a program to produce maximum numbers of A's. That is to
say, the input parameter is N (No. of keys that you can press), the
output is M (No. of As that you can produce).
Complexity
----------
* Recursive Solution : Exponential > O(2^n)
* Dynamic Programming: Quadratic O(n^2)
Reference
---------
* http://www.geeksforgeeks.org/how-to-print-maximum-number-of-a-using-given-four-keys/
"""
def count_a_recursive(n_times):
if n_times < 7:
return n_times
result = float("-inf")
for sub_prob in range(n_times - 3, 0, -1):
result = max(result, (n_times - sub_prob - 1) * count_a_recursive(sub_prob))
return result
def count_a(n_times):
if n_times < 7:
return n_times
T = [0 for _ in range(n_times + 1)]
for num in range(7):
T[num] = num
for n in range(7, n_times + 1):
for sub_prob in range(n - 3, 0, -1):
T[n] = max(T[n], T[sub_prob] * (n - sub_prob - 1))
return T[n_times]
if __name__ == '__main__':
expected = 9
assert expected == count_a_recursive(7)
assert expected == count_a(7)
================================================
FILE: python/dynamic/count_num_binary_without_consec_1.py
================================================
"""
Problem Statement
=================
Given a positive integer N, count all the numbers from 1 to 2^N, whose binary representation does not have consecutive
1s.
This is a simple application of fibonacci series.
Video
-----
* https://www.youtube.com/watch?v=a9-NtLIs1Kk
Complexity
----------
* Runtime Complexity: O(n)
Reference
---------
* http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
"""
def consec_one(num_n):
f1 = f2 = 1
for _ in range(num_n):
f1, f2 = f1 + f2, f1
return f1
if __name__ == '__main__':
assert 13 == consec_one(5)
================================================
FILE: python/dynamic/cutting_rod.py
================================================
"""
Problem Statement
=================
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n.
Determine the maximum value obtainable by cutting up the rod and selling the pieces.
Video
-----
* https://youtu.be/IRwVmTmN6go
Time Complexity
---------------
1. Recursive Solution = O(2^n)
2. Dynamic Programming Solution = O(n^2)
Reference
---------
http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/
"""
def max_profit_dp(prices, rod_length):
rod_length_values = [0 for _ in range(rod_length + 1)]
for length in range(1, rod_length + 1):
max_value = float("-inf")
for cut_length in range(1, length + 1):
max_value = max(max_value, prices[cut_length - 1] + rod_length_values[length - cut_length])
rod_length_values[length] = max_value
return rod_length_values[rod_length]
def max_profit_recursive(prices, rod_length):
if rod_length == 0:
return 0
max_price = float('-inf')
for length in range(1, rod_length + 1):
max_price = max(max_price, prices[length - 1] + max_profit_recursive(prices, rod_length - length))
return max_price
if __name__ == '__main__':
prices = [3,5,8,9,10,20,22,25]
rod_length = 8
expected_max_profit = 26
assert expected_max_profit == max_profit_recursive(prices, rod_length)
assert expected_max_profit == max_profit_dp(prices, rod_length)
================================================
FILE: python/dynamic/dice_throw_ways.py
================================================
"""
Problem Statement
=================
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
on each face when all the dice are thrown.
Complexity
----------
* Run time complexity: O(m * n * x) where m is number of faces, n is number of dice and x is given sum.
References
----------
* http://www.geeksforgeeks.org/dice-throw-problem/
"""
def num_ways(faces, dices, sumX):
T = [[0 for _ in range(sumX + 1)] for _ in range(dices + 1)]
# For a single dice
for face_value in range(1, faces + 1):
if face_value <= sumX:
T[1][face_value] = 1
for dice in range(2, dices + 1):
for partial_sum in range(1, sumX + 1):
for face_value in range(1, faces + 1):
if face_value < partial_sum:
T[dice][partial_sum] += T[dice - 1][partial_sum - face_value]
return T[dices][sumX]
if __name__ == '__main__':
assert 7 == num_ways(3, 3, 6)
================================================
FILE: python/dynamic/editdistance.py
================================================
"""
Problem Statement
=================
Given two strings str1 and str2, find the minimum number of edits (edit one character to another, delete char from str1
or delete char from str2) to change str1 to str2.
Video
-----
* https://youtu.be/We3YDTzNXEk
Analysis
--------
* DP Runtime : O(len(str1) * len(str2))
* Recursive Solution: Exponential (O(3^(m+n-1)))
Reference
---------
* https://www.clear.rice.edu/comp130/12spring/editdist/
"""
def print_edits(T, str1, str2):
i = len(T) - 1
j = len(T[0]) - 1
while True:
if i == 0 or j == 0:
break
if str2[i - 1] == str1[j - 1]:
i -= 1
j -= 1
elif T[i][j] == T[i - 1][j - 1] + 1:
print "Edit %s in string1 to %s in string2." % (str1[j - 1], str2[i - 1])
i -= 1
j -= 1
elif T[i][j] == T[i - 1][j] + 1:
print "Delete %s in string2." % str2[i - 1]
i -= 1
elif T[i][j] == T[i][j - 1] + 1:
print "Delete %s in string1." % str1[j - 1]
j -= 1
def min_edit_distance(str1, str2):
rows = len(str2) + 1
cols = len(str1) + 1
T = [[0 for _ in range(cols)] for _ in range(rows)]
for j in range(cols):
T[0][j] = j
for i in range(rows):
T[i][0] = i
for i in range(1, rows):
for j in range(1, cols):
if str2[i - 1] == str1[j - 1]:
T[i][j] = T[i - 1][j - 1]
else:
T[i][j] = 1 + min(T[i - 1][j - 1], T[i - 1][j], T[i][j - 1])
print_edits(T, str1, str2)
return T[rows - 1][cols - 1]
def min_edit_distance_recursive(str1, str2):
i = len(str1)
j = len(str2)
if i == 0: return j
if j == 0: return i
return min(min_edit_distance_recursive(str1[:i - 1], str2) + 1,
min_edit_distance_recursive(str1, str2[:j - 1]) + 1,
min_edit_distance_recursive(str1[:i - 1], str2[:j - 1]) + (1 if str1[i - 1] != str2[j - 1] else 0))
if __name__ == '__main__':
str1 = "azced"
str2 = "abcdef"
expected = 3
assert expected == min_edit_distance(str1, str2)
assert expected == min_edit_distance(str2, str1)
assert expected == min_edit_distance_recursive(str1, str2)
================================================
FILE: python/dynamic/egg_drop.py
================================================
"""
Problem Statement
=================
Given a certain number of eggs and a certain number of floors, determine the minimum number of attempts required to find
the egg breaking floor.
Analysis
--------
* Dynamic Programming Time Complexity: O(eggs * num_floors^2)
* Recursive Solution: Exponential
Video
-----
* https://youtu.be/3hcaVyX00_4
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
"""
def min_attempts_egg_drop(eggs, floors):
num_eggs = eggs + 1
num_floors = floors + 1
T = [[floor if egg == 1 else 0 for floor in range(num_floors)] for egg in range(num_eggs)]
for egg in range(2, num_eggs):
for floor in range(1, num_floors):
T[egg][floor] = min(1 + max(T[egg - 1][k - 1], T[egg][floor - k]) for k in range(1, floor + 1))
return T[num_eggs - 1][num_floors - 1]
def min_attempts_egg_drop_recursive(eggs, floors):
if eggs == 1 or floors == 0:
return floors
min_value = float("inf")
for floor in range(1, floors + 1):
min_value = min(min_value,
1 + max(min_attempts_egg_drop_recursive(eggs - 1, floor - 1),
min_attempts_egg_drop_recursive(eggs, floors - floor)))
return min_value
if __name__ == '__main__':
eggs = 3
floors = 100
expected_attempts = 9
assert expected_attempts == min_attempts_egg_drop(eggs, floors)
eggs = 2
floors = 6
expected_attempts = 3
assert expected_attempts == min_attempts_egg_drop_recursive(eggs, floors)
================================================
FILE: python/dynamic/knapsack_01.py
================================================
"""
Problem Statement
=================
0/1 Knapsack Problem - Given items of certain weights/values and maximum allowed weight how to pick items to pick items
from this set to maximize sum of value of items such that sum of weights is less than or equal to maximum allowed
weight.
Runtime Analysis
----------------
Time complexity - O(W*total items)
Video
-----
* Topdown DP - https://youtu.be/149WSzQ4E1g
* Bottomup DP - https://youtu.be/8LusJS5-AGo
References
----------
* http://www.geeksforgeeks.org/dynamic-programming-set-10-0-1-knapsack-problem/
* https://en.wikipedia.org/wiki/Knapsack_problem
"""
def knapsack_01(values, weights, total):
total_items = len(weights)
rows = total_items + 1
cols = total + 1
T = [[0 for _ in range(cols)] for _ in range(rows)]
for i in range(1, rows):
for j in range(1, cols):
if j < weights[i - 1]:
T[i][j] = T[i - 1][j]
else:
T[i][j] = max(T[i - 1][j], values[i - 1] + T[i - 1][j - weights[i - 1]])
return T[rows - 1][cols -1]
def knapsack_01_recursive_util(values, weights, remaining_weight, total_items, current_item, memo):
if current_item >= total_items or remaining_weight <= 0:
return 0
key = (total_items - current_item - 1, remaining_weight)
if key in memo:
return memo[key]
if remaining_weight < weights[current_item]:
max_value = knapsack_01_recursive_util(values, weights, remaining_weight, total_items, current_item + 1, memo)
else:
max_value = max(values[current_item] + knapsack_01_recursive_util(values, weights, remaining_weight - weights[current_item], total_items, current_item + 1, memo),
knapsack_01_recursive_util(values, weights, remaining_weight, total_items, current_item + 1, memo))
memo[key] = max_value
return max_value
def knapsack_01_recursive(values, weights, total_weight):
memo = dict()
return knapsack_01_recursive_util(values, weights, total_weight, len(values), 0, memo)
if __name__ == '__main__':
total_weight = 7
weights = [1, 3, 4, 5]
values = [1, 4, 5, 7]
expected = 9
assert expected == knapsack_01(values, weights, total_weight)
assert expected == knapsack_01_recursive(values, weights, total_weight)
total_weight = 8
weights = [2, 2, 4, 5]
values = [2, 4, 6, 9]
expected = 13
assert expected == knapsack_01(values, weights, total_weight)
assert expected == knapsack_01_recursive(values, weights, total_weight)
================================================
FILE: python/dynamic/kth_ugly_number.py
================================================
"""
Problem Statement
=================
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,
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find the kth ugly number.
Complexity
----------
* Time Complexity O(n)
* Space Complexity O(n)
Reference
---------
* http://www.geeksforgeeks.org/ugly-numbers/
"""
def ugly_number(kth):
ugly_factors = [1] # By convention 1 is included.
factor_index = {
2: 0,
3: 0,
5: 0}
for num in range(1, kth):
minimal_factor = min(min(ugly_factors[factor_index[2]] * 2, ugly_factors[factor_index[3]] * 3),
ugly_factors[factor_index[5]] * 5)
ugly_factors.append(minimal_factor)
for factor in [2, 3, 5]:
if minimal_factor % factor == 0:
factor_index[factor] += 1
return ugly_factors[kth - 1]
if __name__ == '__main__':
assert 5832 == ugly_number(150)
================================================
FILE: python/dynamic/longest_common_subsequence.py
================================================
"""
Problem Statement
=================
Given two sequences A = [A1, A2, A3,..., An] and B = [B1, B2, B3,..., Bm], find the length of the longest common
subsequence.
Video
-----
* https://youtu.be/NnD96abizww
Complexity
----------
* Recursive Solution: O(2^n) (or O(2^m) whichever of n and m is larger).
* Dynamic Programming Solution: O(n * m)
Reference
---------
* https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
* http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
"""
def lcs_recursive_helper(sequence1, sequence2, index1, index2):
if (index1 == len(sequence1)) or (index2 == len(sequence2)):
return 0
if sequence1[index1] == sequence2[index2]:
return 1 + lcs_recursive_helper(sequence1, sequence2, index1 + 1, index2 + 1)
return max(lcs_recursive_helper(sequence1, sequence2, index1 + 1, index2),
lcs_recursive_helper(sequence1, sequence2, index1, index2 + 1))
def longest_common_subsequence_recursive(sequence1, sequence2):
return lcs_recursive_helper(sequence1, sequence2, 0, 0)
def longest_common_subsequence(sequence1, sequence2):
cols = len(sequence1) + 1 # Add 1 to represent 0 valued column for DP
rows = len(sequence2) + 1 # Add 1 to represent 0 valued row for DP
T = [[0 for _ in range(cols)] for _ in range(rows)]
max_length = 0
for i in range(1, rows):
for j in range(1, cols):
if sequence2[i - 1] == sequence1[j - 1]:
T[i][j] = 1 + T[i - 1][j - 1]
else:
T[i][j] = max(T[i - 1][j], T[i][j - 1])
max_length = max(max_length, T[i][j])
return max_length
if __name__ == '__main__':
sequence1 = "ABCDGHLQR"
sequence2 = "AEDPHR"
expected_length = 4
assert expected_length == longest_common_subsequence_recursive(sequence1, sequence2)
assert expected_length == longest_common_subsequence_recursive(sequence2, sequence1)
assert expected_length == longest_common_subsequence(sequence1, sequence2)
assert expected_length == longest_common_subsequence(sequence2, sequence1)
================================================
FILE: python/dynamic/longest_common_substring.py
================================================
"""
Problem Statement
=================
Given two sequences A = [A1, A2, A3,..., An] and B = [B1, B2, B3,..., Bm], find the length of the longest common
substring.
Video
-----
* https://youtu.be/BysNXJHzCEs
Complexity
----------
* Recursive Solution: O(2^n) (or O(2^m) whichever of n and m is larger).
* Dynamic Programming Solution: O(n * m)
Reference
---------
* http://en.wikipedia.org/wiki/Longest_common_substring_problem
"""
def longest_common_string_recursive_helper(str1, str2, pos1, pos2, check_equal):
if pos1 == -1 or pos2 == -1:
return 0
if check_equal:
if str1[pos1] == str2[pos2]:
return 1 + longest_common_string_recursive_helper(str1, str2, pos1 - 1, pos2 - 1, True)
else:
return 0
longest = 0 # start (again) to find the longest from the current positions
if str1[pos1] == str2[pos2]:
longest = 1 + longest_common_string_recursive_helper(str1, str2, pos1 - 1, pos2 - 1, True)
return max(longest,
longest_common_string_recursive_helper(str1, str2, pos1, pos2 - 1, False),
longest_common_string_recursive_helper(str1, str2, pos1 - 1, pos2, False))
def longest_common_substring_recursive(str1, str2):
return longest_common_string_recursive_helper(str1, str2, len(str1) - 1, len(str2) - 1, False)
def longest_common_substring(str1, str2):
cols = len(str1) + 1 # Add 1 to represent 0 valued col for DP
rows = len(str2) + 1 # Add 1 to represent 0 valued row for DP
T = [[0 for _ in range(cols)] for _ in range(rows)]
max_length = 0
for i in range(1, rows):
for j in range(1, cols):
if str2[i - 1] == str1[j - 1]:
T[i][j] = T[i - 1][j - 1] + 1
max_length = max(max_length, T[i][j])
return max_length
if __name__ == '__main__':
str1 = "abcdef"
str2 = "zcdemf"
expected = 3
assert expected == longest_common_substring(str1, str2)
assert expected == longest_common_substring_recursive(str1, str2)
str1 = "abcdef"
str2 = "cde"
expected = 3
assert expected == longest_common_substring(str1, str2)
str1 = "cde"
str2 = "zcdemf"
expected = 3
assert expected == longest_common_substring(str1, str2)
================================================
FILE: python/dynamic/longest_increasing_subsequence.py
================================================
"""
Problem Statement
=================
Find a subsequence in given array in which the subsequence's elements are in sorted order, lowest to highest, and in
which the subsequence is as long as possible.
Video
-----
* https://youtu.be/CE2b_-XfVDk
Solution
--------
Dynamic Programming is used to solve this question. DP equation is.::
if(arr[i] > arr[j]) { T[i] = max(T[i], T[j] + 1) }
* Time complexity is O(n^2).
* Space complexity is O(n)
Reference
---------
* http://en.wikipedia.org/wiki/Longest_increasing_subsequence
* http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/
"""
def longest_increasing_subsequence(sequence):
sequence_length = len(sequence)
T = [1 for _ in range(sequence_length)]
solution_indices = [i for i in range(sequence_length)]
for index_i in range(1, sequence_length):
for index_j in range(0, index_i):
if (sequence[index_i] > sequence[index_j]) and (T[index_i] < T[index_j] + 1):
T[index_i] = T[index_j] + 1
solution_indices[index_i] = index_j
# find the index of the max number in T
max_value = max(T)
max_index = T.index(max_value)
# Print solution using linked values in solution_indices
next_index = max_index
while True:
print sequence[next_index],
old_index = next_index
next_index = solution_indices[next_index]
if next_index == old_index:
break
return T[max_index]
def longest_increasing_subsequence_recursive(sequence):
sequence_length = len(sequence)
longest = 0
for index in range(sequence_length - 1):
longest_so_far = longest_subsequence_recursive_helper(sequence, index + 1, sequence[index])
if longest_so_far > longest:
longest = longest_so_far
return longest + 1
def longest_subsequence_recursive_helper(sequence, next_position, current_position_value):
if next_position == len(sequence):
return 0
temp1 = 0
if sequence[next_position] > current_position_value:
temp1 = 1 + longest_subsequence_recursive_helper(sequence, next_position + 1, sequence[next_position])
temp2 = longest_subsequence_recursive_helper(sequence, next_position + 1, current_position_value)
return max(temp1, temp2)
if __name__ == '__main__':
sequence = [23, 10, 22, 5, 33, 8, 9, 21, 50, 41, 60, 80, 99, 22, 23, 24, 25, 26, 27]
assert 10 == longest_increasing_subsequence(sequence)
assert 10 == longest_increasing_subsequence_recursive(sequence)
================================================
FILE: python/dynamic/longest_palindromic_subsequence.py
================================================
"""
Problem Statement
=================
Given a string find longest palindromic subsequence in this string.
Complexity
----------
* Dynamic Programming Time Complexity: O(n^2)
* Recursive Solution Time Complexity: O(2^n)
Video
-----
* https://youtu.be/_nCsPn7_OgI
References
----------
* http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
"""
def longest_palindromic_subsequence(given_string):
rows = cols = string_length = len(given_string)
T = [[0 for _ in range(cols)] for _ in range(rows)]
for row in range(rows):
T[row][row] = 1
for substring_length in range(2, string_length + 1):
for row in range(0, string_length - substring_length + 1):
col = row + substring_length - 1
if given_string[row] == given_string[col]:
if string_length == 2:
T[row][col] = 2
else:
T[row][col] = 2 + T[row + 1][col - 1]
else:
T[row][col] = max(T[row + 1][col], T[row][col - 1])
return T[0][-1]
def palindromic_subsequence_recursive_helper(given_string, start_index, length):
if length == 0 or length == 1:
return length
if given_string[start_index] == given_string[length - start_index - 1]:
return 2 + palindromic_subsequence_recursive_helper(given_string, start_index + 1, length - 2)
else:
return max(palindromic_subsequence_recursive_helper(given_string, start_index, length - 1),
palindromic_subsequence_recursive_helper(given_string, start_index + 1, length - 1))
def longest_palindromic_subsequence_recursive(given_string):
return palindromic_subsequence_recursive_helper(given_string, 0, len(given_string))
if __name__ == '__main__':
given_string = "agbdba"
expected_result = 5
assert expected_result == longest_palindromic_subsequence(given_string)
assert expected_result == longest_palindromic_subsequence_recursive(given_string)
================================================
FILE: python/dynamic/matrix_chain_order.py
================================================
"""
Problem Statement
=================
Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We
need to write a function matrix_chain_order() that should return the minimum number of multiplications needed to
multiply the chain.
Video
-----
* https://youtu.be/vgLJZMUfnsU
Note
----
In the code below we give matrices length as an array and each matrix takes 2 indices from the array.
For e.g. {2, 3, 4} represents two matrices (2, 3) and (3, 4) in (row, col) format.
Complexity
----------
Time Complexity: O(n^3)
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/
"""
def matrix_chain_order(matrices):
matrices_length = len(matrices)
T = [[0 for _ in range(matrices_length)] for _ in range(matrices_length)]
for gap in range(2, matrices_length):
for index_i in range(0, matrices_length - gap):
index_j = index_i + gap
T[index_i][index_j] = 10000
for index_k in range(index_i + 1, index_j):
temp = T[index_i][index_k] + T[index_k][index_j] + matrices[index_i] * matrices[index_k] * matrices[index_j]
if temp < T[index_i][index_j]:
T[index_i][index_j] = temp
return T[0][-1]
if __name__ == '__main__':
matrices = [4, 2, 3, 5, 3]
assert 84 == matrix_chain_order(matrices)
================================================
FILE: python/dynamic/maximum_increasing_subsequence.py
================================================
"""
Problem Statement
=================
Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array
such that the integers in the subsequence are in increasing order.
Complexity
----------
* Time Complexity: O(n^2)
* Space Complexity: O(n)
Video
-----
* https://youtu.be/99ssGWhLPUE
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-14-maximum-sum-increasing-subsequence/
"""
def maximum_sum_subsequence(sequence):
sequence_length = len(sequence)
T = [sequence[i] for i in range(sequence_length)]
for index_i in range(1, sequence_length):
for index_j in range(0, index_i):
if sequence[index_j] < sequence[index_i]:
T[index_i] = max(T[index_i], T[index_j] + sequence[index_i])
return max(T)
if __name__ == '__main__':
sequence = [1, 101, 10, 2, 3, 100, 4]
assert 111 == maximum_sum_subsequence(sequence)
================================================
FILE: python/dynamic/nth_fibonacci.py
================================================
"""
Problem Statement
=================
Given the number n, find the nth fibanacci number.
The fibonacci series is 0, 1, 1, 2, 3 ...
And follows the formula Fn = Fn-1 + Fn-2
Complexity
----------
* Recursive Solution: O(2^n)
* Dynamic Programming: O(n)
"""
def fibonacci_recursive(n):
if n == 0 or n == 1:
return n
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
def fibonacci(n):
n1, n2 = 0, 1
if n == n1 or n == n2:
return n
for i in range(2, n + 1):
n1, n2 = n2, n1 + n2
return n2
if __name__ == '__main__':
assert 610 == fibonacci_recursive(15)
assert 610 == fibonacci(15)
================================================
FILE: python/dynamic/num_bst.py
================================================
"""
Problem Statement
=================
Count number of binary search trees created for array of size n. The solution is the nth catalan number.
Complexity
----------
* Dynamic Programming: O(n^2)
* Recursive Solution: O(2^n)
Video
-----
* https://youtu.be/YDf982Lb84o
Reference
---------
* http://www.geeksforgeeks.org/program-nth-catalan-number/
"""
def num_bst(num_nodes):
T = [0 for _ in range(num_nodes + 1)]
T[0] = 1
T[1] = 1
for node in range(2, num_nodes+1):
for sub in range(0, node):
T[node] += T[sub] * T[node - sub - 1]
return T[num_nodes]
def num_bst_recursive(num_nodes):
if num_nodes == 0 or num_nodes == 1:
return 1
result = 0
for root in range(1, num_nodes + 1):
result += num_bst_recursive(root - 1) * num_bst_recursive(num_nodes - root)
return result
if __name__ == '__main__':
assert 5 == num_bst(3)
assert 5 == num_bst_recursive(3)
================================================
FILE: python/dynamic/num_paths_nm_matrix.py
================================================
"""
Problem Statement
=================
Count the number of Paths from 1,1 to N,M in an NxM matrix.
Analysis
--------
* Dynamic Programing Solution: O(rows * cols)
* Recursive: O(2^rows) if rows > cols else O(2^cols)
References
----------
* http://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
"""
def num_paths_matrix(rows, cols):
T = [[1 if row == 0 or col == 0 else 0 for row in range(cols)] for col in range(rows)]
for row in range(1, rows):
for col in range(1, cols):
T[row][col] = T[row - 1][col] + T[row][col - 1]
return T[rows - 1][cols - 1]
def num_paths_matrix_recursive(rows, cols):
if rows == 1 or cols == 1:
return 1
return num_paths_matrix(rows-1, cols) + num_paths_matrix(rows, cols - 1)
if __name__ == '__main__':
rows = 3
cols = 3
expected = 6
assert expected == num_paths_matrix(rows, cols)
assert expected == num_paths_matrix_recursive(rows, cols)
================================================
FILE: python/dynamic/num_trees_preorder.py
================================================
"""
Problem Statement
=================
Given the number of nodes N, in a pre-order sequence how many unique trees can be created? Number of tree is exactly
same as number of unique BST create with array of size n. The solution is a catalan number.
Complexity
----------
* Dynamic Programming: O(n^2)
* Recursive Solution: O(2^n)
Video
-----
* https://youtu.be/RUB5ZPfKcnY
"""
def num_trees(num_nodes):
T = [0 for _ in range(num_nodes + 1)]
T[0] = 1
T[1] = 1
for n in range(2, num_nodes + 1):
for j in range(0, n):
T[n] += T[j] * T[n - j - 1]
return T[num_nodes]
def num_trees_recursive(num_nodes):
if num_nodes == 0 or num_nodes == 1:
return 1
result = 0
for n in range(1, num_nodes + 1):
result += num_trees_recursive(n - 1) * num_trees_recursive(num_nodes - n)
return result
if __name__ == '__main__':
assert 5 == num_trees(3)
assert 14 == num_trees(4)
assert 42 == num_trees(5)
assert 5 == num_trees_recursive(3)
assert 14 == num_trees_recursive(4)
assert 42 == num_trees_recursive(5)
================================================
FILE: python/dynamic/optimal_bst.py
================================================
"""
Problem Statement
=================
Given a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the
number of searches to keys[i]. Construct a binary search tree of all keys such that the total cost of all the searches
is as small as possible.
Video
-----
* https://youtu.be/hgA4xxlVvfQ
Analysis
--------
* Recursive: Exponential O(n^n)
* Dynamic Programming: O(n^3)
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-24-optimal-binary-search-tree/
"""
def min_cost_bst(input_array, freq):
size = rows = cols = len(input_array)
T = [[0 for _ in range(cols)] for _ in range(rows)]
for idx in range(rows):
T[idx][idx] = freq[idx]
for sub_tree_size in range(2, size + 1):
for start in range(size + 1 - sub_tree_size):
end = start + sub_tree_size - 1
T[start][end] = float("inf")
total = sum(freq[start:end + 1])
for k in range(start, end + 1):
val = total + (0 if k - 1 < 0 else T[start][k - 1]) + (0 if k + 1 > end else T[k + 1][end])
T[start][end] = min(val, T[start][end])
return T[0][-1]
def min_cost_bst_recursive_helper(input_array, freq, low_index, high_index, level):
if low_index > high_index:
return 0
min_value = float("inf")
for index in range(low_index, high_index + 1):
val = (min_cost_bst_recursive_helper(input_array, freq, low_index, index - 1, level + 1) # left tree
+ level * freq[index] # value at level
+ min_cost_bst_recursive_helper(input_array, freq, index + 1, high_index, level + 1)) # right tree
min_value = min(val, min_value)
return min_value
def min_cost_bst_recursive(input_array, freq):
return min_cost_bst_recursive_helper(input_array, freq, 0, len(input_array) - 1, 1)
if __name__ == '__main__':
input_array = [10, 12, 16, 21]
freq = [4, 2, 6, 3]
expected = 26
assert expected == min_cost_bst(input_array, freq)
assert expected == min_cost_bst_recursive(input_array, freq)
input_array = [10, 12, 20, 35, 46]
freq = [34, 8, 50, 21, 16]
expected = 232
assert expected == min_cost_bst(input_array, freq)
assert expected == min_cost_bst_recursive(input_array, freq)
================================================
FILE: python/dynamic/stockbuysellktransactions.py
================================================
""""
Problem Statement
=================
Given certain stock values over a period of days (d days) and a number K, the number of transactions allowed, find the
maximum profit that be obtained with at most K transactions.
Video
-----
* https://youtu.be/oDhu5uGq_ic
Complexity
----------
* Space Complexity O(days * transctions)
* Time Complexity: Slow Solution O (days^2 * transactions), Faster Solution O(days * transaction)
"""
def max_profit(prices, K):
if K == 0 or prices == []:
return 0
days = len(prices)
num_transactions = K + 1 # 0th transaction up to and including kth transaction is considered.
T = [[0 for _ in range(days)] for _ in range(num_transactions)]
for transaction in range(1, num_transactions):
max_diff = - prices[0]
for day in range(1, days):
T[transaction][day] = max(T[transaction][day - 1], # No transaction
prices[day] + max_diff) # price on that day with max diff
max_diff = max(max_diff,
T[transaction - 1][day] - prices[day]) # update max_diff
print_actual_solution(T, prices)
return T[-1][-1]
def max_profit_slow_solution(prices, K):
if K == 0 or prices == []:
return 0
days = len(prices)
num_transactions = K + 1
T = [[0 for _ in range(len(prices))] for _ in range(num_transactions)]
for transaction in range(1, num_transactions):
for day in range(1, days):
# This maximum value of either
# a) No Transaction on the day. We pick the value from day - 1
# b) Max profit made by selling on the day plus the cost of the previous transaction, considered over m days
T[transaction][day] = max(T[transaction][day - 1],
max([(prices[day] - prices[m] + T[transaction - 1][m]) for m in range(day)]))
print_actual_solution(T, prices)
return T[-1][-1]
def print_actual_solution(T, prices):
transaction = len(T) - 1
day = len(T[0]) - 1
stack = []
while True:
if transaction == 0 or day == 0:
break
if T[transaction][day] == T[transaction][day - 1]: # Didn't sell
day -= 1
else:
stack.append(day) # sold
max_diff = T[transaction][day] - prices[day]
for k in range(day - 1, -1, -1):
if T[transaction - 1][k] - prices[k] == max_diff:
stack.append(k) # bought
transaction -= 1
break
for entry in range(len(stack) - 1, -1, -2):
print("Buy on day {day} at price {price}".format(day=stack[entry], price=prices[stack[transaction]]))
print("Sell on day {day} at price {price}".format(day=stack[entry], price=prices[stack[transaction - 1]]))
if __name__ == '__main__':
prices = [2, 5, 7, 1, 4, 3, 1, 3]
assert 10 == max_profit(prices, 3)
assert 10 == max_profit_slow_solution(prices, 3)
================================================
FILE: python/dynamic/string_interleaving.py
================================================
"""
Problem Statement
=================
Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. C is said to be
interleaving A and B, if it contains all characters of A and B and order of all characters in individual strings is
preserved.
http://www.geeksforgeeks.org/check-whether-a-given-string-is-an-interleaving-of-two-other-given-strings-set-2/
Video: https://www.youtube.com/watch?v=ih2OZ9-M3OM
"""
def is_interleaved_recursive(str1, str2, str3, pos1, pos2, pos3):
if pos1 == len(str1) and pos2 == len(str2) and pos3 == len(str3):
return True
if pos3 == len(str3):
return False
return (((pos1 < len(str1) and str1[pos1] == str3[pos3]) and is_interleaved_recursive(str1, str2, str3, pos1 + 1, pos2, pos3 + 1)) or
(pos2 < len(str2) and str2[pos2] == str3[pos3]) and is_interleaved_recursive(str1, str2, str3, pos1, pos2 + 1, pos3 + 1))
def is_interleaved(str1, str2, str3):
if len(str3) != (len(str1) + len(str2)):
return False
cols = len(str1) + 1
rows = len(str2) + 1
T = [[False for _ in range(cols)] for _ in range(rows)]
for row in range(rows):
for col in range(cols):
index = row + col - 1
if row == 0 and col == 0:
T[row][col] = True
elif row == 0:
if str3[index] == str1[col - 1]:
T[row][col] = True and T[row][col - 1]
elif col == 0:
if str3[index] == str2[row - 1]:
T[row][col] = True and T[row - 1][col]
else:
T[row][col] = ((T[row][col - 1] if str3[index] == str1[col - 1] else False) or
(T[row - 1][col] if str3[index] == str2[row - 1] else False))
return T[rows - 1][cols - 1]
if __name__ == '__main__':
str1 = "XXYM"
str2 = "XXZT"
str3 = "XXXZXYTM"
assert True == is_interleaved(str1, str2, str3)
assert True == is_interleaved_recursive(str1, str2, str3, 0, 0, 0)
================================================
FILE: python/dynamic/sub_rectangular_maximum_sum.py
================================================
"""
Problem Statement
=================
Write a program to find maximum sum rectangle in give 2D matrix. Assume there is at least one positive number in the 2D
matrix.
Solution:
--------
* Keep temp array with size as number of rows. Start left and right from 0 and keep adding values for each row and
maintain them in this temp array.
* Run Kadane's algorithm to find max sum subarray in temp. Now increment right by 1.
* When right reaches last column reset right to 1 and left to 1.
Analysis
--------
* Space complexity of this algorithm is O(row)
* Time complexity of this algorithm is O(row*col*col)
Video
-----
* https://youtu.be/yCQN096CwWM
References
----------
* http://www.geeksforgeeks.org/dynamic-programming-set-27-max-sum-rectangle-in-a-2d-matrix/
"""
from collections import namedtuple
Result = namedtuple("Result","maxSum leftBound rightBound upBound lowBound")
KadanesResult = namedtuple("KadanesResult","maxSum start end")
def kadanes(temp):
max = 0
maxStart = -1
maxEnd = -1
currentStart = 0
maxSoFar = 0
for i in range(0, len(temp)):
maxSoFar += temp[i]
if maxSoFar < 0:
maxSoFar = 0
currentStart = i + 1
if maxSoFar > max:
maxStart = currentStart
maxEnd = i
max = maxSoFar
return KadanesResult(max, maxStart, maxEnd)
def max_sub_sub_rectangle(rectangle):
rows = len(rectangle)
cols = len(rectangle[0])
result = Result(float("-inf"), -1, -1, -1, -1)
for left in range(cols):
temp = [0 for _ in range(rows)]
for right in range(left, cols):
for i in range(rows):
temp[i] += rectangle[i][right]
kadanes_result = kadanes(temp)
if kadanes_result.maxSum > result.maxSum:
result = Result(kadanes_result.maxSum, left, right, kadanes_result.start, kadanes_result.end)
return result
if __name__ == '__main__':
rectangle = [[2, 1, -3, -4, 5],
[0, 6, 3, 4, 1],
[2, -2, -1, 4, -5],
[-3, 3, 1, 0, 3]]
result = max_sub_sub_rectangle(rectangle)
assert 18 == result.maxSum
print result
================================================
FILE: python/dynamic/subset_sum.py
================================================
"""
Problem Statement
=================
Given an array of non negative numbers and a total, is there subset of numbers in this array which adds up to given
total. Another variation is given an array is it possible to split it up into 2 equal sum partitions. Partition need not
be equal sized. Just equal sum.
Video
-----
* https://youtu.be/s6FhG--P7z0
Solution
--------
* Time complexity is O(input.size * total_sum)
* Space complexity is O(input.size*total_sum)
Reference
---------
* https://en.wikipedia.org/wiki/Subset_sum_problem
"""
def subset_sum(sequence, sum_value):
cols = sum_value + 1 # Plus 1 for 0 valued col.
rows = len(sequence) + 1 # Plus 1 for 0 valued row.
T = [[False for _ in range(cols)] for _ in range(rows)]
for row in range(rows):
T[row][0] = True
for index_i in range(1, rows):
for index_j in range(1, cols):
if index_j >= sequence[index_i - 1]:
T[index_i][index_j] = T[index_i - 1][index_j] or T[index_i - 1][index_j - sequence[index_i - 1]]
else:
T[index_i][index_j] = T[index_i - 1][index_j]
return T[rows - 1][cols - 1]
def partition(sequence):
sequence_sum = sum(sequence)
if sequence_sum % 2 != 0:
return False
expected = sequence_sum / 2
return subset_sum(sequence, expected)
if __name__ == '__main__':
sequence = [2, 3, 7, 8]
assert True == subset_sum(sequence, 11)
sequence = [1, 3, 5, 5, 2, 1, 1, 6]
assert True == partition(sequence)
================================================
FILE: python/dynamic/symbolexpressionevaluation.py
================================================
"""
Problem Statement
=================
Let there be a binary operation for 3 symbols a, b, c and result of these binary operation given in a table.
Given an expression of these 3 symbols and a final result, tell if this expression can be parenthesize in certain
way to produce the final result.
Complexity
----------
* Run time Complexity: O(n^3)
* SpaceL O(n^2)
Where n is the length of the expression.
"""
def evaluate_expression(expression_map, expression, result):
expression_length = len(expression)
T = [[set() for _ in range(expression_length)] for _ in range(len(expression))]
for idx, expr in enumerate(expression):
T[idx][idx].add(expr)
# We take a sub expression of length 2 until the total expression length
for sub_length in range(2, expression_length + 1):
for left_index in range(0, expression_length - sub_length + 1):
right_index = left_index + sub_length - 1
# we split the expression at different k indices for the total sub-expression length and store the result.
# at T[left_index][right_index]
# Like bbc, will be treated for (b(bc) and ((bb) c) and the final result is stored in a set at T[0][2]
for k in range(left_index, right_index):
for expr1 in T[left_index][k]:
for expr2 in T[k+1][right_index]:
T[left_index][right_index].add(expression_map[(expr1, expr2)])
for expr in T[0][-1]:
if result in expr:
return True
return False
if __name__ == '__main__':
expressions = ['a', 'b', 'c']
# expression table denotes the binary operation between two expression and its result.
expression_table = [
['b', 'b', 'a'],
['c', 'b', 'a'],
['a', 'a', 'c']
]
# For convenience, we can modify it to be more explicit and use the expression table
expression_map = {
('a', 'a'): 'b',
('a', 'b'): 'b',
('a', 'c'): 'a',
('b', 'a'): 'c',
('b', 'b'): 'b',
('b', 'c'): 'a',
('c', 'a'): 'a',
('c', 'b'): 'a',
('c', 'c'): 'c'
}
assert True == evaluate_expression(expression_map, 'bbbbac', 'a')
================================================
FILE: python/dynamic/weighted_job_scheduling_max_profit.py
================================================
"""
Problem Statement
=================
Given set of jobs with start and end interval and profit, how to maximize profit such that jobs in subset do not
overlap.
Video
-----
* https://youtu.be/cr6Ip0J9izc
Complexity
----------
* Runtime Complexity: O(n^2)
* Space Complexity: O(n)
Reference Link
--------------
* http://www.cs.princeton.edu/courses/archive/spr05/cos423/lectures/06dynamic-programming.pdf
"""
def can_sequence(job1, job2):
_, job1_finish_time = job1
job2_start_time, _ = job2
return job1_finish_time <= job2_start_time
def find_max_profit(jobs):
sequenced_jobs = sorted(jobs.keys(), key=lambda x: x[1])
T = [jobs[job_key] for job_key in sequenced_jobs]
num_jobs = len(sequenced_jobs)
for j in range(1, num_jobs):
for i in range(0, j):
if can_sequence(sequenced_jobs[i], sequenced_jobs[j]):
T[j] = max(T[j], T[i] + jobs[sequenced_jobs[j]])
return max(T)
if __name__ == '__main__':
jobs = {
(1, 3): 5, # (start_time, end_time, total_cost)
(2, 5): 6,
(4, 6): 5,
(6, 7): 4,
(5, 8): 11,
(7, 9): 2
}
assert 17 == find_max_profit(jobs)
================================================
FILE: python/geometry/skylinedrawing.py
================================================
# https://leetcode.com/problems/the-skyline-problem/
class BuildingPoint(object):
def __init__(self, point, is_start, height):
self.point = point;
self.is_start = is_start
self.height = height
def __lt__(self, other):
if self.point != other.point:
return self.point < other.point
else:
if self.is_start:
h1 = -self.height
else:
h1 = self.height
if other.is_start:
h2 = -other.height;
else:
h2 = other.height
return h1 < h2
def get_skyline(buildings):
building_points = []
for building in buildings:
building_points.append(BuildingPoint(building[0], True, building[2]))
building_points.append(BuildingPoint(building[1], False, building[2]))
building_points = sorted(building_points)
queue = {}
queue[0] = 1
prev_max_height = 0
result = []
for building_point in building_points:
if building_point.is_start:
if building_point.height in queue:
queue[building_point.height] = queue[building_point.height] + 1
else:
queue[building_point.height] = 1
else:
if queue[building_point.height] == 1:
del queue[building_point.height]
else:
queue[building_point.height] = queue[building_point.height] - 1
current_max_height = max(queue.keys())
if prev_max_height != current_max_height:
result.append([building_point.point, current_max_height])
prev_max_height = current_max_height
return result
if __name__ == '__main__':
buildings = [[1, 3, 4], [3, 4, 4], [2, 6, 2], [8, 11, 4], [7, 9, 3], [10, 11, 2]]
print(get_skyline(buildings))
================================================
FILE: python/graph/cycledirectedgraph.py
================================================
# detect cycle in directed graph
# https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/CycleInDirectedGraph.java
from graph import *
def has_cycle(graph):
white = set()
gray = set()
black = set()
for vertex in graph.all_vertex.values():
white.add(vertex)
while len(white) > 0:
current = next(iter(white))
if dfs(current, white, gray, black) == True:
return True
return False
def dfs(current, white, gray, black):
move_vertex(current, white, gray)
for neighbor in current.adjacent_vertices:
if neighbor in black:
continue
if neighbor in gray:
return True
if dfs(neighbor, white, gray, black) == True:
return True
move_vertex(current, gray, black)
return False
def move_vertex(vertex, source_set, destination_set):
source_set.remove(vertex)
destination_set.add(vertex)
if __name__ == '__main__':
graph = Graph(True)
graph.add_edge(1,2)
graph.add_edge(1,3)
graph.add_edge(2,3)
graph.add_edge(4,1)
graph.add_edge(4,5)
graph.add_edge(5,6)
graph.add_edge(6,4)
print(has_cycle(graph));
================================================
FILE: python/graph/cycleundirectedgraph.py
================================================
# detect cycle in undirected graph
# https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/CycleUndirectedGraph.java
from graph import *
from disjointset import *
def has_cycle_dfs(graph):
visited = set()
for vertex in graph.all_vertex.values():
if vertex in visited:
continue
flag = has_cycle_dfs_util(vertex, visited, None)
if flag:
return True
return False
def has_cycle_dfs_util(vertex, visited, parent):
visited.add(vertex)
for adjacent in vertex.adjacent_vertices:
if parent is not None and adjacent == parent:
continue
if adjacent in visited:
return True
has_cycle = has_cycle_dfs_util(adjacent, visited, vertex)
if has_cycle:
return True
return False
def has_cycle_using_disjoint_set(graph):
disjoint_set = DisjointSet()
for vertex in graph.all_vertex.values():
disjoint_set.make_set(vertex.id)
for edge in graph.all_edges:
parent1 = disjoint_set.find_set(edge.vertex1.id)
parent2 = disjoint_set.find_set(edge.vertex2.id)
if parent1 == parent2:
return True
disjoint_set.union(edge.vertex1.id, edge.vertex2.id)
return False
if __name__ == '__main__':
graph = Graph(False)
graph.add_edge(0,1)
graph.add_edge(1,2)
graph.add_edge(0,3)
graph.add_edge(3,4)
graph.add_edge(4,5)
graph.add_edge(5,1)
has_cycle1 = has_cycle_dfs(graph)
has_cycle2 = has_cycle_using_disjoint_set(graph)
print(str(has_cycle1) + " " + str(has_cycle2))
================================================
FILE: python/graph/dijkstrashortestpath.py
================================================
#dijkstra's algorithm
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/DijkstraShortestPath.java
from priorityqueue import PriorityQueue
from graph import Graph
import sys
def shortest_path(graph, sourceVertex):
min_heap = PriorityQueue(True)
distance = {}
parent = {}
for vertex in graph.all_vertex.values():
min_heap.add_task(sys.maxsize, vertex)
min_heap.change_task_priority(0, sourceVertex)
distance[sourceVertex] = 0
parent[sourceVertex] = None
while min_heap.is_empty() is False:
task = min_heap.peek_task()
weight = min_heap.get_task_priority(task)
current = min_heap.pop_task()
distance[current] = weight
for edge in current.edges:
adjacent = get_other_vertex_for_edge(current, edge)
if min_heap.contains_task(adjacent) is False:
continue
new_distance = distance[current] + edge.weight;
if min_heap.get_task_priority(adjacent) > new_distance:
min_heap.change_task_priority(new_distance, adjacent)
parent[adjacent] = current
return distance
def get_other_vertex_for_edge(vertex, edge):
if edge.vertex1.id == vertex.id:
return edge.vertex2
else:
return edge.vertex1
if __name__ == '__main__':
graph = Graph(False)
graph.add_edge(1,2,5)
graph.add_edge(2,3,2)
graph.add_edge(1,4,9)
graph.add_edge(1,5,3)
graph.add_edge(5,6,2)
graph.add_edge(6,4,2)
graph.add_edge(3,4,3)
distance = shortest_path(graph, graph.all_vertex[1])
print(distance)
================================================
FILE: python/graph/disjointset.py
================================================
# disjoint sets
# https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/DisjointSet.java
class Node(object):
def __init__(self, data, parent = None, rank = 0):
self.data = data
self.parent = parent
self.rank = rank
def __str__(self):
return str(self.data)
def __repr__(self):
return self.__str__()
class DisjointSet(object):
def __init__(self):
self.map = {}
def make_set(self, data):
node = Node(data)
node.parent = node
self.map[data] = node
def union(self, data1, data2):
node1 = self.map[data1]
node2 = self.map[data2]
parent1 = self.find_set_util(node1)
parent2 = self.find_set_util(node2)
if parent1.data == parent2.data:
return
if parent1.rank >= parent2.rank:
if parent1.rank == parent2.rank:
parent1.rank = parent1.rank + 1
parent2.parent = parent1
else:
parent1.parent = parent2
def find_set(self, data):
return self.find_set_util(self.map[data])
def find_set_util(self, node):
parent = node.parent
if parent == node:
return parent
node.parent = self.find_set_util(node.parent)
return node.parent
if __name__ == '__main__':
ds = DisjointSet()
ds.make_set(1)
ds.make_set(2)
ds.make_set(3)
ds.make_set(4)
ds.make_set(5)
ds.make_set(6)
ds.make_set(7)
ds.union(1,2)
ds.union(2,3)
ds.union(4,5)
ds.union(6,7)
ds.union(5,6)
ds.union(3,7)
for i in range(1,8):
print(ds.find_set(i))
================================================
FILE: python/graph/floydwarshall.py
================================================
# floyd warshall all pair shortest path
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/FloydWarshallAllPairShortestPath.java
import sys
INF = 1000000
class NegativeWeightCycleException(Exception):
def __init__(self):
pass
def all_pair_shortest_path(distance_matrix):
size = len(distance_matrix)
distance = [[0 for x in range(size)]
for x in range (size)]
path = [[0 for x in range(size)]
for x in range (size)]
for i in range(size):
for j in range(size):
distance[i][j] = distance_matrix[i][j]
if distance_matrix[i][j] != INF and i != j:
path[i][j] = i
else:
path[i][j] = -1
for k in range(size):
for i in range(size):
for j in range(size):
if distance[i][k] == INF or distance[k][j] == INF:
continue
if distance[i][j] > distance[i][k] + distance[k][j]:
distance[i][j] = distance[i][k] + distance[k][j]
path[i][j] = path[k][j]
for i in range(size):
if distance[i][i] < 0:
raise NegativeWeightCycleException()
print_path(path, 3, 2)
return (distance, path)
def print_path(path, start, end):
stack = []
stack.append(end)
while True:
end = path[start][end]
if end == -1:
return
stack.append(end)
if end == start:
break
print(stack[::-1])
if __name__ == '__main__':
distance_matrix = [[0, 3, 6, 15],
[INF, 0, -2, INF],
[INF, INF, 0, 2],
[1, INF, INF, 0]]
distance, path = all_pair_shortest_path(distance_matrix)
print(distance)
#print(path)
================================================
FILE: python/graph/fordfulkerson.py
================================================
#ford fulkerson method Edomonds Karp algorithm for finding max flow
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/FordFulkerson.java
from queue import Queue
import sys
def max_flow(capacity, source, sink):
residual_capacity = [x[:] for x in capacity]
augmented_paths = []
max_flow = 0
while True:
found_augmented_path, parent = bfs(residual_capacity, source, sink)
if not found_augmented_path:
break
augmented_path = []
v = sink
flow = sys.maxsize
while not v == source:
augmented_path.append(v)
u = parent[v]
if flow > residual_capacity[u][v]:
flow = residual_capacity[u][v]
v = u
augmented_path.append(source)
augmented_paths.append(augmented_path[::-1])
max_flow += flow
v = sink
while not v == source:
u = parent[v]
residual_capacity[u][v] -= flow
residual_capacity[v][u] += flow
v = u
print("Augmented path")
print(augmented_paths)
return max_flow
def bfs(residual_capacity, source, sink):
visited = set()
queue = Queue()
parent = {}
queue.put(source)
visited.add(source)
found_augmented_path = False
while not queue.empty():
u = queue.get()
for v in range(len(residual_capacity)):
if v not in visited and residual_capacity[u][v] > 0:
parent[v] = u
visited.add(v)
queue.put(v)
if v == sink:
found_augmented_path = True
break;
return found_augmented_path, parent
if __name__ == '__main__':
capacity = [[0, 3, 0, 3, 0, 0, 0],
[0, 0, 4, 0, 0, 0, 0],
[3, 0, 0, 1, 2, 0, 0],
[0, 0, 0, 0, 2, 6, 0],
[0, 1, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 9],
[0, 0, 0, 0, 0, 0, 0]]
max_val = max_flow(capacity, 0, 6)
print(max_val)
================================================
FILE: python/graph/graph.py
================================================
#Graph class
# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/Graph.java
class Graph(object):
def __init__(self, is_directed):
self.all_edges = []
self.all_vertex = {}
self.is_directed = is_directed
def add_edge(self, id1, id2, weight=0):
if id1 in self.all_vertex:
vertex1 = self.all_vertex[id1]
else:
vertex1 = Vertex(id1)
self.all_vertex[id1] = vertex1
if id2 in self.all_vertex:
vertex2 = self.all_vertex[id2]
else:
vertex2 = Vertex(id2)
self.all_vertex[id2] = vertex2
edge = Edge(vertex1, vertex2, self.is_directed, weight)
self.all_edges.append(edge)
vertex1.add_adjacent_vertex(edge, vertex2)
if self.is_directed is not True:
vertex2.add_adjacent_vertex(edge,vertex1)
class Edge(object):
def __init__(self, vertex1, vertex2, is_directed, weight):
self.vertex1 = vertex1
self.vertex2 = vertex2
self.is_directed = is_directed
self.weight = weight
def __eq__(self, other):
return self.vertex1.id == other.vertex1.id and self.vertex2.id == other.vertex2.id
def __hash(self):
return hash(vertex1) + hash(vertex2)
def __str__(self):
return "Edge " + str(self.vertex1) + " " + str(self.vertex2) + " Weight-" + str(self.weight)
def __repr__(self):
return self.__str__()
class Vertex(object):
def __init__(self, id):
self.id = id;
self.edges = []
self.adjacent_vertices = []
def add_adjacent_vertex(self, edge, vertex):
self.edges.append(edge)
self.adjacent_vertices.append(vertex)
def get_degree(self):
return len(self.edges)
def __eq__(self, other):
return self.id == other.id
def __hash__(self):
return hash(self.id)
def __str__(self):
return str("Vertex-" + str(self.id))
def __repr__(self):
return self.__str__();
def __lt__(self, other):
return self.id < other.id
def __gt__(self, other):
return self.id > other.id
if __name__ == '__main__':
g = Graph(False)
g.add_edge(1,2,10)
g.add_edge(2,3,5)
g.add_edge(1,4,6)
for edge in g.all_edges:
print(edge)
for vertex in g.all_vertex:
print("Vertex " + str(g.all_vertex[vertex]))
for edge in g.all_vertex[vertex].edges:
print("Edge " + str(edge))
================================================
FILE: python/graph/graphtraversal.py
================================================
#doing BFS and DFS traversal of the graph
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/GraphTraversal.java
from graph import *
import queue
def dfs_util(v, visited):
if v in visited:
return
visited.add(v)
print(v)
for vertex in v.adjacent_vertices:
dfs_util(vertex, visited)
def dfs(graph):
visited = set()
for id in graph.all_vertex:
dfs_util(graph.all_vertex[id], visited)
def bfs(graph):
q = queue.Queue()
visited = set()
for vertex in graph.all_vertex.values():
if vertex not in visited:
q.put(vertex)
visited.add(vertex)
while not q.empty():
v = q.get();
print(v)
for adj in v.adjacent_vertices:
if adj not in visited:
q.put(adj)
visited.add(adj)
if __name__ == '__main__':
g = Graph(False)
g.add_edge(1,2,10)
g.add_edge(2,3,5)
g.add_edge(1,4,6)
dfs(g)
bfs(g)
================================================
FILE: python/graph/kruskalmst.py
================================================
# kruskal minimum spanning tree
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/KruskalMST.java
from disjointset import *
from graph import *
def get_key(edge):
return edge.weight
def minimum_spanning_tree(graph):
disjoint_set = DisjointSet()
sorted_edges = sorted(graph.all_edges, key = get_key)
print(sorted_edges)
for vertex in graph.all_vertex.values():
disjoint_set.make_set(vertex.id)
result_edge = []
for edge in sorted_edges:
root1 = disjoint_set.find_set(edge.vertex1.id)
root2 = disjoint_set.find_set(edge.vertex2.id)
if root1 == root2:
continue
else:
result_edge.append(edge)
disjoint_set.union(edge.vertex1.id, edge.vertex2.id)
return result_edge
if __name__ == '__main__':
graph = Graph(False)
graph.add_edge(1,3,1)
graph.add_edge(1,2,4)
graph.add_edge(2,4,2)
graph.add_edge(2,5,1)
graph.add_edge(2,6,3)
graph.add_edge(3,4,5)
graph.add_edge(3,7,8)
graph.add_edge(4,7,2)
graph.add_edge(6,5,2)
graph.add_edge(6,4,3)
result = minimum_spanning_tree(graph)
for edge in result:
print(edge)
================================================
FILE: python/graph/primmst.py
================================================
#Prim's MST
# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/PrimMST.java
from graph import Graph
from priorityqueue import PriorityQueue
import sys
def minimum_spanning_tree(graph):
min_heap = PriorityQueue(True)
vertex_to_edge = {}
result = []
for vertex in graph.all_vertex.values():
min_heap.add_task(sys.maxsize, vertex)
start_vertex = next(iter((graph.all_vertex.values())))
min_heap.change_task_priority(0, start_vertex)
while min_heap.is_empty() is False:
current = min_heap.pop_task()
if(current in vertex_to_edge):
spanning_tree_edge = vertex_to_edge[current]
result.append(spanning_tree_edge)
for edge in current.edges:
adjacent = get_other_vertex_for_edge(current, edge)
if min_heap.contains_task(adjacent) is True and min_heap.get_task_priority(adjacent) > edge.weight:
min_heap.change_task_priority(edge.weight, adjacent)
vertex_to_edge[adjacent] = edge
return result
def get_other_vertex_for_edge(vertex, edge):
if edge.vertex1.id == vertex.id:
return edge.vertex2
else:
return edge.vertex1
if __name__ == '__main__':
graph = Graph(False)
graph.add_edge(1,2,3)
graph.add_edge(2,3,1)
graph.add_edge(3,1,1)
graph.add_edge(1,4,1)
graph.add_edge(2,4,3)
graph.add_edge(4,5,6)
graph.add_edge(5,6,2)
graph.add_edge(3,5,5)
graph.add_edge(3,6,4)
result = minimum_spanning_tree(graph)
print(result)
================================================
FILE: python/graph/priorityqueue.py
================================================
# add to heapq things like removing any item and changing key value
# implementation of priority queue to support contains, change_task_priority
# and remove_task in log time
from heapq import *
class PriorityQueue(object):
def __init__(self, is_min_heap):
self.pq = []
self.entry_finder = {}
if(is_min_heap is True):
self.mul = 1
else :
self.mul = -1
def contains_task(self, task):
if task in self.entry_finder:
return True
else:
return False
def get_task_priority(self, task):
if task in self.entry_finder:
return (self.entry_finder[task])[0]
raise ValueError("task does not exist")
def add_task(self, priority, task):
if task in self.entry_finder:
raise KeyError("Key already exists")
entry = [self.mul*priority, False, task]
self.entry_finder[task] = entry
heappush(self.pq, entry)
def change_task_priority(self, priority, task):
if task not in self.entry_finder:
raise KeyError("Task not found")
self.remove_task(task)
entry = [self.mul*priority, False, task]
self.entry_finder[task] = entry
heappush(self.pq, entry)
def remove_task(self, task):
entry = self.entry_finder.pop(task)
entry[1] = True
def pop_task(self):
while self.pq:
priority, removed, task = heappop(self.pq)
if removed is False:
del self.entry_finder[task]
return task
raise KeyError("pop from an empty priority queue")
def peek_task(self):
while self.pq:
priority, removed, task = tuple(heappop(self.pq))
if removed is False:
heappush(self.pq, [priority, False, task])
return task
raise KeyError("pop from an empty priority queue")
def is_empty(self):
try:
self.peek_task()
return False
except KeyError:
return True
def __str__(self):
return str(self.entry_finder) + " " + str(self.pq)
if __name__ == '__main__':
task1 = "Tushar"
task2 = "Roy"
task3 = "is"
task4 = "coder"
min_pq = PriorityQueue(True)
min_pq.add_task(1, task1)
min_pq.add_task(3, task2)
min_pq.add_task(6, task3)
min_pq.add_task(7, task4)
print(min_pq.contains_task(task3))
print(min_pq.get_task_priority(task3))
print(min_pq)
while min_pq.is_empty() is False:
print(min_pq.pop_task())
max_pq = PriorityQueue(False)
max_pq.add_task(1, task1)
max_pq.add_task(3, task2)
max_pq.add_task(6, task3)
max_pq.add_task(7, task4)
while max_pq.is_empty() is False:
print(max_pq.pop_task())
================================================
FILE: python/graph/topologicalsort.py
================================================
#topological sort
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/TopologicalSort.java
from graph import Graph
def top_sort(graph):
stack = []
visited = set()
for vertex in graph.all_vertex.values():
if vertex in visited:
continue
top_sort_util(vertex, stack, visited)
return stack
def top_sort_util(vertex, stack, visited):
visited.add(vertex)
for adjacent in vertex.adjacent_vertices:
if adjacent in visited:
continue
top_sort_util(adjacent, stack, visited)
stack.append(vertex)
if __name__ == '__main__':
graph = Graph(True)
graph.add_edge(1,3)
graph.add_edge(1,2)
graph.add_edge(3,4)
graph.add_edge(5,6)
graph.add_edge(6,3)
graph.add_edge(3,8)
graph.add_edge(8,11)
stack = top_sort(graph)
print(stack[::-1])
================================================
FILE: python/recursion/setpairtogether.py
================================================
# http://www.geeksforgeeks.org/minimum-number-of-swaps-required-for-arranging-pairs-adjacent-to-each-other/
def find_minimum_swaps(input, pair):
index = {}
for i, val in enumerate(input):
index[val] = i
return find_minimum_swaps_util(input, pair, index, 0)
def find_minimum_swaps_util(input, pair, index, current):
if current == len(input):
return 0
v1 = input[current]
v2 = input[current + 1]
pv2 = pair[v1]
if pv2 == v2:
return find_minimum_swaps_util(input, pair, index, current + 2)
else:
idx1 = index.get(v1)
idx2 = index.get(v2)
idx3 = index.get(pair[v1])
idx4 = index.get(pair[v2])
swap(index, input, idx2, idx3)
val1 = find_minimum_swaps_util(input, pair, index, current+2)
swap(index, input, idx2, idx3)
swap(index, input, idx1, idx4)
val2 = find_minimum_swaps_util(input, pair, index, current+2)
swap(index, input, idx1, idx4)
return 1 + max(val1, val2)
def swap(index, input, i, j):
index[input[i]] = j
index[input[j]] = i
t = input[i]
input[i] = input[j]
input[j] = t
if __name__ == '__main__':
input = [3, 5, 6, 4, 1, 2]
pair = {}
pair[1] = 3
pair[3] = 1
pair[2] = 6
pair[6] = 2
pair[4] = 5
pair[5] = 4
print(find_minimum_swaps(input, pair))
================================================
FILE: python/recursion/stringpermutation.py
================================================
# string permutation in lexicographically order with repetition of characters in the string
def permute(input):
count_map = {}
for ch in input:
if ch in count_map.keys():
count_map[ch] = count_map[ch] + 1
else:
count_map[ch] = 1
keys = sorted(count_map)
str = []
count = []
for key in keys:
str.append(key)
count.append(count_map[key])
result = [0 for x in range(len(input))]
permute_util(str, count, result, 0)
def permute_util(str, count, result, level):
if level == len(result):
print(result)
return
for i in range(len(str)):
if count[i] == 0:
continue;
result[level] = str[i]
count[i] -= 1
permute_util(str, count, result, level + 1)
count[i] += 1
if __name__ == '__main__':
input = ['B', 'C', 'A', 'A']
permute(input)
================================================
FILE: python/string/Z_Algorithm.py
================================================
#author: Pankaj Kumar
#time complexity: O(length(string) + length(pattern))
#space complexity: O(length(string) + length(pattern))
#Link to theory: http://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/
def z_algo(arr):
z = [0 for i in range(len(arr))]
left , right = 0 , 0
for k in range(1 , len(arr)):
if k > right:
left = k
right = k
while right < len(arr) and arr[right] == arr[right-left]:
right += 1
z[k] = right - left
right -= 1
else:
k1 = k - left
if z[k1] < right - k + 1:
z[k] = z[k1]
else:
left = k
while right < len(arr) and arr[right] == arr[right-left]:
right += 1
z[k] = right - left
right -= 1
return z
def makepattern(string , pattern):
n , m = len(string) , len(pattern)
str_arr = []
for i in range(m):
str_arr.append(pattern[i])
str_arr.append('$')
for i in range(n):
str_arr.append(string[i])
z_values = z_algo(str_arr)
result = []
for i in range(len(z_values)):
if z_values[i] == m:
result.append(i - m - 1)
print result
if __name__ == '__main__':
string = 'abcdeabcd'
pattern = 'abc'
makepattern(string , pattern)
================================================
FILE: python/string/knuthmorrispratt.py
================================================
# Knuth-Morris-Pratt algorithm
# Compute temporary array to maintain size of suffix which is same as prefix
# Time/space complexity is O(size of pattern)
def compute_temporary_array(pattern):
n = len(pattern)
lsp = [0 for j in range(n)]
index = 0
i = 1
while i < len(pattern):
if pattern[i] == pattern[index]:
lsp[i] = index + 1
index += 1
i += 1
else:
if index != 0:
index = lsp[index - 1]
else:
lsp[i] = 0
i += 1
return lsp
# KMP algorithm of pattern matching.
def kmp(text, pattern):
lsp = compute_temporary_array(pattern)
i = 0
j = 0
while i < len(text) and j < len(pattern):
if text[i] == pattern[j]:
i += 1
j += 1
else:
if j != 0:
j = lsp[j - 1]
else:
i += 1
if j == len(pattern):
return True
else:
return False
src = 'abcxabcdabcdabcy'
sub_string = 'abcdabcy'
result = kmp(src, sub_string)
print(result)
================================================
FILE: python/string/rabinkarp.py
================================================
#Rabin Karp algorithm
# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/string/RabinKarpSearch.java
prime = 101
def pattern_matching(text, pattern):
m = len(pattern)
n = len(text)
pattern_hash = create_hash(pattern, m - 1)
text_hash = create_hash(text, m - 1)
for i in range(1, n - m + 2):
if pattern_hash == text_hash:
if check_equal(text[i-1:i+m-1], pattern[0:]) is True:
return i - 1;
if i < n - m + 1:
text_hash = recalculate_hash(text, i-1, i+m-1, text_hash, m)
return -1;
def check_equal(str1, str2):
if len(str1) != len(str2):
return False;
i = 0
j = 0
for i, j in zip(str1, str2):
if i != j:
return False;
return True
def create_hash(input, end):
hash = 0
for i in range(end + 1):
hash = hash + ord(input[i])*pow(prime, i)
return hash
def recalculate_hash(input, old_index, new_index, old_hash, pattern_len):
new_hash = old_hash - ord(input[old_index])
new_hash = new_hash/prime
new_hash += ord(input[new_index])*pow(prime, pattern_len - 1)
return new_hash;
index = pattern_matching("TusharRoy", "sharRoy")
print("Index ", index)
index = pattern_matching("TusharRoy", "Roy")
print("Index ", index)
index = pattern_matching("TusharRoy", "shar")
print("Index ", index)
index = pattern_matching("TusharRoy", "usha")
print("Index ", index)
index = pattern_matching("TusharRoy", "Tus")
print("Index ", index)
index = pattern_matching("TusharRoy", "Roa")
print("Index ", index)
================================================
FILE: python/tree/binary_tree.py
================================================
from collections import namedtuple
Color = namedtuple("Color", "RED BLACK")
class Node:
def __init__(self):
self.color = None
self.height = None
self.lis = None
self.data = None
self.size = None
self.next = None
self.right = None
self.left = None
@staticmethod
def newNode(data):
n = Node()
n.data = data
n.lis = -1
n.height = 1
n.size = 1
n.color = Color.RED
return n
class BinaryTree:
def __init__(self):
pass
@staticmethod
def add_head(data, head):
temp_head = head
n = Node.newNode(data)
if head is None:
head = n
return head
prev = None
while head is not None:
prev = head
if head.data < data:
head = head.right
else:
head = head.left
if prev.data < data:
prev.right = n
else:
prev.left = n
return temp_head
================================================
FILE: python/tree/construct_tree_from_inorder_preorder.py
================================================
from binary_tree import Node
class ConstructTreeFromInorderPreOrder:
def __init__(self):
self.index = 0
def _createTree(self, inorder, preorder, start, end):
if start > end:
return None
i = 0
for i in range(start, end + 1):
if preorder[self.index] == inorder[i]:
break
node = Node.newNode(preorder[self.index])
self.index += 1
node.left = self._createTree(inorder, preorder, start, i - 1)
node.right = self._createTree(inorder, preorder, i + 1, end)
return node
def createTree(self, inorder, preorder):
return self._createTree(inorder, preorder, 0, len(inorder) - 1)
================================================
FILE: python/tree/fenwick_tree.py
================================================
#################################################################################################################################
#Implementation of Binary Indexed Tree OR Fenwick Tree
#Time Complexities:
# Construction of Tree: O (n.log (n))
# Updating an element: O (log (n))
# Prefix Query (sum of elements 0 to i) or Range Minimum Query (sum of elements x to y): O (log (n))
#Space Complexity: O (n)
#################################################################################################################################
class FenTree (object):
def __init__ (self, array):
self.array, self.tree = [0] * len (array), [0] * (len (array) + 1);
for i in range (len (array)):
self.update (i, array [i]);
def get_parent (self, child):
return (child - (child & -child));
def get_next (self, index):
return (index + (index & -index));
def update (self, index, item):
current, self.array [index] = self.array [index], item;
item -= current;
index += 1;
while (index <= len (self.array)):
self.tree [index] += item;
index = self.get_next (index);
def prefix_sum (self, index):
index += 1;
total = 0;
while (index > 0):
total += self.tree [index];
index = self.get_parent (index);
return (total);
def range_sum (self, x, y):
return (self.prefix_sum (max (x, y)) - self.prefix_sum (min (x, y) - 1));
def describe (self):
print ('ARRAY =>\t', self.array);
print ('Binary Indexed Tree =>\t', self.tree);
if (__name__ == '__main__'):
tree = FenTree ([3,2,-1,6,5,4]);
# tree = FenTree ([int (i) for i in input ('Enter the array (space-separated integers): ').split ()]);
tree.describe ();
tree.update (4, 8); #replaces 5 with 8 in the list given to the fenwick tree
tree.describe ();
print (tree.range_sum (1, 5)); #returns 2-1+6+5+4
print (tree.prefix_sum (5)); #returns 3+2-1+6+5+4
================================================
FILE: python/tree/largest_bst_in_binary_tree.py
================================================
""" Given a binary tree, find size of largest binary search subtree in this binary tree.
Approach
--------
Traverse tree in post order fashion. Left and right nodes return 4 piece of information to root which isBST, size of max
BST, min and max in those subtree.
If both left and right subtree are BST and this node data is greater than max of left and less than min of right then it
returns to above level left size + right size + 1 and new min will be min of left side and new max will be max of right
side.
Video link
----------
* https://youtu.be/4fiDs7CCxkc
References
----------
* http://www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/
* https://leetcode.com/problems/largest-bst-subtree/
* http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
"""
from construct_tree_from_inorder_preorder import ConstructTreeFromInorderPreOrder
class MinMax:
def __init__(self):
self.min = float("inf")
self.max = float("-inf")
self.isBST = True
self.size = 0
class LargestBSTBinaryTree:
def largestBST(self, root):
m = self.largest(root)
return m.size
def largest(self, root):
if root is None:
return MinMax()
leftMinMax = self.largest(root.left)
rightMinMax = self.largest(root.right)
m = MinMax()
if ((leftMinMax.isBST == False or rightMinMax.isBST == False)
or (leftMinMax.max > root.data or rightMinMax.min <= root.data)):
m.isBST = False
m.size = max(leftMinMax.size, rightMinMax.size)
return m
m.isBST = True
m.size = leftMinMax.size + rightMinMax.size + 1
m.min = leftMinMax.min if root.left is not None else root.data
m.max = rightMinMax.max if root.right is not None else root.data
return m
if __name__ == '__main__':
lbi = LargestBSTBinaryTree()
ctf = ConstructTreeFromInorderPreOrder()
inorder = [-7, -6, -5, -4, -3, -2, 1, 2, 3, 16, 6, 10, 11, 12, 14]
preorder = [3, -2, -3, -4, -5, -6, -7, 1, 2, 16, 10, 6, 12, 11, 14]
root = ctf.createTree(inorder, preorder)
largestBSTSize = lbi.largestBST(root)
print "Size of the largest BST in the Binary Tree is ", largestBSTSize
assert 8 == lbi.largestBST(root)
================================================
FILE: python/tree/max_depth_binary_tree.py
================================================
"""
Problem Statement
=================
Given a binary tree, write a program to find the maximum depth at any given node.
For e.g, for this binary tree.
1
/ \
2 3
/ \
4 5
The height at 1 is 3, and the height at 3 is 2.
"""
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)
# construct the tree as given in the problem.
n1.left = n2
n1.right = n3
n3.left = n4
n3.right = n5
def find_max_depth(n):
if n is None:
return 0
left_height = find_max_depth(n.left)
right_height = find_max_depth(n.right)
if left_height > right_height:
result = left_height + 1
else:
result = right_height + 1
return result
if __name__ == '__main__':
assert 3 == find_max_depth(n1)
assert 2 == find_max_depth(n3)
================================================
FILE: python/tree/morris_traversal.py
================================================
"""Morris Traversal of a Binary Tree.
Video
-----
* https://youtu.be/wGXB9OWhPTg
Analysis
--------
* Time complexity O(n)
* Space complexity O(1)
"""
from binary_tree import BinaryTree
class MorrisTraversal:
def __init__(self):
pass
@staticmethod
def find_predecessor(current):
predecessor = current.left
while predecessor.right != current and predecessor.right is not None:
predecessor = predecessor.right
return predecessor
@staticmethod
def inorder(root_node):
current = root_node
while current is not None:
if current.left is None:
print "{data} ".format(data=current.data),
current = current.right
else:
predecessor = MorrisTraversal.find_predecessor(current)
if predecessor.right is None:
predecessor.right = current
current = current.left
else:
predecessor.right = None
print "{data} ".format(data=current.data),
current = current.right
@staticmethod
def preorder(root_node):
current = root_node
while current is not None:
if current.left is None:
print "{data} ".format(data=current.data),
current = current.right
else:
predecessor = MorrisTraversal.find_predecessor(current)
if predecessor.right is None:
print "{data} ".format(data=current.data),
predecessor.right = current
current = current.left
else:
predecessor.right = None
current = current.right
if __name__ == '__main__':
bt = BinaryTree()
root = None
root = bt.add_head(10, root)
root = bt.add_head(50, root)
root = bt.add_head(-10, root)
root = bt.add_head(7, root)
root = bt.add_head(9, root)
root = bt.add_head(-20, root)
root = bt.add_head(30, root)
mt = MorrisTraversal()
mt.inorder(root)
print "\n",
mt.preorder(root)
================================================
FILE: python/tree/segmenttreesum.py
================================================
def create_segment_tree(input):
size = next_power_of_2(len(input));
segment_tree = [0 for x in range(2*size - 1)]
construct_tree(segment_tree, input, 0, len(input) - 1, 0)
return segment_tree
def construct_tree(segment_tree, input, low, high, pos):
if low == high:
segment_tree[pos] = input[low]
return
mid = (low + high)/2
construct_tree(segment_tree, input, low, mid, 2*pos + 1)
construct_tree(segment_tree, input, mid + 1, high, 2*pos + 2)
segment_tree[pos] = segment_tree[2*pos+1] + segment_tree[2*pos+2]
def sum_range_query(segment_tree, q_low, q_high, len):
return sum_range_query_util(segment_tree, 0, len - 1, q_low, q_high, 0)
def sum_range_query_util(segment_tree, low, high, q_low, q_high, pos):
if q_low <= low and q_high >= high:
return segment_tree[pos]
if q_high < low or q_low > high:
return 0
mid = (low + high)/2
return sum_range_query_util(segment_tree, low, mid, q_low, q_high, 2*pos + 1)\
+ sum_range_query_util(segment_tree, mid + 1, high, q_low, q_high, 2*pos + 2)
def update_value(input, segment_tree, new_value, index):
diff = new_value - input[index]
input[index] = new_value
update_value_util(segment_tree, 0, len(input)-1, diff, index, 0)
def update_value_util(segment_tree, low, high, diff, index, pos):
if low > index or high < index:
return
segment_tree[pos] += diff
if low >= high:
return
mid = (low + high)/2
update_value_util(segment_tree, low, mid, diff, index, 2*pos + 1)
update_value_util(segment_tree, mid + 1, high, diff, index, 2*pos + 2)
def next_power_of_2(n):
if n == 0:
return 1
if n & (n - 1) == 0:
return n
while n & (n - 1) > 0:
n &= (n - 1)
return n << 1
if __name__ == '__main__':
input = [1,3,5,7,9,11]
segment_tree = create_segment_tree(input)
print(segment_tree)
print(sum_range_query(segment_tree, 2, 5, len(input)))
print(sum_range_query(segment_tree, 1, 3, len(input)))
update_value(input, segment_tree, 4, 3)
print(sum_range_query(segment_tree, 2, 5, len(input)))
print(sum_range_query(segment_tree, 1, 3, len(input)))
================================================
FILE: src/com/interview/array/AdditiveNumber.java
================================================
package com.interview.array;
import java.math.BigInteger;
/**
* Date 04/24/2016
* @author Tushar Roy
*
* Additive number is a string whose digits can form additive sequence.
* A valid additive sequence should contain at least three numbers.
* Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
*
* https://leetcode.com/problems/additive-number/
*/
public class AdditiveNumber {
public boolean isAdditiveNumber(String num) {
if (num.length() < 3) {
return false;
}
for (int i = 0; i <= num.length()/2; i++) {
if (num.charAt(0) == '0' && i > 0) {
break;
}
BigInteger x1 = new BigInteger(num.substring(0, i + 1));
//make sure remaining size is at least size of first and second integer.
for (int j = i + 1; Math.max(i, j - (i + 1)) + 1 <= num.length() - j - 1 ; j++) {
if (num.charAt(i + 1) == '0' && j > i + 1) {
break;
}
BigInteger x2 = new BigInteger(num.substring(i + 1, j + 1));
if (isValid(num, j + 1, x1, x2)) {
return true;
}
}
}
return false;
}
private boolean isValid(String num, int start, BigInteger x1, BigInteger x2) {
if (start == num.length()) {
return true;
}
BigInteger x3 = x1.add(x2);
//if num starts with x3 from offset start means x3 is found. So look for next number.
return num.startsWith(x3.toString(), start) && isValid(num, start + x3.toString().length(), x2, x3);
}
}
================================================
FILE: src/com/interview/array/ArrayAddition.java
================================================
package com.interview.array;
public class ArrayAddition {
public int[] add(int arr1[], int arr2[]){
int l = Math.max(arr1.length, arr2.length);
int[] result = new int[l];
int c=0;
int i = arr1.length-1;
int j= arr2.length-1;
int r=0;
l--;
while(i >=0 && j >=0){
r = arr1[i--] + arr2[j--] + c;
c = r/10;
result[l--] = r%10;
}
while(i>=0){
r = arr1[i--] + c;
c = r/10;
result[l--] = r%10;
}
while(j>=0){
r = arr2[j--] + c;
c = r/10;
result[l--] = r%10;
}
if(c != 0){
int[] newResult = new int[result.length+1];
for(int t= newResult.length-1; t> 0; t--){
newResult[t] = result[t-1];
}
newResult[0] = c;
return newResult;
}
return result;
}
public static void main(String args[]){
int arr1[] = {9,9,9,9,9,9,9};
int arr2[] = {1,6,8,2,6,7};
ArrayAddition aa = new ArrayAddition();
int result[] = aa.add(arr1, arr2);
for(int i=0; i < result.length; i++){
System.out.print(" " + result[i]);
}
}
}
================================================
FILE: src/com/interview/array/BestMeetingPoint.java
================================================
package com.interview.array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Date 03/24/2016
* @author Tushar Roy
*
* A group of two or more people wants to meet and minimize the total travel distance.
* You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group.
* The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
* Find the total distance that needs to be travelled to reach this meeting point.
*
* Time complexity O(m*n)
* Space complexity O(m + n)
*
* https://leetcode.com/problems/best-meeting-point/
*/
public class BestMeetingPoint {
public int minTotalDistance(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
List<Integer> vertical = new ArrayList<>();
List<Integer> horizontal = new ArrayList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
vertical.add(i);
horizontal.add(j);
}
}
}
Collections.sort(vertical);
Collections.sort(horizontal);
int size = vertical.size()/2;
int x = vertical.get(size);
int y = horizontal.get(size);
int distance = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
distance += Math.abs(x - i) + Math.abs(y - j);
}
}
}
return distance;
}
public static void main(String args[]) {
BestMeetingPoint bmp = new BestMeetingPoint();
int[][] grid = {{1, 0, 0, 0, 1}, {0, 0, 0, 0, 0},{0, 0, 1, 0, 0}};
System.out.print(bmp.minTotalDistance(grid));
}
}
================================================
FILE: src/com/interview/array/BuySellStockProfit.java
================================================
package com.interview.array;
/**
* Date 03/04/2016
* @author Tushar Roy
*
* Best time to buy and sell stocks.
* 1) Only 1 transaction is allowed
* 2) Infinite number transactions are allowed
*
* Time complexity O(n)
* Space complexity O(1)
*
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
*/
public class BuySellStockProfit {
public int oneProfit(int arr[]){
int minPrice = arr[0];
int maxProfit = 0;
for(int i=1; i < arr.length; i++){
if(arr[i] - minPrice > maxProfit){
maxProfit = arr[i] - minPrice;
}
if(arr[i] < minPrice){
minPrice = arr[i];
}
}
return maxProfit;
}
public int allTimeProfit(int arr[]){
int profit = 0;
for(int i=1; i < arr.length;i++){
if(arr[i-1] < arr[i]){
profit += arr[i] - arr[i-1];
}
}
return profit;
}
public static void main(String args[]){
int arr[] = {7,10,15,5,11,2,7,9,3};
int arr1[] = {6,4,1,3,5,7,3,1,3,4,7,9,2,5,6,0,1,2};
BuySellStockProfit bss = new BuySellStockProfit();
System.out.println(bss.oneProfit(arr));
System.out.print(bss.allTimeProfit(arr1));
}
}
================================================
FILE: src/com/interview/array/CheckIfArrayElementsAreConsecutive.java
================================================
package com.interview.array;
/**
* http://www.geeksforgeeks.org/check-if-array-elements-are-consecutive/
*/
public class CheckIfArrayElementsAreConsecutive {
public boolean areConsecutive(int input[]){
int min = Integer.MAX_VALUE;
for(int i=0; i < input.length; i++){
if(input[i] < min){
min = input[i];
}
}
for(int i=0; i < input.length; i++){
if(Math.abs(input[i]) - min >= input.length){
return false;
}
if(input[Math.abs(input[i]) - min] < 0){
return false;
}
input[Math.abs(input[i]) - min] = -input[Math.abs(input[i]) - min];
}
for(int i=0; i < input.length ; i++){
input[i] = Math.abs(input[i]);
}
return true;
}
public static void main(String args[]){
int input[] = {76,78,76,77,73,74};
CheckIfArrayElementsAreConsecutive cia = new CheckIfArrayElementsAreConsecutive();
System.out.println(cia.areConsecutive(input));
}
}
================================================
FILE: src/com/interview/array/ChunkMerge.java
================================================
package com.interview.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
/**
* Given a list of lists. Each element in the list is sorted. Sort the
* entire list.
* Test cases
* One or more lists are empty
* All elements in one list are smaller than all elements in another list
*/
public class ChunkMerge {
class Triplet implements Comparable<Triplet>{
int pos;
int val;
int index;
@Override
public int compareTo(Triplet o) {
if(val <= o.val){
return -1;
}else{
return 1;
}
}
}
public List<Integer> mergeUsingHeap(List<List<Integer>> chunks){
List<Integer> result = new ArrayList<Integer>();
PriorityQueue<Triplet> queue = new PriorityQueue<Triplet>();
//add first element of every chunk into queue
for(int i=0; i < chunks.size(); i++){
Triplet p = new Triplet();
p.pos = i;
p.val = chunks.get(i).get(0);
p.index = 1;
queue.add(p);
}
while(!queue.isEmpty()){
Triplet p = queue.poll();
result.add(p.val);
if(p.index < chunks.get(p.pos).size()){
p.val = chunks.get(p.pos).get(p.index);
p.index += 1;
queue.add(p);
}
}
return result;
}
public List<Integer> mergeChunksOfDifferentSize(List<List<Integer>> chunks){
List<Integer> result = new ArrayList<Integer>();
int sum[] = new int[chunks.size()+1];
sum[0] = 0;
for(int i =1; i < sum.length;i++){
sum[i] = sum[i-1] + chunks.get(i-1).size();
}
for(List<Integer> chunk : chunks){
for(Integer i : chunk){
result.add(i);
}
}
mergeSort(result,0,chunks.size()-1,sum);
return result;
}
private void mergeSort(List<Integer> result,int start,int end,int sum[]){
if(start >= end){
return;
}
int mid = (start + end)/2;
mergeSort(result,start,mid,sum);
mergeSort(result,mid+1,end,sum);
sortedMerge(result,start,end,sum);
}
private void sortedMerge(List<Integer> result,int start,int end,int sum[]){
/**
* If chunks are of equal size then
* i = size*start to (mid+1)*size -1
* j = (mid+1)*size to size*(end+1)
*/
int mid = (start + end)/2;
int i = sum[start];
int j = sum[mid+1];
List<Integer> temp = new ArrayList<Integer>();
while(i < sum[mid+1] && j < sum[end+1]){
if(result.get(i) < result.get(j)){
temp.add(result.get(i));
i++;
}else{
temp.add(result.get(j));
j++;
}
}
while(i < sum[mid+1]){
temp.add(result.get(i));
i++;
}
while(j < sum[end+1]){
temp.add(result.get(j));
j++;
}
int index = sum[start];
for(int k : temp){
result.set(index, k);
index++;
}
}
public static void main(String args[]){
Integer arr1[] = {1,5,6,9,21};
Integer arr2[] = {4,6,11,14};
Integer arr3[] = {-1,0,7};
Integer arr4[] = {-4,-2,11,14,18};
Integer arr5[] = {2,6};
Integer arr6[] = {-5,-2,1,5,7,11,14};
Integer arr7[] = {-6,-1,0,15,17,22,24};
List<Integer> list1 = Arrays.asList(arr1);
List<Integer> list2 = Arrays.asList(arr2);
List<Integer> list3 = Arrays.asList(arr3);
List<Integer> list4 = Arrays.asList(arr4);
List<Integer> list5 = Arrays.asList(arr5);
List<Integer> list6 = Arrays.asList(arr6);
List<Integer> list7 = Arrays.asList(arr7);
List<List<Integer>> chunks = new ArrayList<List<Integer>>();
chunks.add(list1);
chunks.add(list2);
chunks.add(list3);
chunks.add(list4);
chunks.add(list5);
chunks.add(list6);
chunks.add(list7);
ChunkMerge cm = new ChunkMerge();
List<Integer> result = cm.mergeChunksOfDifferentSize(chunks);
System.out.println(result.size());
for(Integer r : result){
System.out.print(r + " ");
}
result = cm.mergeUsingHeap(chunks);
System.out.println();
for(Integer r : result){
System.out.print(r + " ");
}
}
}
================================================
FILE: src/com/interview/array/CommonThreeSortedArray.java
================================================
package com.interview.array;
import java.util.ArrayList;
import java.util.List;
/**
* Date 01/01/2016
* @author Tushar Roy
*
* Given 3 sorted array find common elements in these 3 sorted array.
*
* Time complexity is O(m + n + k)
*
* http://www.geeksforgeeks.org/find-common-elements-three-sorted-arrays/
*/
public class CommonThreeSortedArray {
public List<Integer> commonElements(int input1[], int input2[], int input3[]) {
int i = 0;
int j = 0;
int k = 0;
List<Integer> result = new ArrayList<>();
while (i < input1.length && j < input2.length && k < input3.length) {
if (input1[i] == input2[j] && input2[j] == input3[k]) {
result.add(input1[i]);
i++;
j++;
k++;
} else if (input1[i] < input2[j]) {
i++;
} else if (input2[j] < input3[k]) {
j++;
} else {
k++;
}
}
return result;
}
public static void main(String args[]) {
int input1[] = {1, 5, 10, 20, 40, 80};
int input2[] = {6, 7, 20, 80, 100};
int input3[] = {3, 4, 15, 20, 30, 70, 80, 120};
CommonThreeSortedArray cts = new CommonThreeSortedArray();
List<Integer> result = cts.commonElements(input1, input2, input3);
result.forEach(i -> System.out.print(i + " "));
}
}
================================================
FILE: src/com/interview/array/ConvertAnArrayIntoDecreaseIncreaseFashion.java
================================================
package com.interview.array;
import java.util.Arrays;
/**
* Convert an unsorted array into an array such that
* a < b > c < d > e < f and so on
*/
public class ConvertAnArrayIntoDecreaseIncreaseFashion {
public void convert(int arr[]){
int k = 0;
if(arr.length % 2 ==0){
k = arr.length/2 ;
}else{
k = arr.length/2+1;
}
KthElementInArray kthElement = new KthElementInArray();
kthElement.kthElement(arr, k);
int high = k;
int low = 1;
while(low < high && high < arr.length){
swap(arr,low,high);
high++;
low += 2;
}
}
/**
* Sort the array first.
* Then swap every adjacent element to get final result
* @param arr
*/
public void convert1(int arr[]){
Arrays.sort(arr);
for(int i=1; i < arr.length; i+=2){
if(i+1 < arr.length){
swap(arr, i, i+1);
}
}
}
private void swap(int arr[],int low,int high){
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
}
public static void main(String args[]){
ConvertAnArrayIntoDecreaseIncreaseFashion can = new ConvertAnArrayIntoDecreaseIncreaseFashion();
int arr[] = {0,6,9,13,10,-1,8,2,4,14,-5};
can.convert(arr);
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
int arr1[] = {0,6,9,13,10,-1,8,2,4,14,-5};
can.convert1(arr1);
for(int i=0; i < arr1.length; i++){
System.out.print(arr1[i] + " ");
}
}
}
================================================
FILE: src/com/interview/array/CountInversionOfSize3.java
================================================
package com.interview.array;
/**
* Date 12/29/15
* @author Tushar Roy
*
* Given input array find number of inversions where i < j < k and input[i] > input[j] > input[k]
*
* http://www.geeksforgeeks.org/count-inversions-of-size-three-in-a-give-array/
*/
public class CountInversionOfSize3 {
/**
* Time complexity of this method is O(n^2)
* Space complexity is O(1)
*/
public int findInversions(int input[]) {
int inversion = 0;
for (int i = 1; i < input.length - 1 ; i++) {
int larger = 0;
for (int k = 0; k < i; k++) {
if (input[k] > input[i]) {
larger++;
}
}
int smaller = 0;
for (int k = i+1; k < input.length; k++) {
if (input[k] < input[i]) {
smaller++;
}
}
inversion += smaller*larger;
}
return inversion;
}
public static void main(String args[]) {
int input[] = {9, 6, 4, 5, 8};
CountInversionOfSize3 ci = new CountInversionOfSize3();
System.out.print(ci.findInversions(input));
}
}
================================================
FILE: src/com/interview/array/CountSmallerOnRight.java
================================================
package com.interview.array;
import java.util.ArrayList;
import java.util.List;
/**
* Date 03/01/2016
* @author Tushar Roy
*
* Count number of smaller elements on right side of an array for every element.
*
* Time complexity is O(nlogn)
* Space complexity is O(n)
*
* https://leetcode.com/problems/count-of-smaller-numbers-after-self/
*/
public class CountSmallerOnRight {
static class NumberIndex {
int val;
int index;
NumberIndex(int val, int index) {
this.val = val;
this.index = index;
}
}
public List<Integer> countSmaller(int[] nums) {
if (nums.length == 0) {
return new ArrayList<>();
}
NumberIndex[] input = new NumberIndex[nums.length];
for (int i = 0; i < nums.length; i++) {
input[i] = new NumberIndex(nums[i], i);
}
int result[] = new int[nums.length];
mergeUtil(input, result, 0, input.length - 1);
List<Integer> r = new ArrayList<>();
for (int s : result) {
r.add(s);
}
return r;
}
private void mergeUtil(NumberIndex[] nums, int[] result, int low, int high) {
if (low == high) {
return;
}
int mid = (low + high)/2;
mergeUtil(nums, result, low, mid);
mergeUtil(nums, result, mid + 1, high);
int i = low;
int j = mid + 1;
NumberIndex[] t = new NumberIndex[high - low + 1];
int k = 0;
int tempResult[] = new int[high - low + 1];
while (i <= mid && j <= high) {
if (nums[i].val <= nums[j].val) {
tempResult[nums[i].index - low] = j - mid - 1;
t[k++] = nums[i++];
} else {
tempResult[nums[i].index - low] = j - mid;
t[k++] = nums[j++];
}
}
int i1= i;
while (i1 <= mid) {
tempResult[nums[i1].index - low] = j - mid - 1;
t[k++] = nums[i1++];
}
while (j <= high) {
t[k++] = nums[j++];
}
k = 0;
for (i = low; i <= high; i++) {
nums[i] = t[k];
result[i] += tempResult[k++];
}
}
public static void main(String args[]) {
CountSmallerOnRight csr = new CountSmallerOnRight();
int nums[] = {5, 2, 6, 1, 0, 3};
List<Integer> result = csr.countSmaller(nums);
result.forEach(r -> System.out.print(r + " "));
}
}
================================================
FILE: src/com/interview/array/DivideNumbersInEqualGroupWithClosestSum.java
================================================
package com.interview.array;
/**
* This solution is incorrect. It is greedy approach which will not work
* e.g 1,6,6,8,9,10 - Result should be 1,9,10 and 6,6,8 but it will not give this result
* since it will greedily break 9 and 10 into different sets
*
* INCORRECT SOLUTION.(Still keeping the code in case I can improve it)
*
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DivideNumbersInEqualGroupWithClosestSum {
public void divide(int arr[],List<Integer> list1, List<Integer> list2){
Arrays.sort(arr);
int len = arr.length;
int sum1 = 0;
int sum2 = 0;
for(int i = len-1 ; i >=0; i--){
if((sum1 < sum2 && list1.size() < len/2) || (list2.size() >= len/2)){
list1.add(arr[i]);
sum1 = sum1 + arr[i];
}else{
list2.add(arr[i]);
sum2 = sum2 + arr[i];
}
}
}
public static void main(String args[]){
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
int arr[] = {15,14,13,1,3,2,};
int arr1[] = {23, 45, 34, 12,11, 98, 99, 4, 189, 1,7,19,105, 201};
DivideNumbersInEqualGroupWithClosestSum dn = new DivideNumbersInEqualGroupWithClosestSum();
dn.divide(arr, list1, list2);
System.out.println(list1);
System.out.println(list2);
list1.clear();
list2.clear();
dn.divide(arr1, list1, list2);
System.out.println(list1);
System.out.println(list2);
}
}
================================================
FILE: src/com/interview/array/DuplicateNumberDetection.java
================================================
package com.interview.array;
/**
* Date 03/04/2016
* @author Tushar Roy
*
* Given an array of size n + 1 with elements from 1 to n. One element is duplicated mulitiple times.
* Find that element in O(1) space. Array cannot be changed.
*
* Reference
* https://leetcode.com/problems/find-the-duplicate-number/
*/
public class DuplicateNumberDetection {
public int findDuplicate(int[] nums) {
if (nums.length == 0 || nums.length == 1) {
return -1;
}
int slow = nums[0];
int fast = nums[nums[0]];
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
fast = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return fast;
}
public static void main(String args[]) {
int[] input = {2,1,3,4,3};
DuplicateNumberDetection dd = new DuplicateNumberDetection();
System.out.println(dd.findDuplicate(input));
}
}
================================================
FILE: src/com/interview/array/DuplicateWithinkIndices.java
================================================
package com.interview.array;
import java.util.HashSet;
import java.util.Set;
/**
* Write a function that determines whether a array contains duplicate
* characters within k indices of each other
*/
public class DuplicateWithinkIndices {
public boolean duplicate(int arr[],int k){
Set<Integer> visited = new HashSet<Integer>();
for(int i=0; i < arr.length; i++){
if(visited.contains(arr[i])){
return true;
}
if(i >= k){
visited.remove(arr[i-k]);
}
visited.add(arr[i]);
}
return false;
}
public static void main(String args[]){
int arr[] = {1,2,3,11,2,5,6};
DuplicateWithinkIndices dk = new DuplicateWithinkIndices();
System.out.println(dk.duplicate(arr, 3));
}
}
================================================
FILE: src/com/interview/array/FindElementsOccurringNByKTimesTetris.java
================================================
package com.interview.array;
/**
* http://www.geeksforgeeks.org/given-an-array-of-of-size-n-finds-all-the-elements-that-appear-more-than-nk-times/
* The reason this algorithm works is there can never be more than k-1 elements of size
* more than n/k
*
* This question does not make much sense. Why not just use a map and keep count and
* check if occurrence is more than n/k. This is way too much effort to find elements more than
* n by k even though it saves some space.
*/
public class FindElementsOccurringNByKTimesTetris {
public static class Pair{
public int element;
public int count;
}
public void printElementsOccurringKTimes(int arr[],int k){
Pair[] p = new Pair[k];
for(int i=0; i < k; i++){
p[i] = new Pair();
}
for(int i=0; i < arr.length; i++){
int j=0;
for(j=0; j < k; j++){
if(p[j].element == arr[i]){
p[j].count++;
break;
}
}
if(j == k){
int l=0;
for(l =0; l < k ; l++){
if(p[l].count == 0){
p[l].element = arr[i];
p[l].count = 1;
break;
}
}
if(l == k){
for(int t =0; t < k ; t++){
p[t].count--;
}
}
}
}
for(int i=0; i < k ; i++){
if(p[i].count > 0){
int count =0;
for(int j=0; j < arr.length; j++){
if(arr[j] == p[i].element){
count++;
}
}
if(count >= arr.length/k){
System.out.println(p[i].element);
}
}
}
}
public static void main(String args[]){
int arr[] = {3,2,2,1,1,2,3,3,4,5,3,1};
FindElementsOccurringNByKTimesTetris fe = new FindElementsOccurringNByKTimesTetris();
fe.printElementsOccurringKTimes(arr, 3);
}
}
================================================
FILE: src/com/interview/array/FirstPositiveMissing.java
================================================
package com.interview.array;
/**
* https://leetcode.com/problems/first-missing-positive/
*/
public class FirstPositiveMissing {
public int firstMissingPositive(int[] nums) {
int startOfPositive = segregate(nums);
for (int i = startOfPositive; i < nums.length; i++) {
int index = Math.abs(nums[i]) + startOfPositive - 1;
if (index < nums.length) {
nums[index] = -Math.abs(nums[index]);
}
}
for (int i = startOfPositive; i < nums.length; i++) {
if (nums[i] > 0) {
return i - startOfPositive + 1;
}
}
return nums.length - startOfPositive + 1;
}
private int segregate(int[] nums) {
int start = 0;
int end = nums.length -1 ;
while (start <= end) {
if (nums[start] <= 0) {
start++;
} else if (nums[end] > 0) {
end--;
} else {
swap(nums, start, end);
}
}
return start;
}
private void swap(int[] nums, int start, int end) {
int t = nums[start];
nums[start] = nums[end];
nums[end] = t;
}
}
================================================
FILE: src/com/interview/array/Flip0sMaximum1s.java
================================================
package com.interview.array;
/**
* Date 12/29/2015
* @author Tushar Roy
*
* Given input array of 0s and 1s and number of flips allowed from 0 to 1, what is maximum consecutive 1s we can have
* in array
*
* Time complexity - O(n)
* Space complexity - O(1)
*
* http://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/
*/
public class Flip0sMaximum1s {
public int flip0sToMaximizeConsecutive1s(int input[], int flipsAllowed) {
int windowStart = 0;
int countZero = 0;
int result = 0;
for (int i = 0 ; i < input.length; i++) {
if (input[i] == 1) {
result = Math.max(result, i - windowStart + 1);
} else {
if (countZero < flipsAllowed) {
countZero++;
result = Math.max(result, i - windowStart + 1);
} else {
while(true) {
if (input[windowStart] == 0) {
windowStart++;
break;
}
windowStart++;
}
}
}
}
return result;
}
public static void main(String args[]) {
int input[] = {0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1};
Flip0sMaximum1s fm = new Flip0sMaximum1s();
System.out.print(fm.flip0sToMaximizeConsecutive1s(input, 1));
}
}
================================================
FILE: src/com/interview/array/FourSum.java
================================================
package com.interview.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Date 07/31/2016
* @author Tushar Roy
*
* Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
* Find all unique quadruplets in the array which gives the sum of target.
*
* Time complexity O(n^3)
* Space complexity O(1)
*
* Reference
* https://leetcode.com/problems/4sum/
*/
public class FourSum {
public List<List<Integer>> fourSum(int[] nums, int target) {
if (nums.length < 4) {
return Collections.EMPTY_LIST;
}
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 3; i++) {
if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}
if(nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) {
break;
}
if(nums[i] + nums[nums.length - 3] + nums[nums.length - 2] + nums[nums.length - 1] < target) {
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
if (j != i + 1 && nums[j] == nums[j - 1]) {
continue;
}
if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
break;
}
if (nums[i] + nums[j] + nums[nums.length - 1] + nums[nums.length - 1] < target) {
continue;
}
int low = j + 1;
int high = nums.length - 1;
while (low < high) {
if (low != j + 1 && nums[low] == nums[low - 1]) {
low++;
continue;
}
if (high != nums.length - 1 && nums[high] == nums[high + 1]) {
high--;
continue;
}
int sum = nums[i] + nums[j] + nums[low] + nums[high];
if (sum == target) {
List<Integer> r = new ArrayList<>();
r.add(nums[i]);
r.add(nums[j]);
r.add(nums[low]);
r.add(nums[high]);
result.add(r);
low++;
high--;
} else if (sum < target) {
low++;
} else {
high--;
}
gitextract_ew93x48r/
├── .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
Showing preview only (249K chars total). Download the full file or copy to clipboard to get everything.
SYMBOL INDEX (2811 symbols across 637 files)
FILE: C++/Arrays/Trapping the rain water.cpp
function trapped_water (line 4) | int trapped_water(int array[],int size){
function main (line 20) | int main(){
FILE: C++/Bit Manipulation/Checking Whether K-th Bit is Set or Not.cpp
function main (line 3) | int main(){
FILE: C++/Bit Manipulation/Clearing the K-th bit of a number.cpp
function main (line 3) | int main(){
FILE: C++/Bit Manipulation/Setting the K-th bit of a number.cpp
function main (line 3) | int main(){
FILE: C++/Bit Manipulation/Toggling Rightmost Set Bit of a number.cpp
function main (line 3) | int main(){
FILE: C++/Bit Manipulation/Toggling the K-th bit of a number.cpp
function main (line 3) | int main(){
FILE: C++/Dynamic Programming/Edit Distance.cpp
function editDistance (line 1) | int editDistance(string s1, string s2){
FILE: C++/Dynamic Programming/Longest Common Subsequence.cpp
function lcs (line 1) | int lcs(string x,string y){
FILE: C++/Dynamic Programming/Longest Common Substring.cpp
function longest_common_substring (line 4) | int longest_common_substring(string x,string y){
function main (line 26) | int main(){
FILE: C++/Dynamic Programming/Longest Increasing Subsequence.cpp
function lis (line 1) | int lis(int array[],int n){
FILE: C++/Dynamic Programming/Longest palindromic Subsequence.cpp
function longest_palindromic_subsequence (line 3) | int longest_palindromic_subsequence(string str){
function main (line 22) | int main(){
FILE: C++/Dynamic Programming/Matrix Chain Multiplication.cpp
function mcm (line 1) | int mcm(int p[], int n){
FILE: C++/Graph Algorithms/All Pair Shortest Path Problem.cpp
function floydWarshall (line 5) | void floydWarshall(vector<vector<int>> &graph){
function main (line 15) | int main(){
FILE: C++/Graph Algorithms/Breadth First Search.cpp
function breadth_first_search (line 6) | void breadth_first_search(vector<list<int>> graph,int src){
function main (line 21) | int main(){
FILE: C++/Graph Algorithms/Connected Components Algorithm DFS.cpp
function connectedComponentsDFS (line 6) | void connectedComponentsDFS(vector<list<int>> graph,int src,vector<bool>...
function connectedComponents (line 15) | int connectedComponents(vector<list<int>> graph){
function main (line 27) | int main(){
FILE: C++/Graph Algorithms/Depth First Search.cpp
function depth_first_search (line 6) | void depth_first_search(vector<list<int>> graph,int src){
function main (line 21) | int main(){
FILE: C++/Graph Algorithms/Kruskal's Minimum Spanning Tree Algorithm.cpp
type edge (line 6) | struct edge{int src,des,weight;}
class UnionFind (line 8) | class UnionFind {
method UnionFind (line 11) | UnionFind(){
method UnionFind (line 13) | UnionFind(int size){
method resize (line 20) | void resize(int size){
method find (line 27) | int find(int element){
method connected (line 35) | bool connected(int x,int y){
method merge (line 43) | void merge(int x,int y){
method clear (line 59) | void clear(){
method size (line 62) | int size(){
function comparator (line 66) | bool comparator(const edge &a,const edge &b){
function kruskalsAlgorithm (line 70) | vector<edge> kruskalsAlgorithm(vector<edge>graph,int vertices){
function main (line 84) | int main(){
FILE: C++/Graph Algorithms/Prims Minimum Spanning Tree Algorithm.cpp
class edge (line 10) | class edge{ public: int src,des,weight; edge(){}edge(int s,int d,int w):...
method edge (line 10) | edge(){}
method edge (line 10) | edge(int s,int d,int w): src(s),des(d),weight(w){}
class compare (line 11) | class compare { public: bool operator()(const edge &a,const edge &b){ re...
function primsAlgorithm (line 13) | vector<edge> primsAlgorithm(vector<list<pair<int,int>>> graph,edge minEd...
function main (line 29) | int main(){
FILE: C++/Graph Algorithms/Recursive Depth First Search.cpp
function depth_first_search (line 5) | void depth_first_search(vector<list<int>> graph,int src,vector<bool> &vi...
function main (line 14) | int main(){
FILE: C++/Graph Algorithms/Single Shortest Path Bellman Ford Algorithm.cpp
type edge (line 6) | struct edge {int src, des, weight;}
function bellmanFord (line 8) | pair<bool,vector<int>> bellmanFord(vector<edge> graph,int vertex,int sou...
function main (line 26) | int main(){
FILE: C++/Graph Algorithms/Single Source Shortest Path Dijkstra Algorithm.cpp
type compare (line 7) | struct compare{
function dijkshtra (line 12) | vector<int> dijkshtra(vector<list<pair<int,int>>> graph,int src){
function main (line 33) | int main(){
FILE: C++/Graph Algorithms/Topological Sorting.cpp
function topologicalSortDFS (line 6) | void topologicalSortDFS(vector<list<int>> graph,int src,vector<bool> &vi...
function topologicalSort (line 16) | list<int> topologicalSort(vector<list<int>> graph){
function main (line 25) | int main(){
FILE: C++/Heaps - Priority Queues/K-th Largest element of the stream.cpp
function main (line 5) | int main(){
FILE: C++/Linked List/Reverse a linked list recursively.cpp
function reverse_list (line 1) | void reverse_list(list_node *head){
FILE: C++/Number Theory Algorithms/Divisors.cpp
function generateDivisors (line 4) | set<int> generateDivisors(long long int num){
function main (line 16) | int main(){
FILE: C++/Number Theory Algorithms/Sieve of Eratosthenes.cpp
function seiveEratosthenes (line 11) | int seiveEratosthenes(){
function main (line 22) | int main(){
FILE: C++/Recursion/Partition of array on the pivot.cpp
function partition (line 3) | void partition(int array[],int low,int high){
function main (line 13) | int main(){
FILE: C++/Recursion/Permutation of a string.cpp
function permutation (line 4) | void permutation(char str[],int k,int n){
function main (line 19) | int main(){
FILE: C++/Segment Tree/Segment Tree.cpp
function buildTree (line 1) | void buildTree (int tree[],int array[], int index, int low, int high) {
function rangeQuery (line 11) | int rangeQuery (int tree[],int index, int low, int high, int l, int r) {
function updateQuery (line 20) | void updateQuery (int tree[],int index, int low, int high, int pos, int ...
FILE: C++/Stacks - Queue/CircularQueue.cpp
class circular_queue (line 3) | class circular_queue
function main (line 59) | int main(){
FILE: C++/String Algorithms/KMP.cpp
function computePrefix (line 1) | vector<int> computePrefix(string pat){
function KMP (line 17) | void KMP(string str,string pat){
FILE: C++/String Algorithms/Trie.cpp
type Trie (line 1) | struct Trie {
method Trie (line 5) | Trie() {
method pushWord (line 10) | void pushWord(char *str) {
method wordExist (line 21) | bool wordExist(char* str) {
method prefixExist (line 32) | bool prefixExist(char* str) {
FILE: C++/Union Find/Union Find.cpp
class UnionFind (line 4) | class UnionFind {
method UnionFind (line 7) | UnionFind(){
method UnionFind (line 9) | UnionFind(int size){
method resize (line 16) | void resize(int size){
method find (line 23) | int find(int element){
method connected (line 31) | bool connected(int x,int y){
method merge (line 39) | void merge(int x,int y){
method clear (line 55) | void clear(){
method size (line 58) | int size(){
function main (line 64) | int main(){
FILE: python/array/arrayaddition.py
function add (line 1) | def add(arr1, arr2):
FILE: python/array/commonthreesortedarray.py
function common_elements (line 3) | def common_elements(input1, input2, input3):
FILE: python/array/countinversionofsize3.py
function find_inversions (line 3) | def find_inversions(input):
FILE: python/array/flip0smaximum1s.py
function flip_0s_to_maximize_consecutive_1s (line 3) | def flip_0s_to_maximize_consecutive_1s(input, flips_allowed):
FILE: python/array/longestsamesumspan.py
function longest_span (line 4) | def longest_span(input1, input2):
FILE: python/array/maximumsumpathtwoarrays.py
function max_sum (line 3) | def max_sum(input1, input2):
FILE: python/array/maxproductsubarray.py
function max_product (line 3) | def max_product(input):
FILE: python/array/numberoftrianglesunsortedarray.py
function number_of_triangles (line 3) | def number_of_triangles(input):
FILE: python/array/positiveandnegativealternativelymaintainingorder.py
function rearrange (line 3) | def rearrange(input):
function find_next (line 18) | def find_next(input, start, isPositive):
function right_rotate (line 24) | def right_rotate(input, start, end):
FILE: python/array/rearrangearrayperindex.py
function rearrange (line 3) | def rearrange(input):
function rearrange_util (line 14) | def rearrange_util(input, start):
FILE: python/array/reorderarraybyindex.py
function reorder (line 3) | def reorder(input, index):
FILE: python/array/rotationwithmaxsum.py
function max_sum (line 3) | def max_sum(input):
FILE: python/array/smallestintegernotrepresentedbysubsetsum.py
function find_smallest_integer (line 3) | def find_smallest_integer(input):
FILE: python/array/tripletsumlessthantotal.py
function find_all_triplet (line 3) | def find_all_triplet(input, total):
FILE: python/array/zigzagarrangement.py
function rearrange (line 3) | def rearrange(input):
function swap (line 14) | def swap(input, i, j):
FILE: python/dynamic/bitonicsequence.py
function longest_bitonic (line 22) | def longest_bitonic(sequence):
FILE: python/dynamic/boxstacking.py
function create_rotation (line 37) | def create_rotation(given_dimensions):
function sort_by_decreasing_area (line 53) | def sort_by_decreasing_area(rotations):
function can_stack (line 57) | def can_stack(box1, box2):
function box_stack_max_height (line 61) | def box_stack_max_height(dimensions):
FILE: python/dynamic/breakword.py
function word_break_recursive (line 30) | def word_break_recursive(given_string, dictionary):
function word_break_dp (line 47) | def word_break_dp(given_string, dictionary):
function is_word_break_possible (line 86) | def is_word_break_possible(given_string, dictionary):
function is_word_break_possible_recursive_helper (line 94) | def is_word_break_possible_recursive_helper(given_string, dictionary, st...
function all_possible_word_break_helper (line 114) | def all_possible_word_break_helper(given_string, dictionary, start, max_...
function all_possible_word_breaks (line 137) | def all_possible_word_breaks(given_string, dictionary):
FILE: python/dynamic/coin_change_num_ways.py
function coin_changing_num_ways (line 22) | def coin_changing_num_ways(coins, total):
function coin_changing_num_ways2 (line 39) | def coin_changing_num_ways2(coins, total):
function print_coin_changes_recursive (line 54) | def print_coin_changes_recursive(coins, total, results_stack, pos):
function print_coin_changes (line 67) | def print_coin_changes(coins, total):
FILE: python/dynamic/coinchangingmincoins.py
function min_coins (line 22) | def min_coins(coins, total):
function print_coins (line 37) | def print_coins(R, coins):
function min_coins2 (line 51) | def min_coins2(coins, total):
function min_coins_top_down (line 68) | def min_coins_top_down(coins, total, memo):
FILE: python/dynamic/count_num_A.py
function count_a_recursive (line 30) | def count_a_recursive(n_times):
function count_a (line 42) | def count_a(n_times):
FILE: python/dynamic/count_num_binary_without_consec_1.py
function consec_one (line 28) | def consec_one(num_n):
FILE: python/dynamic/cutting_rod.py
function max_profit_dp (line 26) | def max_profit_dp(prices, rod_length):
function max_profit_recursive (line 41) | def max_profit_recursive(prices, rod_length):
FILE: python/dynamic/dice_throw_ways.py
function num_ways (line 21) | def num_ways(faces, dices, sumX):
FILE: python/dynamic/editdistance.py
function print_edits (line 23) | def print_edits(T, str1, str2):
function min_edit_distance (line 44) | def min_edit_distance(str1, str2):
function min_edit_distance_recursive (line 65) | def min_edit_distance_recursive(str1, str2):
FILE: python/dynamic/egg_drop.py
function min_attempts_egg_drop (line 27) | def min_attempts_egg_drop(eggs, floors):
function min_attempts_egg_drop_recursive (line 40) | def min_attempts_egg_drop_recursive(eggs, floors):
FILE: python/dynamic/knapsack_01.py
function knapsack_01 (line 25) | def knapsack_01(values, weights, total):
function knapsack_01_recursive_util (line 43) | def knapsack_01_recursive_util(values, weights, remaining_weight, total_...
function knapsack_01_recursive (line 62) | def knapsack_01_recursive(values, weights, total_weight):
FILE: python/dynamic/kth_ugly_number.py
function ugly_number (line 22) | def ugly_number(kth):
FILE: python/dynamic/longest_common_subsequence.py
function lcs_recursive_helper (line 27) | def lcs_recursive_helper(sequence1, sequence2, index1, index2):
function longest_common_subsequence_recursive (line 38) | def longest_common_subsequence_recursive(sequence1, sequence2):
function longest_common_subsequence (line 42) | def longest_common_subsequence(sequence1, sequence2):
FILE: python/dynamic/longest_common_substring.py
function longest_common_string_recursive_helper (line 26) | def longest_common_string_recursive_helper(str1, str2, pos1, pos2, check...
function longest_common_substring_recursive (line 45) | def longest_common_substring_recursive(str1, str2):
function longest_common_substring (line 49) | def longest_common_substring(str1, str2):
FILE: python/dynamic/longest_increasing_subsequence.py
function longest_increasing_subsequence (line 30) | def longest_increasing_subsequence(sequence):
function longest_increasing_subsequence_recursive (line 61) | def longest_increasing_subsequence_recursive(sequence):
function longest_subsequence_recursive_helper (line 73) | def longest_subsequence_recursive_helper(sequence, next_position, curren...
FILE: python/dynamic/longest_palindromic_subsequence.py
function longest_palindromic_subsequence (line 23) | def longest_palindromic_subsequence(given_string):
function palindromic_subsequence_recursive_helper (line 45) | def palindromic_subsequence_recursive_helper(given_string, start_index, ...
function longest_palindromic_subsequence_recursive (line 56) | def longest_palindromic_subsequence_recursive(given_string):
FILE: python/dynamic/matrix_chain_order.py
function matrix_chain_order (line 32) | def matrix_chain_order(matrices):
FILE: python/dynamic/maximum_increasing_subsequence.py
function maximum_sum_subsequence (line 25) | def maximum_sum_subsequence(sequence):
FILE: python/dynamic/nth_fibonacci.py
function fibonacci_recursive (line 20) | def fibonacci_recursive(n):
function fibonacci (line 27) | def fibonacci(n):
FILE: python/dynamic/num_bst.py
function num_bst (line 23) | def num_bst(num_nodes):
function num_bst_recursive (line 35) | def num_bst_recursive(num_nodes):
FILE: python/dynamic/num_paths_nm_matrix.py
function num_paths_matrix (line 21) | def num_paths_matrix(rows, cols):
function num_paths_matrix_recursive (line 29) | def num_paths_matrix_recursive(rows, cols):
FILE: python/dynamic/num_trees_preorder.py
function num_trees (line 19) | def num_trees(num_nodes):
function num_trees_recursive (line 29) | def num_trees_recursive(num_nodes):
FILE: python/dynamic/optimal_bst.py
function min_cost_bst (line 24) | def min_cost_bst(input_array, freq):
function min_cost_bst_recursive_helper (line 43) | def min_cost_bst_recursive_helper(input_array, freq, low_index, high_ind...
function min_cost_bst_recursive (line 57) | def min_cost_bst_recursive(input_array, freq):
FILE: python/dynamic/stockbuysellktransactions.py
function max_profit (line 20) | def max_profit(prices, K):
function max_profit_slow_solution (line 42) | def max_profit_slow_solution(prices, K):
function print_actual_solution (line 63) | def print_actual_solution(T, prices):
FILE: python/dynamic/string_interleaving.py
function is_interleaved_recursive (line 14) | def is_interleaved_recursive(str1, str2, str3, pos1, pos2, pos3):
function is_interleaved (line 25) | def is_interleaved(str1, str2, str3):
FILE: python/dynamic/sub_rectangular_maximum_sum.py
function kadanes (line 37) | def kadanes(temp):
function max_sub_sub_rectangle (line 59) | def max_sub_sub_rectangle(rectangle):
FILE: python/dynamic/subset_sum.py
function subset_sum (line 27) | def subset_sum(sequence, sum_value):
function partition (line 45) | def partition(sequence):
FILE: python/dynamic/symbolexpressionevaluation.py
function evaluate_expression (line 19) | def evaluate_expression(expression_map, expression, result):
FILE: python/dynamic/weighted_job_scheduling_max_profit.py
function can_sequence (line 24) | def can_sequence(job1, job2):
function find_max_profit (line 30) | def find_max_profit(jobs):
FILE: python/geometry/skylinedrawing.py
class BuildingPoint (line 3) | class BuildingPoint(object):
method __init__ (line 5) | def __init__(self, point, is_start, height):
method __lt__ (line 10) | def __lt__(self, other):
function get_skyline (line 26) | def get_skyline(buildings):
FILE: python/graph/cycledirectedgraph.py
function has_cycle (line 6) | def has_cycle(graph):
function dfs (line 21) | def dfs(current, white, gray, black):
function move_vertex (line 34) | def move_vertex(vertex, source_set, destination_set):
FILE: python/graph/cycleundirectedgraph.py
function has_cycle_dfs (line 7) | def has_cycle_dfs(graph):
function has_cycle_dfs_util (line 17) | def has_cycle_dfs_util(vertex, visited, parent):
function has_cycle_using_disjoint_set (line 29) | def has_cycle_using_disjoint_set(graph):
FILE: python/graph/dijkstrashortestpath.py
function shortest_path (line 10) | def shortest_path(graph, sourceVertex):
function get_other_vertex_for_edge (line 43) | def get_other_vertex_for_edge(vertex, edge):
FILE: python/graph/disjointset.py
class Node (line 4) | class Node(object):
method __init__ (line 6) | def __init__(self, data, parent = None, rank = 0):
method __str__ (line 11) | def __str__(self):
method __repr__ (line 14) | def __repr__(self):
class DisjointSet (line 18) | class DisjointSet(object):
method __init__ (line 20) | def __init__(self):
method make_set (line 23) | def make_set(self, data):
method union (line 28) | def union(self, data1, data2):
method find_set (line 45) | def find_set(self, data):
method find_set_util (line 48) | def find_set_util(self, node):
FILE: python/graph/floydwarshall.py
class NegativeWeightCycleException (line 7) | class NegativeWeightCycleException(Exception):
method __init__ (line 8) | def __init__(self):
function all_pair_shortest_path (line 11) | def all_pair_shortest_path(distance_matrix):
function print_path (line 45) | def print_path(path, start, end):
FILE: python/graph/fordfulkerson.py
function max_flow (line 6) | def max_flow(capacity, source, sink):
function bfs (line 38) | def bfs(residual_capacity, source, sink):
FILE: python/graph/graph.py
class Graph (line 4) | class Graph(object):
method __init__ (line 6) | def __init__(self, is_directed):
method add_edge (line 11) | def add_edge(self, id1, id2, weight=0):
class Edge (line 31) | class Edge(object):
method __init__ (line 33) | def __init__(self, vertex1, vertex2, is_directed, weight):
method __eq__ (line 39) | def __eq__(self, other):
method __hash (line 42) | def __hash(self):
method __str__ (line 45) | def __str__(self):
method __repr__ (line 48) | def __repr__(self):
class Vertex (line 51) | class Vertex(object):
method __init__ (line 53) | def __init__(self, id):
method add_adjacent_vertex (line 58) | def add_adjacent_vertex(self, edge, vertex):
method get_degree (line 62) | def get_degree(self):
method __eq__ (line 65) | def __eq__(self, other):
method __hash__ (line 68) | def __hash__(self):
method __str__ (line 71) | def __str__(self):
method __repr__ (line 74) | def __repr__(self):
method __lt__ (line 77) | def __lt__(self, other):
method __gt__ (line 80) | def __gt__(self, other):
FILE: python/graph/graphtraversal.py
function dfs_util (line 7) | def dfs_util(v, visited):
function dfs (line 15) | def dfs(graph):
function bfs (line 20) | def bfs(graph):
FILE: python/graph/kruskalmst.py
function get_key (line 7) | def get_key(edge):
function minimum_spanning_tree (line 10) | def minimum_spanning_tree(graph):
FILE: python/graph/primmst.py
function minimum_spanning_tree (line 8) | def minimum_spanning_tree(graph):
function get_other_vertex_for_edge (line 35) | def get_other_vertex_for_edge(vertex, edge):
FILE: python/graph/priorityqueue.py
class PriorityQueue (line 7) | class PriorityQueue(object):
method __init__ (line 9) | def __init__(self, is_min_heap):
method contains_task (line 17) | def contains_task(self, task):
method get_task_priority (line 23) | def get_task_priority(self, task):
method add_task (line 28) | def add_task(self, priority, task):
method change_task_priority (line 35) | def change_task_priority(self, priority, task):
method remove_task (line 43) | def remove_task(self, task):
method pop_task (line 47) | def pop_task(self):
method peek_task (line 55) | def peek_task(self):
method is_empty (line 63) | def is_empty(self):
method __str__ (line 70) | def __str__(self):
FILE: python/graph/topologicalsort.py
function top_sort (line 6) | def top_sort(graph):
function top_sort_util (line 15) | def top_sort_util(vertex, stack, visited):
FILE: python/recursion/setpairtogether.py
function find_minimum_swaps (line 3) | def find_minimum_swaps(input, pair):
function find_minimum_swaps_util (line 9) | def find_minimum_swaps_util(input, pair, index, current):
function swap (line 36) | def swap(index, input, i, j):
FILE: python/recursion/stringpermutation.py
function permute (line 3) | def permute(input):
function permute_util (line 20) | def permute_util(str, count, result, level):
FILE: python/string/Z_Algorithm.py
function z_algo (line 9) | def z_algo(arr):
function makepattern (line 33) | def makepattern(string , pattern):
FILE: python/string/knuthmorrispratt.py
function compute_temporary_array (line 6) | def compute_temporary_array(pattern):
function kmp (line 26) | def kmp(text, pattern):
FILE: python/string/rabinkarp.py
function pattern_matching (line 5) | def pattern_matching(text, pattern):
function check_equal (line 19) | def check_equal(str1, str2):
function create_hash (line 29) | def create_hash(input, end):
function recalculate_hash (line 35) | def recalculate_hash(input, old_index, new_index, old_hash, pattern_len):
FILE: python/tree/binary_tree.py
class Node (line 6) | class Node:
method __init__ (line 7) | def __init__(self):
method newNode (line 18) | def newNode(data):
class BinaryTree (line 28) | class BinaryTree:
method __init__ (line 30) | def __init__(self):
method add_head (line 34) | def add_head(data, head):
FILE: python/tree/construct_tree_from_inorder_preorder.py
class ConstructTreeFromInorderPreOrder (line 4) | class ConstructTreeFromInorderPreOrder:
method __init__ (line 5) | def __init__(self):
method _createTree (line 8) | def _createTree(self, inorder, preorder, start, end):
method createTree (line 22) | def createTree(self, inorder, preorder):
FILE: python/tree/fenwick_tree.py
class FenTree (line 10) | class FenTree (object):
method __init__ (line 11) | def __init__ (self, array):
method get_parent (line 16) | def get_parent (self, child):
method get_next (line 19) | def get_next (self, index):
method update (line 22) | def update (self, index, item):
method prefix_sum (line 30) | def prefix_sum (self, index):
method range_sum (line 38) | def range_sum (self, x, y):
method describe (line 41) | def describe (self):
FILE: python/tree/largest_bst_in_binary_tree.py
class MinMax (line 26) | class MinMax:
method __init__ (line 28) | def __init__(self):
class LargestBSTBinaryTree (line 35) | class LargestBSTBinaryTree:
method largestBST (line 37) | def largestBST(self, root):
method largest (line 41) | def largest(self, root):
FILE: python/tree/max_depth_binary_tree.py
class Node (line 19) | class Node:
method __init__ (line 20) | def __init__(self, value):
function find_max_depth (line 40) | def find_max_depth(n):
FILE: python/tree/morris_traversal.py
class MorrisTraversal (line 19) | class MorrisTraversal:
method __init__ (line 21) | def __init__(self):
method find_predecessor (line 25) | def find_predecessor(current):
method inorder (line 32) | def inorder(root_node):
method preorder (line 50) | def preorder(root_node):
FILE: python/tree/segmenttreesum.py
function create_segment_tree (line 1) | def create_segment_tree(input):
function construct_tree (line 7) | def construct_tree(segment_tree, input, low, high, pos):
function sum_range_query (line 17) | def sum_range_query(segment_tree, q_low, q_high, len):
function sum_range_query_util (line 20) | def sum_range_query_util(segment_tree, low, high, q_low, q_high, pos):
function update_value (line 31) | def update_value(input, segment_tree, new_value, index):
function update_value_util (line 36) | def update_value_util(segment_tree, low, high, diff, index, pos):
function next_power_of_2 (line 48) | def next_power_of_2(n):
FILE: src/com/interview/array/AdditiveNumber.java
class AdditiveNumber (line 15) | public class AdditiveNumber {
method isAdditiveNumber (line 17) | public boolean isAdditiveNumber(String num) {
method isValid (line 40) | private boolean isValid(String num, int start, BigInteger x1, BigInteg...
FILE: src/com/interview/array/ArrayAddition.java
class ArrayAddition (line 3) | public class ArrayAddition {
method add (line 5) | public int[] add(int arr1[], int arr2[]){
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/array/BestMeetingPoint.java
class BestMeetingPoint (line 21) | public class BestMeetingPoint {
method minTotalDistance (line 22) | public int minTotalDistance(int[][] grid) {
method main (line 56) | public static void main(String args[]) {
FILE: src/com/interview/array/BuySellStockProfit.java
class BuySellStockProfit (line 17) | public class BuySellStockProfit {
method oneProfit (line 19) | public int oneProfit(int arr[]){
method allTimeProfit (line 33) | public int allTimeProfit(int arr[]){
method main (line 43) | public static void main(String args[]){
FILE: src/com/interview/array/CheckIfArrayElementsAreConsecutive.java
class CheckIfArrayElementsAreConsecutive (line 6) | public class CheckIfArrayElementsAreConsecutive {
method areConsecutive (line 8) | public boolean areConsecutive(int input[]){
method main (line 30) | public static void main(String args[]){
FILE: src/com/interview/array/ChunkMerge.java
class ChunkMerge (line 15) | public class ChunkMerge {
class Triplet (line 17) | class Triplet implements Comparable<Triplet>{
method compareTo (line 21) | @Override
method mergeUsingHeap (line 31) | public List<Integer> mergeUsingHeap(List<List<Integer>> chunks){
method mergeChunksOfDifferentSize (line 55) | public List<Integer> mergeChunksOfDifferentSize(List<List<Integer>> ch...
method mergeSort (line 73) | private void mergeSort(List<Integer> result,int start,int end,int sum[]){
method sortedMerge (line 83) | private void sortedMerge(List<Integer> result,int start,int end,int su...
method main (line 118) | public static void main(String args[]){
FILE: src/com/interview/array/CommonThreeSortedArray.java
class CommonThreeSortedArray (line 16) | public class CommonThreeSortedArray {
method commonElements (line 18) | public List<Integer> commonElements(int input1[], int input2[], int in...
method main (line 40) | public static void main(String args[]) {
FILE: src/com/interview/array/ConvertAnArrayIntoDecreaseIncreaseFashion.java
class ConvertAnArrayIntoDecreaseIncreaseFashion (line 10) | public class ConvertAnArrayIntoDecreaseIncreaseFashion {
method convert (line 12) | public void convert(int arr[]){
method convert1 (line 37) | public void convert1(int arr[]){
method swap (line 46) | private void swap(int arr[],int low,int high){
method main (line 52) | public static void main(String args[]){
FILE: src/com/interview/array/CountInversionOfSize3.java
class CountInversionOfSize3 (line 11) | public class CountInversionOfSize3 {
method findInversions (line 17) | public int findInversions(int input[]) {
method main (line 37) | public static void main(String args[]) {
FILE: src/com/interview/array/CountSmallerOnRight.java
class CountSmallerOnRight (line 17) | public class CountSmallerOnRight {
class NumberIndex (line 18) | static class NumberIndex {
method NumberIndex (line 21) | NumberIndex(int val, int index) {
method countSmaller (line 27) | public List<Integer> countSmaller(int[] nums) {
method mergeUtil (line 47) | private void mergeUtil(NumberIndex[] nums, int[] result, int low, int ...
method main (line 86) | public static void main(String args[]) {
FILE: src/com/interview/array/DivideNumbersInEqualGroupWithClosestSum.java
class DivideNumbersInEqualGroupWithClosestSum (line 15) | public class DivideNumbersInEqualGroupWithClosestSum {
method divide (line 17) | public void divide(int arr[],List<Integer> list1, List<Integer> list2){
method main (line 33) | public static void main(String args[]){
FILE: src/com/interview/array/DuplicateNumberDetection.java
class DuplicateNumberDetection (line 13) | public class DuplicateNumberDetection {
method findDuplicate (line 14) | public int findDuplicate(int[] nums) {
method main (line 34) | public static void main(String args[]) {
FILE: src/com/interview/array/DuplicateWithinkIndices.java
class DuplicateWithinkIndices (line 10) | public class DuplicateWithinkIndices {
method duplicate (line 12) | public boolean duplicate(int arr[],int k){
method main (line 26) | public static void main(String args[]){
FILE: src/com/interview/array/FindElementsOccurringNByKTimesTetris.java
class FindElementsOccurringNByKTimesTetris (line 12) | public class FindElementsOccurringNByKTimesTetris {
class Pair (line 14) | public static class Pair{
method printElementsOccurringKTimes (line 19) | public void printElementsOccurringKTimes(int arr[],int k){
method main (line 66) | public static void main(String args[]){
FILE: src/com/interview/array/FirstPositiveMissing.java
class FirstPositiveMissing (line 6) | public class FirstPositiveMissing {
method firstMissingPositive (line 7) | public int firstMissingPositive(int[] nums) {
method segregate (line 23) | private int segregate(int[] nums) {
method swap (line 38) | private void swap(int[] nums, int start, int end) {
FILE: src/com/interview/array/Flip0sMaximum1s.java
class Flip0sMaximum1s (line 15) | public class Flip0sMaximum1s {
method flip0sToMaximizeConsecutive1s (line 17) | public int flip0sToMaximizeConsecutive1s(int input[], int flipsAllowed) {
method main (line 43) | public static void main(String args[]) {
FILE: src/com/interview/array/FourSum.java
class FourSum (line 21) | public class FourSum {
method fourSum (line 23) | public List<List<Integer>> fourSum(int[] nums, int target) {
method main (line 82) | public static void main(String args[]) {
FILE: src/com/interview/array/GasStationCircle.java
class GasStationCircle (line 12) | public class GasStationCircle {
method startTour (line 14) | public int startTour(int gasAvailable[],int gasRequired[]){
method startTour1 (line 44) | public int startTour1(int gasAvailable[], int gasRequired[]){
method main (line 78) | public static void main(String args[]){
FILE: src/com/interview/array/GreedyTextJustification.java
class GreedyTextJustification (line 19) | public class GreedyTextJustification {
method fullJustify (line 20) | public List<String> fullJustify(String[] words, int maxWidth) {
method padSpace (line 61) | private void padSpace(StringBuffer buff, int count) {
method fullJustify1 (line 67) | public List<String> fullJustify1(String[] words, int maxWidth) {
method main (line 131) | public static void main(String args[]) {
FILE: src/com/interview/array/GroupElementsInSizeM.java
class Pair (line 15) | class Pair{
method Pair (line 18) | Pair(int num,int count){
class Comparators (line 24) | class Comparators implements Comparator<Pair>{
method compare (line 26) | @Override
class GroupElementsInSizeM (line 37) | public class GroupElementsInSizeM {
method group (line 39) | public boolean group(int input[],int m){
method main (line 77) | public static void main(String args[]){
FILE: src/com/interview/array/HIndex.java
class HIndex (line 8) | public class HIndex {
method hIndex (line 9) | public int hIndex(int[] citations) {
method main (line 35) | public static void main(String args[]) {
FILE: src/com/interview/array/IncreasingSubsequnceOfLength3WithMaxProduct.java
class IncreasingSubsequnceOfLength3WithMaxProduct (line 13) | public class IncreasingSubsequnceOfLength3WithMaxProduct {
method maxProduct (line 15) | public int maxProduct(int arr[]){
method getLGN (line 47) | private void getLGN(int arr[],int pos,int LGN[]){
method main (line 61) | public static void main(String args[]){
FILE: src/com/interview/array/IncreasingTripletSubsequence.java
class IncreasingTripletSubsequence (line 15) | public class IncreasingTripletSubsequence {
method increasingTriplet (line 16) | public boolean increasingTriplet(int[] nums) {
method main (line 38) | public static void main(String args[]) {
FILE: src/com/interview/array/JumpGame.java
class JumpGame (line 25) | public class JumpGame {
method canJump (line 27) | public boolean canJump(int[] nums) {
method jump (line 36) | public int jump(int[] nums) {
method main (line 50) | public static void main(String args[]) {
FILE: src/com/interview/array/KadaneWrapArray.java
class Triplet (line 11) | class Triplet{
method toString (line 15) | @Override
class KadaneWrapArray (line 22) | public class KadaneWrapArray {
method kadaneWrap (line 24) | public Triplet kadaneWrap(int arr[]){
method kadane (line 49) | public Triplet kadane(int arr[]){
method main (line 75) | public static void main(String args[]){
FILE: src/com/interview/array/KthElementInArray.java
class KthElementInArray (line 12) | public class KthElementInArray {
method kthElement (line 14) | public int kthElement(int arr[],int k){
method quickSelect (line 32) | private int quickSelect(int arr[],int low,int high){
method swap (line 52) | private void swap(int arr[],int low,int high){
method main (line 58) | public static void main(String args[]){
FILE: src/com/interview/array/KthLargestInTwoSortedArray.java
class KthLargestInTwoSortedArray (line 7) | public class KthLargestInTwoSortedArray {
method kthLargest1 (line 10) | public int kthLargest1(int arr1[],int arr2[],int low1,int high1,int lo...
method kthLargest (line 45) | public int kthLargest(int input1[],int input2[],int k){
method kthLargest (line 49) | private int kthLargest(int input1[],int input2[],int l1, int h1, int l...
method main (line 113) | public static void main(String args[]){
FILE: src/com/interview/array/LargerElementOnRight.java
class LargerElementOnRight (line 15) | public class LargerElementOnRight {
method larger (line 17) | public int[] larger(int input[]){
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/array/LargestMountain.java
class LargestMountain (line 6) | public class LargestMountain {
method longestMountain (line 8) | public int longestMountain(int[] nums) {
type State (line 34) | enum State {
method main (line 40) | public static void main(String[] args) {
FILE: src/com/interview/array/LargestSubArrayWithEqual0sAnd1s.java
class LargestSubArrayWithEqual0sAnd1s (line 13) | public class LargestSubArrayWithEqual0sAnd1s {
method equalNumber (line 15) | public int equalNumber(int arr[]){
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/array/LeetCodeCandy.java
class LeetCodeCandy (line 7) | public class LeetCodeCandy {
method candy (line 8) | public int candy(int[] ratings) {
FILE: src/com/interview/array/LongestConsecutiveSubsequence.java
class LongestConsecutiveSubsequence (line 18) | public class LongestConsecutiveSubsequence {
method longestConsecutive (line 19) | public int longestConsecutive(int[] nums) {
method main (line 38) | public static void main(String args[]) {
FILE: src/com/interview/array/LongestIncreasingSubSequenceOlogNMethod.java
class LongestIncreasingSubSequenceOlogNMethod (line 15) | public class LongestIncreasingSubSequenceOlogNMethod {
method ceilIndex (line 20) | private int ceilIndex(int input[], int T[], int end, int s){
method longestIncreasingSubSequence (line 37) | public int longestIncreasingSubSequence(int input[]){
method main (line 71) | public static void main(String args[]){
FILE: src/com/interview/array/LongestSameSumSpan.java
class LongestSameSumSpan (line 18) | public class LongestSameSumSpan {
method longestSpan (line 20) | public int longestSpan(int input1[], int input2[]) {
method main (line 41) | public static void main(String args[]) {
FILE: src/com/interview/array/LongestSubstringWithAtMost2Char.java
class LongestSubstringWithAtMost2Char (line 7) | public class LongestSubstringWithAtMost2Char {
method lengthOfLongestSubstringTwoDistinct (line 8) | public int lengthOfLongestSubstringTwoDistinct(String s) {
method main (line 51) | public static void main(String args[]) {
FILE: src/com/interview/array/MaxNumberFromTwoArray.java
class MaxNumberFromTwoArray (line 22) | public class MaxNumberFromTwoArray {
method maxNumber (line 23) | public int[] maxNumber(int[] nums1, int[] nums2, int k) {
method merge (line 37) | private int[] merge(int[] a1, int[] a2) {
method isGreater (line 62) | private boolean isGreater(int[] a, int[] b, int i, int j) {
method findLargest1 (line 75) | private int[] findLargest1(int[] nums, int k) {
method main (line 92) | public static void main(String args[]) {
FILE: src/com/interview/array/MaxProductSubarray.java
class MaxProductSubarray (line 15) | public class MaxProductSubarray {
method maxProduct (line 17) | public int maxProduct(int[] nums) {
method main (line 48) | public static void main(String args[]){
FILE: src/com/interview/array/MaxRepeatingNumber.java
class MaxRepeatingNumber (line 9) | public class MaxRepeatingNumber {
method maxRepeatingNumber (line 11) | public int maxRepeatingNumber(int arr[], int k){
method main (line 30) | public static void main(String args[]){
FILE: src/com/interview/array/MaximumGap.java
class MaximumGap (line 15) | public class MaximumGap {
class Bucket (line 17) | class Bucket {
method update (line 21) | void update(int val) {
method maximumGap (line 33) | public int maximumGap(int[] input) {
method main (line 73) | public static void main(String args[]) {
FILE: src/com/interview/array/MaximumIminusJSuchThatAiGTAj.java
class MaximumIminusJSuchThatAiGTAj (line 9) | public class MaximumIminusJSuchThatAiGTAj {
class Node (line 11) | class Node{
method maximumGeeks (line 16) | public int maximumGeeks(int input[]){
method main (line 50) | public static void main(String args[]){
FILE: src/com/interview/array/MaximumMinimumArrangement.java
class MaximumMinimumArrangement (line 15) | public class MaximumMinimumArrangement {
method rearrange (line 17) | public void rearrange(int[] input) {
FILE: src/com/interview/array/MaximumOfSubarrayOfSizeK.java
class MaximumOfSubarrayOfSizeK (line 14) | public class MaximumOfSubarrayOfSizeK {
method maxSubArray (line 16) | public int[] maxSubArray(int input[], int k) {
method main (line 56) | public static void main(String args[]){
FILE: src/com/interview/array/MaximumSumPathTwoArrays.java
class MaximumSumPathTwoArrays (line 16) | public class MaximumSumPathTwoArrays {
method maxSum (line 18) | public int maxSum(int input1[], int input2[]) {
method main (line 55) | public static void main(String args[]) {
FILE: src/com/interview/array/MaximumSumThreeNonOverlappingSubarray.java
class MaximumSumThreeNonOverlappingSubarray (line 11) | public class MaximumSumThreeNonOverlappingSubarray {
method maxSumOfThreeSubarrays (line 13) | public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
method main (line 60) | public static void main(String[] args) {
FILE: src/com/interview/array/MeetingRooms.java
class MeetingRooms (line 18) | public class MeetingRooms {
class Interval (line 20) | public static class Interval {
method Interval (line 23) | Interval() { start = 0; end = 0; }
method Interval (line 24) | Interval(int s, int e) { start = s; end = e; }
method minMeetingRooms1 (line 27) | public int minMeetingRooms1(Interval[] intervals) {
method minMeetingRooms (line 51) | public int minMeetingRooms(Interval[] intervals) {
FILE: src/com/interview/array/MinimumDistanceBetweenTwoNumbers.java
class MinimumDistanceBetweenTwoNumbers (line 6) | public class MinimumDistanceBetweenTwoNumbers {
method minDistance (line 8) | public int minDistance(int input[],int x, int y){
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/array/MinimumNumberFromSequence.java
class MinimumNumberFromSequence (line 15) | public class MinimumNumberFromSequence {
method find (line 17) | public int[] find(char[] input) {
method main (line 39) | public static void main(String args[]) {
FILE: src/com/interview/array/MinimumSortedWhichSortsEntireArray.java
class MinimumSortedWhichSortsEntireArray (line 6) | public class MinimumSortedWhichSortsEntireArray {
method minLength (line 8) | public int minLength(int arr[]){
method main (line 49) | public static void main(String args[]){
FILE: src/com/interview/array/MissingRanges.java
class MissingRanges (line 15) | public class MissingRanges {
method findMissingRanges (line 16) | public List<String> findMissingRanges(int[] nums, int lower, int upper) {
method makeRange (line 38) | private String makeRange(int a, int b) {
FILE: src/com/interview/array/MoveAllZerosToEnd.java
class MoveAllZerosToEnd (line 3) | public class MoveAllZerosToEnd {
method moveZeros (line 5) | public void moveZeros(int arr[]){
method main (line 22) | public static void main(String args[]){
FILE: src/com/interview/array/MultiplyAllFieldsExceptOwnPosition.java
class MultiplyAllFieldsExceptOwnPosition (line 6) | public class MultiplyAllFieldsExceptOwnPosition {
method multiply (line 8) | public int[] multiply(int nums[]) {
FILE: src/com/interview/array/NthElementOfCountNumberSequence.java
class NthElementOfCountNumberSequence (line 14) | public class NthElementOfCountNumberSequence {
method nthElement (line 16) | public List<Integer> nthElement(int n) {
method main (line 43) | public static void main(String args[]) {
FILE: src/com/interview/array/NumberOfTrianglesInUnsortedArray.java
class NumberOfTrianglesInUnsortedArray (line 8) | public class NumberOfTrianglesInUnsortedArray {
method numberOfTriangles (line 10) | public int numberOfTriangles(int input[]){
method main (line 27) | public static void main(String args[]){
FILE: src/com/interview/array/PositiveAndNegativeNumberAlternatively.java
class PositiveAndNegativeNumberAlternatively (line 6) | public class PositiveAndNegativeNumberAlternatively {
method arrange (line 8) | public void arrange(int arr[]){
method segregate (line 19) | private int segregate(int arr[]){
method swap (line 34) | private void swap(int arr[],int i,int j){
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/array/PositiveAndNegativeNumberAlternativelyMaintainingOrder.java
class PositiveAndNegativeNumberAlternativelyMaintainingOrder (line 17) | public class PositiveAndNegativeNumberAlternativelyMaintainingOrder {
method rearrange (line 19) | public void rearrange(int input[]) {
method findNext (line 40) | private int findNext(int input[], int start, boolean isPositive) {
method rightRotate (line 49) | private void rightRotate(int input[], int start, int end) {
method main (line 57) | public static void main(String args[]) {
FILE: src/com/interview/array/RearrangeArrayPerIndex.java
class RearrangeArrayPerIndex (line 16) | public class RearrangeArrayPerIndex {
method rearrange (line 18) | public void rearrange(int input[]) {
method rearrangeUtil (line 35) | private void rearrangeUtil(int input[], int start) {
method main (line 46) | public static void main(String args[]) {
FILE: src/com/interview/array/RearrangeSuchThatArriBecomesArrArri.java
class RearrangeSuchThatArriBecomesArrArri (line 6) | public class RearrangeSuchThatArriBecomesArrArri {
method rearrange (line 8) | public void rearrange(int arr[]){
method main (line 24) | public static void main(String args[]){
FILE: src/com/interview/array/ReorderArrayByIndex.java
class ReorderArrayByIndex (line 17) | public class ReorderArrayByIndex {
method reorder (line 18) | public void reorder(int input[], int index[]) {
method main (line 36) | public static void main(String args[]) {
FILE: src/com/interview/array/RepeatingAndMissingNumber.java
class RepeatingAndMissingNumber (line 6) | public class RepeatingAndMissingNumber {
class Pair (line 8) | class Pair{
method toString (line 11) | public String toString(){
method findNumbers (line 16) | public Pair findNumbers(int input[]){
method main (line 36) | public static void main(String args[]){
FILE: src/com/interview/array/RotationWithMaxSum.java
class RotationWithMaxSum (line 14) | public class RotationWithMaxSum {
method maxSum (line 15) | int maxSum(int input[]) {
method main (line 32) | public static void main(String args[]) {
FILE: src/com/interview/array/SelfCrossing.java
class SelfCrossing (line 6) | public class SelfCrossing {
method isSelfCrossing (line 8) | public boolean isSelfCrossing(int[] x) {
method main (line 40) | public static void main(String args[]) {
FILE: src/com/interview/array/ShortestPalindrome.java
class ShortestPalindrome (line 18) | public class ShortestPalindrome {
method shortestPalindrome (line 19) | public String shortestPalindrome(String s) {
method kmp (line 36) | private int kmp(char[] input) {
method createInput (line 63) | private char[] createInput(String s) {
method main (line 77) | public static void main(String args[]) {
FILE: src/com/interview/array/SmallestIntegerNotRepresentedBySubsetSum.java
class SmallestIntegerNotRepresentedBySubsetSum (line 14) | public class SmallestIntegerNotRepresentedBySubsetSum {
method findSmallestInteger (line 16) | public int findSmallestInteger(int input[]) {
method minPatches (line 31) | public int minPatches(int[] nums, int n) {
method main (line 48) | public static void main(String args[]) {
FILE: src/com/interview/array/SmallestSubarrayWithAtleastKSum.java
class SmallestSubarrayWithAtleastKSum (line 6) | public class SmallestSubarrayWithAtleastKSum {
method shortestSubarray (line 8) | public int shortestSubarray(int[] A, int K) {
method main (line 47) | public static void main(String[] args) {
FILE: src/com/interview/array/SortedArrayTransformation.java
class SortedArrayTransformation (line 14) | public class SortedArrayTransformation {
method sortTransformedArray (line 15) | public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
method apply (line 36) | private int apply(int x, int a, int b, int c) {
FILE: src/com/interview/array/StableMarriageProblem.java
class StableMarriageProblem (line 3) | public class StableMarriageProblem {
method checkIfNewIsBetter (line 5) | private boolean checkIfNewIsBetter(int priority[][], int bride,
method findPair (line 18) | public int[] findPair(int[][] priority) {
method main (line 59) | public static void main(String args[]){
FILE: src/com/interview/array/SubarrayWithGivenSum.java
class SubarrayWithGivenSum (line 6) | public class SubarrayWithGivenSum {
class Pair (line 8) | class Pair{
method toString (line 12) | public String toString(){
method findSubArray (line 16) | public Pair findSubArray(int input[],int sum){
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/array/SummaryRanges.java
class SummaryRanges (line 22) | public class SummaryRanges {
method summaryRanges (line 23) | public List<String> summaryRanges(int[] nums) {
method makeRange (line 45) | private String makeRange(int a, int b) {
FILE: src/com/interview/array/ThreeSumSmallerThanTarget.java
class ThreeSumSmallerThanTarget (line 11) | public class ThreeSumSmallerThanTarget {
method threeSumSmaller (line 12) | public int threeSumSmaller(int[] nums, int target) {
FILE: src/com/interview/array/TrappingWater.java
class TrappingWater (line 7) | public class TrappingWater {
method trap (line 9) | public int trap(int[] height) {
method main (line 33) | public static void main(String args[]){
FILE: src/com/interview/array/TripletInArray.java
class TripletInArray (line 10) | public class TripletInArray {
class Triplet (line 12) | class Triplet {
method toString (line 17) | public String toString() {
method findTriplet (line 22) | public Triplet findTriplet(int input[], int sum) {
method threeSum (line 50) | public List<List<Integer>> threeSum(int[] nums) {
method main (line 84) | public static void main(String args[]){
FILE: src/com/interview/array/TripletSumLessThanTotal.java
class TripletSumLessThanTotal (line 13) | public class TripletSumLessThanTotal {
method findAllTriplets (line 15) | public int findAllTriplets(int input[], int total) {
method main (line 34) | public static void main(String args[]) {
FILE: src/com/interview/array/TugOfWar.java
class TugOfWar (line 9) | public class TugOfWar {
method findMind (line 12) | public int findMind(int arr[]){
method combinationUtil (line 22) | private void combinationUtil(int arr[],int k, int start,int sum, int t...
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/array/WaterContainer.java
class WaterContainer (line 10) | public class WaterContainer {
method maxArea (line 11) | public int maxArea(int[] height) {
FILE: src/com/interview/array/WiggleSort.java
class WiggleSort (line 17) | public class WiggleSort {
method wiggleSort2 (line 20) | public void wiggleSort2(int[] arr) {
method wiggleSort1 (line 46) | public void wiggleSort1(int[] nums) {
method next (line 62) | private int next(int index, int n) {
method swap (line 66) | private void swap(int arr[],int low,int high){
method main (line 72) | public static void main(String args[]) {
FILE: src/com/interview/array/ZigZagArrangement.java
class ZigZagArrangement (line 16) | public class ZigZagArrangement {
method rearrange (line 18) | public void rearrange(int input[]) {
method swap (line 34) | private void swap(int input[], int i, int j) {
method main (line 40) | public static void main(String args[]) {
FILE: src/com/interview/binarysearch/ArithmeticProgressionSearch.java
class ArithmeticProgressionSearch (line 6) | public class ArithmeticProgressionSearch {
method search (line 8) | public int search(int input[]){
method main (line 26) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/BinarySearch.java
class BinarySearch (line 6) | public class BinarySearch {
method search (line 8) | public int search(final int input[], int search) {
method main (line 25) | public static void main(String args[]) {
FILE: src/com/interview/binarysearch/CircularBinarySearch.java
class CircularBinarySearch (line 14) | public class CircularBinarySearch {
method search (line 18) | public int search(int arr[]) {
method main (line 45) | public static void main(String args[]) {
FILE: src/com/interview/binarysearch/CountNDistinctPairsWithDifferenceK.java
class CountNDistinctPairsWithDifferenceK (line 8) | public class CountNDistinctPairsWithDifferenceK {
method count (line 10) | public int count(int arr[],int k){
method binarySearch (line 22) | private boolean binarySearch(int arr[],int start,int end,int num){
method main (line 37) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/FirstOccurrenceOfNumberInSortedArray.java
class FirstOccurrenceOfNumberInSortedArray (line 6) | public class FirstOccurrenceOfNumberInSortedArray {
method firstOccurrence (line 8) | public int firstOccurrence(int input[], int x){
method main (line 25) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/FloorAndCeilingSortedArray.java
class FloorAndCeilingSortedArray (line 6) | public class FloorAndCeilingSortedArray {
method floor (line 8) | public int floor(int input[], int x){
method ceiling (line 24) | public int ceiling(int input[], int x){
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/MedianOfTwoSortedArray.java
class MedianOfTwoSortedArray (line 6) | public class MedianOfTwoSortedArray {
method median (line 8) | public double median(int arr1[],int arr2[]){
method getMedian (line 48) | private double getMedian(int arr[],int low,int high){
method main (line 57) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/MedianOfTwoSortedArrayOfDifferentLength.java
class MedianOfTwoSortedArrayOfDifferentLength (line 18) | public class MedianOfTwoSortedArrayOfDifferentLength {
method findMedianSortedArrays (line 20) | public double findMedianSortedArrays(int input1[], int input2[]) {
method main (line 62) | public static void main(String[] args) {
FILE: src/com/interview/binarysearch/MinimumInSortedRotatedArray.java
class MinimumInSortedRotatedArray (line 6) | public class MinimumInSortedRotatedArray {
method findMin (line 7) | public int findMin(int[] nums) {
FILE: src/com/interview/binarysearch/MissingNumberInConsecutiveNumbers.java
class MissingNumberInConsecutiveNumbers (line 6) | public class MissingNumberInConsecutiveNumbers {
method findMissing (line 8) | public Integer findMissing(int arr[]){
method main (line 28) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/MonotonicallyIncreasingFunctionBecomesPositive.java
class MonotonicallyIncreasingFunctionBecomesPositive (line 6) | public class MonotonicallyIncreasingFunctionBecomesPositive {
method f (line 8) | private int f(int x){
method findPoint (line 12) | public int findPoint(){
method binarySearch (line 20) | private int binarySearch(int start,int end){
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/NumberOfPairWithXPowerYGreaterThanYPowerX.java
class NumberOfPairWithXPowerYGreaterThanYPowerX (line 10) | public class NumberOfPairWithXPowerYGreaterThanYPowerX {
method countPairs (line 12) | public int countPairs(int X[],int Y[]){
method count (line 32) | private int count(int x, int Y[],Map<Integer,Integer> hardCount){
method upperBound (line 52) | private int upperBound(int x, int arr[]){
method main (line 69) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/PeakElement.java
class PeakElement (line 13) | public class PeakElement {
method findPeakElement (line 15) | public int findPeakElement(int[] nums) {
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/SearchForRange.java
class SearchForRange (line 14) | public class SearchForRange {
method searchRange (line 15) | public int[] searchRange(int[] nums, int target) {
method firstOccurence (line 24) | private int firstOccurence(int[] nums, int target) {
method lastOccurence (line 40) | private int lastOccurence(int[] nums, int target) {
method main (line 56) | public static void main(String args[]) {
FILE: src/com/interview/binarysearch/SearchInsertPosition.java
class SearchInsertPosition (line 6) | public class SearchInsertPosition {
method searchInsert (line 7) | public int searchInsert(int[] nums, int target) {
FILE: src/com/interview/binarysearch/SortedAndRotatedArraySearch.java
class SortedAndRotatedArraySearch (line 16) | public class SortedAndRotatedArraySearch {
method search (line 21) | public int search(int arr[],int search){
method searchWithDuplicates (line 50) | public boolean searchWithDuplicates(int[] arr, int search) {
method main (line 80) | public static void main(String args[]){
FILE: src/com/interview/binarysearch/SquareRootOfNumber.java
class SquareRootOfNumber (line 7) | public class SquareRootOfNumber {
method mySqrt (line 8) | public int mySqrt(int x) {
FILE: src/com/interview/bits/AddTwoNumberInBinaryRepresentation.java
class AddTwoNumberInBinaryRepresentation (line 8) | public class AddTwoNumberInBinaryRepresentation {
method add (line 10) | public int add(char[] num1,char[] num2){
method addTwoNumbersWithoutArithmeticOperator (line 42) | public int addTwoNumbersWithoutArithmeticOperator(int num1,int num2){
method addTwoNumbersWithoutArithmeticOperatorFaster (line 59) | public int addTwoNumbersWithoutArithmeticOperatorFaster(int num1,int n...
method printResult (line 68) | public void printResult(int num){
method main (line 78) | public static void main(String args[]){
FILE: src/com/interview/bits/BitRotation.java
class BitRotation (line 6) | public class BitRotation {
method rotateLeft (line 8) | public byte rotateLeft(byte num, int d){
method main (line 12) | public static void main(String args[]){
FILE: src/com/interview/bits/ByteAsStorage.java
class ByteAsStorage (line 3) | public class ByteAsStorage {
method useByteAsBoolean (line 5) | void useByteAsBoolean(boolean[] visited){
method main (line 27) | public static void main(String args[]){
FILE: src/com/interview/bits/CountBits.java
class CountBits (line 6) | public class CountBits {
method CountBits (line 8) | public CountBits(){
method countBits (line 11) | public int countBits(int num){
method preCalculate (line 22) | void preCalculate(){
method countBitsFaster (line 28) | public int countBitsFaster(int num){
method countBitsEvenFaster (line 40) | public int countBitsEvenFaster(int x){
method main (line 53) | public static void main(String args[]){
FILE: src/com/interview/bits/CountingBitsTillNum.java
class CountingBitsTillNum (line 15) | public class CountingBitsTillNum {
method countBits (line 16) | public int[] countBits(int num) {
FILE: src/com/interview/bits/DrawHorizontalLine.java
class DrawHorizontalLine (line 6) | public class DrawHorizontalLine {
method draw (line 8) | public void draw(byte[] screen, int width, int x1, int x2,int y){
method drawFaster (line 23) | public void drawFaster(byte[] screen,int width,int x1,int x2,int y){
method printScreen (line 47) | private void printScreen(byte[] screen,int width){
method main (line 64) | public static void main(String args[]){
FILE: src/com/interview/bits/FindNumberOccurringOnceOtherNumbers3Times.java
class FindNumberOccurringOnceOtherNumbers3Times (line 6) | public class FindNumberOccurringOnceOtherNumbers3Times {
method getNumberOccurringOnce (line 8) | public int getNumberOccurringOnce(int arr[]){
method main (line 20) | public static void main(String args[]){
FILE: src/com/interview/bits/GrayCode.java
class GrayCode (line 14) | public class GrayCode {
method grayCode (line 15) | public List<Integer> grayCode(int n) {
method main (line 23) | public static void main(String args[]) {
FILE: src/com/interview/bits/InsertMintoNiTojBits.java
class InsertMintoNiTojBits (line 6) | public class InsertMintoNiTojBits {
method insert (line 8) | public int insert(int M,int N, int i, int j){
method main (line 18) | public static void main(String args[]){
FILE: src/com/interview/bits/MaxProductWordLength.java
class MaxProductWordLength (line 18) | public class MaxProductWordLength {
method maxProduct (line 19) | public int maxProduct(String[] words) {
FILE: src/com/interview/bits/MissingNumbers.java
class Pair (line 3) | class Pair{
class MissingNumbers (line 12) | public class MissingNumbers {
method findMissingAndRepeated (line 14) | public Pair findMissingAndRepeated(int arr[], int n){
method findTwoMissingNumber (line 47) | public Pair findTwoMissingNumber(int arr[], int n){
method main (line 80) | public static void main(String args[]){
FILE: src/com/interview/bits/NextHigherAndNextLowerWithSameNumberBits.java
class NextHigherAndNextLowerWithSameNumberBits (line 6) | public class NextHigherAndNextLowerWithSameNumberBits {
method nextHigher (line 8) | public int nextHigher(int n){
method nextLower (line 32) | public int nextLower(int n){
method main (line 57) | public static void main(String args[]){
FILE: src/com/interview/bits/NextPowerOf2.java
class NextPowerOf2 (line 6) | public class NextPowerOf2 {
method nextPowerOf2 (line 8) | public int nextPowerOf2(int num){
method main (line 20) | public static void main(String args[]){
FILE: src/com/interview/bits/NumberOccuringOddTimes.java
class NumberOccuringOddTimes (line 7) | public class NumberOccuringOddTimes {
method oneNumberOccuringOddTimes (line 9) | public int oneNumberOccuringOddTimes(int arr[]){
class Pair (line 17) | class Pair{
method twoNumbersOccuringOddTimes (line 23) | public Pair twoNumbersOccuringOddTimes(int arr[]){
method main (line 45) | public static void main(String args[]){
FILE: src/com/interview/bits/NumberOfBitsFlipToConvertNToM.java
class NumberOfBitsFlipToConvertNToM (line 6) | public class NumberOfBitsFlipToConvertNToM {
method number (line 8) | public int number(int m, int n){
method main (line 17) | public static void main(String args[]){
FILE: src/com/interview/bits/RealNumberToBinary.java
class RealNumberToBinary (line 6) | public class RealNumberToBinary {
method print (line 8) | public void print(double num){
method main (line 28) | public static void main(String args[]){
FILE: src/com/interview/bits/RepeatedDnaSequence.java
class RepeatedDnaSequence (line 16) | public class RepeatedDnaSequence {
method findRepeatedDnaSequences (line 21) | public List<String> findRepeatedDnaSequences(String s) {
method createString (line 51) | private String createString(int input) {
method add (line 59) | private int add(int input, char ch) {
method getVal (line 66) | private int getVal(char ch) {
method getChar (line 81) | private char getChar(int val) {
method main (line 96) | public static void main(String args[]) {
FILE: src/com/interview/bits/ReverseBits.java
class ReverseBits (line 6) | public class ReverseBits {
method reverse (line 8) | public int reverse(int num){
method main (line 21) | public static void main(String args[]){
FILE: src/com/interview/bits/SquareOfNumber.java
class SquareOfNumber (line 12) | public class SquareOfNumber {
method square (line 14) | public int square(int n){
method fastSquare (line 34) | public int fastSquare(int n){
method fastSquareRec (line 42) | private int fastSquareRec(int n, int leftToMultiply){
method main (line 57) | public static void main(String args[]){
FILE: src/com/interview/bits/SwapOddEvenBits.java
class SwapOddEvenBits (line 6) | public class SwapOddEvenBits {
method swap (line 8) | public int swap(int num){
method main (line 14) | public static void main(String args[]){
FILE: src/com/interview/bits/SwapTwoBits.java
class SwapTwoBits (line 6) | public class SwapTwoBits {
method swap (line 8) | public int swap(int num,int i, int j){
method betterSwap (line 18) | public int betterSwap(int num,int i,int j){
method main (line 26) | public static void main(String args[]){
FILE: src/com/interview/bits/WinnerWithBeautifulNumber.java
class WinnerWithBeautifulNumber (line 14) | public class WinnerWithBeautifulNumber {
method winner (line 16) | public int winner(int n){
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/dynamic/BitonicSequence.java
class BitonicSequence (line 6) | public class BitonicSequence {
method longestSequence (line 8) | public int longestSequence(int arr[]){
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/dynamic/BoxStacking.java
class BoxStacking (line 28) | public class BoxStacking {
method maxHeight (line 30) | public int maxHeight(Dimension[] input) {
method createAllRotation (line 74) | private void createAllRotation(Dimension[] input,
method main (line 88) | public static void main(String args[]) {
class Dimension (line 102) | class Dimension implements Comparable<Dimension> {
method Dimension (line 107) | Dimension(int height, int length, int width) {
method Dimension (line 113) | Dimension() {
method createDimension (line 116) | static Dimension createDimension(int height, int side1, int side2) {
method compareTo (line 132) | @Override
method toString (line 141) | @Override
FILE: src/com/interview/dynamic/BreakMultipleWordsWithNoSpaceIntoSpace.java
class BreakMultipleWordsWithNoSpaceIntoSpace (line 28) | public class BreakMultipleWordsWithNoSpaceIntoSpace {
method breakWord (line 35) | public String breakWord(char[] str,int low,Set<String> dictionary){
method breakWordDP (line 60) | public String breakWordDP(String word, Set<String> dict){
method wordBreakTopDown (line 113) | public List<String> wordBreakTopDown(String s, Set<String> wordDict) {
method wordBreakUtil (line 122) | private List<String> wordBreakUtil(String s, Set<String> dict, Map<Int...
method wordBreakTopDownOneSolution (line 151) | public boolean wordBreakTopDownOneSolution(String s, Set<String> wordD...
method wordBreakTopDownOneSolutionUtil (line 161) | private boolean wordBreakTopDownOneSolutionUtil(String s, Set<String> ...
method wordBreakBottomUp (line 184) | public boolean wordBreakBottomUp(String s, List<String> wordList) {
method main (line 202) | public static void main(String args[]){
FILE: src/com/interview/dynamic/BurstBalloons.java
class BurstBalloons (line 19) | public class BurstBalloons {
method maxCoinsBottomUpDp (line 24) | public int maxCoinsBottomUpDp(int[] nums) {
method maxCoinsRec (line 66) | public int maxCoinsRec(int nums[]) {
method maxCoinsRecUtil (line 76) | private int maxCoinsRecUtil(int[] nums) {
method formNewArray (line 92) | private int[] formNewArray(int[] input, int doNotIncludeIndex) {
method main (line 105) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/CoinChanging.java
class CoinChanging (line 16) | public class CoinChanging {
method numberOfSolutions (line 18) | public int numberOfSolutions(int total, int coins[]){
method numberOfSolutionsOnSpace (line 39) | public int numberOfSolutionsOnSpace(int total, int arr[]){
method printCoinChangingSolution (line 57) | public void printCoinChangingSolution(int total,int coins[]){
method printActualSolution (line 62) | private void printActualSolution(List<Integer> result,int total,int co...
method main (line 78) | public static void main(String args[]){
FILE: src/com/interview/dynamic/CoinChangingMinimumCoin.java
class CoinChangingMinimumCoin (line 21) | public class CoinChangingMinimumCoin {
method minimumCoinTopDown (line 27) | public int minimumCoinTopDown(int total, int coins[], Map<Integer, Int...
method minimumCoinBottomUp (line 70) | public int minimumCoinBottomUp(int total, int coins[]){
method printCoinCombination (line 92) | private void printCoinCombination(int R[], int coins[]) {
method main (line 107) | public static void main ( String args[] ) {
FILE: src/com/interview/dynamic/CountAs.java
class CountAs (line 10) | public class CountAs {
method countAsRec (line 12) | public int countAsRec(int n){
method countAs (line 28) | public int countAs(int n){
method main (line 45) | public static void main(String args[]){
FILE: src/com/interview/dynamic/CountNumberOfBinaryWithoutConsecutive1s.java
class CountNumberOfBinaryWithoutConsecutive1s (line 9) | public class CountNumberOfBinaryWithoutConsecutive1s {
method count (line 11) | public int count(int n){
method countSimple (line 26) | public int countSimple(int n){
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/dynamic/CountNumberOfTreePreorder.java
class CountNumberOfTreePreorder (line 21) | public class CountNumberOfTreePreorder {
method count (line 23) | public int count(int num){
method countRec (line 40) | public int countRec(int num){
method main (line 51) | public static void main(String args[]){
FILE: src/com/interview/dynamic/CountNumberOfTreesInBST.java
class CountNumberOfTreesInBST (line 7) | public class CountNumberOfTreesInBST {
method countTreesRec (line 9) | int countTreesRec(int numKeys) {
method countTrees (line 25) | public int countTrees(int n){
method main (line 36) | public static void main(String args[]){
FILE: src/com/interview/dynamic/CutRodToMinimizeCost.java
class CutRodToMinimizeCost (line 14) | public class CutRodToMinimizeCost {
method cutRodToMinimizeCost (line 17) | public int cutRodToMinimizeCost(int [] markings, int total) {
method cutRodToMinimizeCost (line 27) | private int cutRodToMinimizeCost(int[] markings, int start, int end, i...
method main (line 78) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/CuttingRod.java
class CuttingRod (line 6) | public class CuttingRod {
method maxValue (line 8) | public int maxValue(int price[]){
method maxValue1 (line 18) | public int maxValue1(int price[]){
method recursiveMaxValue (line 31) | public int recursiveMaxValue(int price[],int len){
method main (line 44) | public static void main(String args[]){
FILE: src/com/interview/dynamic/DecodeWays.java
class DecodeWays (line 16) | public class DecodeWays {
method numDecodings (line 18) | public int numDecodings(String s) {
method numDecodingsUtil (line 26) | public int numDecodingsUtil(String s, int start, Map<Integer, Integer>...
FILE: src/com/interview/dynamic/DiceThrowWays.java
class DiceThrowWays (line 9) | public class DiceThrowWays {
method numberOfWays (line 11) | public int numberOfWays(int n, int f, int k){
method main (line 38) | public static void main(String args[]){
FILE: src/com/interview/dynamic/DistinctSubsequence.java
class DistinctSubsequence (line 14) | public class DistinctSubsequence {
method numDistinct (line 15) | public int numDistinct(String s, String t) {
method main (line 35) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/DungeonGame.java
class DungeonGame (line 14) | public class DungeonGame {
method calculateMinimumHP (line 15) | public int calculateMinimumHP(int[][] dungeon) {
method main (line 43) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/EditDistance.java
class EditDistance (line 18) | public class EditDistance {
method recEditDistance (line 23) | public int recEditDistance(char[] str1, char str2[], int len1,int len2){
method dynamicEditDistance (line 37) | public int dynamicEditDistance(char[] str1, char[] str2){
method printActualEdits (line 65) | public void printActualEdits(int T[][], char[] str1, char[] str2) {
method min (line 92) | private int min(int a,int b, int c){
method main (line 97) | public static void main(String args[]){
FILE: src/com/interview/dynamic/EggDropping.java
class EggDropping (line 6) | public class EggDropping {
method calculate (line 8) | public int calculate(int eggs, int floors){
method calculateRecursive (line 30) | public int calculateRecursive(int eggs, int floors){
method main (line 47) | public static void main(String args[]){
FILE: src/com/interview/dynamic/ExpressionEvaluation.java
class ExpressionEvaluation (line 17) | public class ExpressionEvaluation {
method evaluate (line 19) | public boolean evaluate(char[] expression, int result) {
method operate (line 70) | private int operate(char operator, int x, int y) {
class Holder (line 84) | static class Holder {
method add (line 86) | void add(Integer ch) {
method values (line 89) | Set<Integer> values() {
method main (line 94) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/FibonacciSeries.java
class FibonacciSeries (line 24) | public class FibonacciSeries {
method fibonacciSeries (line 30) | public int fibonacciSeries(int n){
method fibonacciSeriesRecursive (line 51) | public int fibonacciSeriesRecursive(int n){
method main (line 58) | public static void main(String args[]){
FILE: src/com/interview/dynamic/Immutable2DSumRangeQuery.java
class Immutable2DSumRangeQuery (line 16) | public class Immutable2DSumRangeQuery {
method Immutable2DSumRangeQuery (line 19) | public Immutable2DSumRangeQuery(int[][] matrix) {
method sumQuery (line 34) | public int sumQuery(int row1, int col1, int row2, int col2) {
method main (line 42) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/Knapsack01.java
class Knapsack01 (line 24) | public class Knapsack01 {
method bottomUpDP (line 29) | public int bottomUpDP(int val[], int wt[], int W){
class Index (line 50) | class Index {
method equals (line 54) | @Override
method hashCode (line 66) | @Override
method topDownRecursive (line 77) | public int topDownRecursive(int values[], int weights[], int W) {
method topDownRecursiveUtil (line 83) | public int topDownRecursiveUtil(int values[], int weights[], int remai...
method main (line 114) | public static void main(String args[]){
FILE: src/com/interview/dynamic/LongestCommonSubsequence.java
class LongestCommonSubsequence (line 6) | public class LongestCommonSubsequence {
method lcs (line 8) | public int lcs(char str1[],char str2[],int len1, int len2){
method lcsDynamic (line 21) | public int lcsDynamic(char str1[],char str2[]){
method main (line 43) | public static void main(String args[]){
FILE: src/com/interview/dynamic/LongestCommonSubstring.java
class LongestCommonSubstring (line 6) | public class LongestCommonSubstring {
method longestCommonSubstring (line 11) | public int longestCommonSubstring(char str1[], char str2[]){
method longestCommonSubstringRec (line 31) | public int longestCommonSubstringRec(char str1[], char str2[], int pos...
method main (line 49) | public static void main(String args[]){
FILE: src/com/interview/dynamic/LongestEvenLengthSubstringOfEqualHalf.java
class LongestEvenLengthSubstringOfEqualHalf (line 10) | public class LongestEvenLengthSubstringOfEqualHalf {
method findMaxLength (line 12) | public int findMaxLength(int input[]){
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/dynamic/LongestIncreasingPath.java
class LongestIncreasingPath (line 15) | public class LongestIncreasingPath {
method longestIncreasingPath (line 17) | public int longestIncreasingPath(int[][] matrix) {
method dfs (line 34) | int dfs(int[][] matrix, int i, int j, int[][] distance, int prev) {
method main (line 55) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/LongestIncreasingSubsequence.java
class LongestIncreasingSubsequence (line 23) | public class LongestIncreasingSubsequence {
method longestSubsequenceWithActualSolution (line 28) | public int longestSubsequenceWithActualSolution(int arr[]){
method longestSubsequenceRecursive (line 72) | public int longestSubsequenceRecursive(int arr[]){
method longestSubsequenceRecursive (line 83) | private int longestSubsequenceRecursive(int arr[], int pos, int lastNum){
method main (line 95) | public static void main(String args[]){
FILE: src/com/interview/dynamic/LongestPalindromicSubsequence.java
class LongestPalindromicSubsequence (line 17) | public class LongestPalindromicSubsequence {
method calculate1 (line 19) | public int calculate1(char []str){
method calculateRecursive (line 40) | public int calculateRecursive(char str[],int start,int len){
method main (line 54) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MatrixMultiplicationCost.java
class MatrixMultiplicationCost (line 6) | public class MatrixMultiplicationCost {
method findCost (line 8) | public int findCost(int arr[]){
method main (line 26) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MaxSumForNonAdjacentElements.java
class MaxSumForNonAdjacentElements (line 17) | public class MaxSumForNonAdjacentElements {
method maxSum (line 22) | public int maxSum(int arr[]) {
method maxSum (line 36) | public int maxSum(int arr[], int index) {
method maxSumCircularArray (line 51) | public int maxSumCircularArray(int[] nums) {
method main (line 76) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/MaximizeSkiGates.java
class MaximizeSkiGates (line 19) | public class MaximizeSkiGates {
class Index (line 20) | class Index {
method Index (line 26) | Index(int remainingChanges, int current, boolean isRight, int prevIt...
method equals (line 33) | @Override
method hashCode (line 47) | @Override
method solution (line 57) | public int solution(int gates[], int totalDirectionChanges) {
method solution (line 62) | public int solution(int gates[], int remainingDirectionChanges, int cu...
method main (line 92) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/MaximumLengthChainPair.java
class MaximumLengthChainPair (line 8) | public class MaximumLengthChainPair {
class Pair (line 10) | static class Pair implements Comparable<Pair>{
method Pair (line 11) | public Pair(int a,int b){
method compareTo (line 17) | @Override
method maxLength (line 27) | public int maxLength(Pair[] arr){
method main (line 51) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MaximumProductCutting.java
class MaximumProductCutting (line 6) | public class MaximumProductCutting {
method maxProduct (line 8) | public int maxProduct(int num){
method main (line 22) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MaximumRectangularSubmatrixOf1s.java
class MaximumRectangularSubmatrixOf1s (line 28) | public class MaximumRectangularSubmatrixOf1s {
method maximum (line 30) | public int maximum(int input[][]){
method main (line 51) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MaximumSizeSubMatrix.java
class MaximumSizeSubMatrix (line 6) | public class MaximumSizeSubMatrix {
method min (line 8) | private int min(int a,int b, int c){
method maxSize (line 13) | public int maxSize(int arr[][]){
method main (line 51) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MaximumSumSubsequence.java
class MaximumSumSubsequence (line 15) | public class MaximumSumSubsequence {
method maxSum (line 17) | public int maxSum(int arr[]){
method main (line 41) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MinCostPath.java
class MinCostPath (line 6) | public class MinCostPath {
method minCost (line 8) | public int minCost(int [][]cost,int m,int n){
method minCostRec (line 30) | public int minCostRec(int cost[][], int m, int n){
method minCostRec (line 34) | public int minCostRec(int cost[][], int m, int n, int x, int y){
method min (line 49) | private int min(int a,int b, int c){
method main (line 54) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MinJumpToReachEnd.java
class MinJumpToReachEnd (line 23) | public class MinJumpToReachEnd {
method minJump (line 25) | public int minJump(int arr[],int result[]){
method jump (line 50) | public int jump(int[] nums) {
method main (line 71) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MinimumCostTrainTicket.java
class MinimumCostTrainTicket (line 6) | public class MinimumCostTrainTicket {
method minCost (line 8) | public int minCost(int ticket[][]){
method main (line 37) | public static void main(String args[]){
FILE: src/com/interview/dynamic/MinimumNumberOfPerfectSquares.java
class MinimumNumberOfPerfectSquares (line 18) | public class MinimumNumberOfPerfectSquares {
method numSquaresUsingDP (line 19) | public int numSquaresUsingDP(int n) {
method numSquaresUsingBFS (line 38) | public int numSquaresUsingBFS(int n) {
FILE: src/com/interview/dynamic/MinimumTriangleSum.java
class MinimumTriangleSum (line 10) | public class MinimumTriangleSum {
method minimumTotal (line 11) | public int minimumTotal(List<List<Integer>> triangle) {
FILE: src/com/interview/dynamic/NPotGold.java
class NPotGold (line 8) | public class NPotGold {
class Pair (line 10) | static class Pair{
method toString (line 13) | public String toString(){
method findMoves (line 17) | public Pair[][] findMoves(int pots[]){
method printSequence (line 51) | public void printSequence(int pots[], Pair moves[][]){
method main (line 66) | public static void main(String args[]){
FILE: src/com/interview/dynamic/NumberOfPathsInMxNMatrix.java
class NumberOfPathsInMxNMatrix (line 6) | public class NumberOfPathsInMxNMatrix {
method countPathsRecursive (line 8) | public int countPathsRecursive(int n, int m){
method countPaths (line 15) | public int countPaths(int n,int m){
method main (line 32) | public static void main(String args[]){
FILE: src/com/interview/dynamic/NumberOfWaysToScorePoints.java
class NumberOfWaysToScorePoints (line 9) | public class NumberOfWaysToScorePoints {
method version1 (line 13) | public int version1(int score[],int total){
method version2 (line 28) | public int version2(int score[],int total){
method main (line 41) | public static void main(String args[]){
FILE: src/com/interview/dynamic/OptimalTreeSearch.java
class OptimalTreeSearch (line 6) | public class OptimalTreeSearch {
method minCostRec (line 8) | public int minCostRec(int input[],int freq[]){
method minCostRec (line 13) | private int minCostRec(int input[],int freq[],int low,int high,int lev...
method minCost (line 30) | public int minCost(int input[], int freq[]){
method getSum (line 55) | private int getSum(int freq[], int i, int j){
method main (line 64) | public static void main(String args[]){
FILE: src/com/interview/dynamic/PaintHouse.java
class PaintHouse (line 8) | public class PaintHouse {
method minCostTopDownPainHouse1or2 (line 10) | public int minCostTopDownPainHouse1or2(int[][] costs) {
method minCostUtil (line 18) | private int minCostUtil(int[][] costs, int house, int prevColor, int k...
method minCostBottomUpPaintHouse2 (line 39) | public int minCostBottomUpPaintHouse2(int[][] costs) {
class Pair (line 66) | class Pair {
method findMinSecondMin (line 71) | private Pair findMinSecondMin(int[] input) {
method main (line 95) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/PalindromePartition.java
class PalindromePartition (line 14) | public class PalindromePartition {
method minCut (line 21) | public int minCut(String str){
method partition (line 45) | public List<List<String>> partition(String s) {
method partitionUtil (line 55) | private List<List<String>> partitionUtil(String s, Map<Integer, List<L...
method isPalindrome (line 83) | private boolean isPalindrome(String str, int r, int t) {
FILE: src/com/interview/dynamic/PhoneDialNumberOfCombinationOfSizeK.java
class PhoneDialNumberOfCombinationOfSizeK (line 15) | public class PhoneDialNumberOfCombinationOfSizeK {
method numberOfCombination (line 24) | public int numberOfCombination(int k, int input[][]) {
method copyMap (line 59) | private void copyMap(Map<Integer, Integer> t, Map<Integer, Integer> t1) {
method findNeighborsAndPopulateMap (line 66) | private void findNeighborsAndPopulateMap(int x, int y, int input[][],
method updateMap (line 75) | private void updateMap(int input[][], int x, int y, int i, int j,
method main (line 89) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/RegexMatching.java
class RegexMatching (line 10) | public class RegexMatching {
method matchRegexRecursive (line 12) | public boolean matchRegexRecursive(char[] str, char[] pattern){
method matchRegexRecursive (line 16) | private boolean matchRegexRecursive(char text[], char pattern[], int p...
method matchRegex (line 50) | public boolean matchRegex(char[] text, char[] pattern) {
method main (line 78) | public static void main(String args[]){
FILE: src/com/interview/dynamic/RemoveFromEndToMake2IntoMinGreaterThanMax.java
class RemoveFromEndToMake2IntoMinGreaterThanMax (line 6) | public class RemoveFromEndToMake2IntoMinGreaterThanMax {
method removeFromEnd (line 8) | public int removeFromEnd(int input[]){
method removeFromEnd (line 12) | private int removeFromEnd(int input[],int low,int high){
method min (line 25) | private int min(int input[],int low,int high){
method max (line 34) | private int max(int input[],int low,int high){
method removeFromEndDynamic (line 44) | public int removeFromEndDynamic(int input[]){
method main (line 59) | public static void main(String args[]){
FILE: src/com/interview/dynamic/ScrambledString.java
class ScrambledString (line 9) | public class ScrambledString {
class Index (line 14) | private static class Index {
method equals (line 19) | @Override
method hashCode (line 33) | @Override
method isScrambled (line 45) | boolean isScrambled(char input1[], char input2[], int start1, int end1...
method main (line 129) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/StockBuySellKTransactions.java
class StockBuySellKTransactions (line 18) | public class StockBuySellKTransactions {
method maxProfitLinearSpace (line 23) | public int maxProfitLinearSpace(int k, int[] prices) {
method allTimeProfit (line 46) | public int allTimeProfit(int arr[]){
method maxProfit (line 69) | public int maxProfit(int prices[], int K) {
method maxProfitSlowSolution (line 91) | public int maxProfitSlowSolution(int prices[], int K) {
method printActualSolution (line 110) | public void printActualSolution(int T[][], int prices[]) {
method main (line 142) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/SubRectangularMatrixWithMaximumSum.java
class SubRectangularMatrixWithMaximumSum (line 22) | public class SubRectangularMatrixWithMaximumSum {
class Result (line 24) | class Result{
method toString (line 30) | @Override
method maxSum (line 39) | public Result maxSum(int input[][]){
class KadaneResult (line 65) | class KadaneResult{
method KadaneResult (line 69) | public KadaneResult(int maxSum, int start, int end) {
method kadane (line 76) | private KadaneResult kadane(int arr[]){
method main (line 98) | public static void main(String args[]){
FILE: src/com/interview/dynamic/SubsetSum.java
class SubsetSum (line 15) | public class SubsetSum {
method subsetSum (line 17) | public boolean subsetSum(int input[], int total) {
method partition (line 37) | public boolean partition(int arr[]) {
method main (line 65) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/SubsquareSurrounedByXs.java
class SubsquareSurrounedByXs (line 30) | public class SubsquareSurrounedByXs {
class Cell (line 32) | class Cell{
method findSubSquare (line 36) | public int findSubSquare(char input[][]){
method main (line 96) | public static void main(String args[]){
FILE: src/com/interview/dynamic/SymbolExpressionEvaluation.java
class SymbolExpressionEvaluation (line 18) | public class SymbolExpressionEvaluation {
method evaluateExpression (line 20) | public boolean evaluateExpression(char input[][], Map<Character, Integ...
method main (line 53) | public static void main(String args[]) {
class Holder (line 66) | class Holder {
method add (line 68) | void add(Character ch) {
method values (line 71) | Set<Character> values() {
FILE: src/com/interview/dynamic/TextJustification.java
class TextJustification (line 34) | public class TextJustification {
method justify (line 36) | public String justify(String words[], int width) {
method main (line 98) | public static void main(String args[]){
FILE: src/com/interview/dynamic/TwoStringInterleavingToFormThird.java
class TwoStringInterleavingToFormThird (line 7) | public class TwoStringInterleavingToFormThird {
method isInterleavedRecursive (line 9) | public boolean isInterleavedRecursive(char str1[], char str2[], char s...
method isInterleaved (line 23) | public boolean isInterleaved(char str1[], char str2[], char str3[]){
method main (line 54) | public static void main(String args[]){
FILE: src/com/interview/dynamic/UglyNumbers.java
class UglyNumbers (line 15) | public class UglyNumbers {
class Node (line 17) | static class Node implements Comparable<Node> {
method Node (line 21) | Node (int inputIndex, int index, int val) {
method compareTo (line 27) | @Override
method nthSuperUglyNumber1 (line 33) | public int nthSuperUglyNumber1(int n, int[] primes) {
method ugly (line 54) | int ugly(int n){
method min (line 78) | private int min(int a,int b, int c){
method main (line 83) | public static void main(String args[]) {
FILE: src/com/interview/dynamic/WeightedJobSchedulingMaximumProfit.java
class Job (line 6) | class Job{
method Job (line 10) | Job(int start,int end,int profit){
class FinishTimeComparator (line 17) | class FinishTimeComparator implements Comparator<Job>{
method compare (line 19) | @Override
class WeightedJobSchedulingMaximumProfit (line 35) | public class WeightedJobSchedulingMaximumProfit {
method maximum (line 45) | public int maximum(Job[] jobs){
method main (line 69) | public static void main(String args[]){
FILE: src/com/interview/dynamic/WildCardMatching.java
class WildCardMatching (line 12) | public class WildCardMatching {
method isMatch (line 13) | public boolean isMatch(String s, String p) {
method isMatchRecursive (line 58) | public boolean isMatchRecursive(String s, String p) {
method isMatchRecursiveUtil (line 62) | private boolean isMatchRecursiveUtil(char[] text, char[] pattern, int ...
method main (line 89) | public static void main(String args[]) {
FILE: src/com/interview/geometry/ClosestPairOfPoints.java
class Point (line 29) | class Point{
method Point (line 32) | Point(int x, int y){
class XCoordinatorSorter (line 38) | class XCoordinatorSorter implements Comparator<Point>{
method compare (line 39) | @Override
class YCoordinatorSorter (line 49) | class YCoordinatorSorter implements Comparator<Point>{
method compare (line 50) | @Override
class ClosestPairOfPoints (line 60) | public class ClosestPairOfPoints {
method closestPairOfPoints (line 63) | public double closestPairOfPoints(Point[] points){
method closestPairOfPoints (line 85) | private int closestPairOfPoints(Point[] px, Point[] py,int start, int ...
method closest (line 115) | private int closest(List<Point> deltaPoints){
method distance (line 128) | private int distance(Point p1, Point p2){
method computeMinDistance (line 132) | private int computeMinDistance(Point[] points, int start, int end){
method main (line 149) | public static void main(String args[]){
FILE: src/com/interview/geometry/GrahamScanConvexHull.java
class GrahamScanConvexHull (line 26) | public class GrahamScanConvexHull {
class Point (line 28) | static class Point{
method Point (line 31) | Point(int x, int y){
method findConvexHull (line 37) | public List<Point> findConvexHull(Point[] points) {
method sortToHandleCollinear (line 71) | private void sortToHandleCollinear(Point[] points, Point start) {
method distance (line 106) | private int distance(Point a, Point b, Point c) {
method crossProduct (line 120) | private int crossProduct(Point a, Point b, Point c) {
method main (line 128) | public static void main(String[] args) {
FILE: src/com/interview/geometry/JarvisMarchConvexHull.java
class JarvisMarchConvexHull (line 29) | public class JarvisMarchConvexHull {
class Point (line 31) | class Point{
method Point (line 34) | Point(int x, int y){
method findConvexHull (line 40) | public List<Point> findConvexHull(Point[] points) {
method distance (line 97) | private int distance(Point a, Point b, Point c) {
method crossProduct (line 111) | private int crossProduct(Point a, Point b, Point c) {
FILE: src/com/interview/geometry/MaximumPointsOnSameLine.java
class MaximumPointsOnSameLine (line 17) | public class MaximumPointsOnSameLine {
class Point (line 19) | static class Point {
method Point (line 22) | Point() { x = 0; y = 0; }
method Point (line 23) | Point(int a, int b) { x = a; y = b; }
class Pair (line 26) | class Pair {
method equals (line 30) | @Override
method hashCode (line 42) | @Override
method maxPoints (line 50) | public int maxPoints(Point[] points) {
method gcd (line 85) | int gcd(int a, int b) {
FILE: src/com/interview/geometry/SkylineDrawing.java
class SkylineDrawing (line 18) | public class SkylineDrawing {
class BuildingPoint (line 23) | static class BuildingPoint implements Comparable<BuildingPoint> {
method compareTo (line 28) | @Override
method getSkyline (line 43) | public List<int[]> getSkyline(int[][] buildings) {
method main (line 103) | public static void main(String args[]) {
FILE: src/com/interview/graph/AlientDictionary.java
class AlientDictionary (line 12) | public class AlientDictionary {
method alienOrder (line 13) | public String alienOrder(String[] words) {
method topSortUtil (line 33) | private boolean topSortUtil(char vertex, Deque<Character> stack, Set<C...
method buildGraph (line 58) | private Map<Character, Set<Character>> buildGraph(String words[], Map<...
method getAllChars (line 84) | private void getAllChars(String words[], Map<Character, Integer> degre...
method alienOrder1 (line 93) | public String alienOrder1(String words[]) {
method main (line 127) | public static void main(String args[]) {
FILE: src/com/interview/graph/AllCyclesInDirectedGraphJohnson.java
class AllCyclesInDirectedGraphJohnson (line 19) | public class AllCyclesInDirectedGraphJohnson {
method simpleCyles (line 28) | public List<List<Vertex<Integer>>> simpleCyles(Graph<Integer> graph) {
method leastIndexSCC (line 56) | private Optional<Vertex<Integer>> leastIndexSCC(List<Set<Vertex<Intege...
method unblock (line 85) | private void unblock(Vertex<Integer> u) {
method findCyclesInSCG (line 97) | private boolean findCyclesInSCG(
method getBSet (line 141) | private Set<Vertex<Integer>> getBSet(Vertex<Integer> v) {
method createSubGraph (line 146) | private Graph createSubGraph(long startVertex, Graph<Integer> graph) {
method main (line 156) | public static void main(String args[]) {
FILE: src/com/interview/graph/AllCyclesInDirectedGraphTarjan.java
class AllCyclesInDirectedGraphTarjan (line 14) | public class AllCyclesInDirectedGraphTarjan {
method AllCyclesInDirectedGraphTarjan (line 21) | public AllCyclesInDirectedGraphTarjan() {
method reset (line 25) | private void reset() {
method findAllSimpleCycles (line 32) | public List<List<Vertex<Integer>>> findAllSimpleCycles(Graph<Integer> ...
method findAllSimpleCycles (line 45) | private boolean findAllSimpleCycles(Vertex start, Vertex<Integer> curr...
method main (line 80) | public static void main(String args[]) {
FILE: src/com/interview/graph/ArticulationPoint.java
class ArticulationPoint (line 34) | public class ArticulationPoint<T> {
method findarticulationPoints (line 38) | public Set<Vertex<T>> findarticulationPoints(Graph<T> graph) {
method DFS (line 52) | private void DFS(Set<Vertex<T>> visited,
method main (line 97) | public static void main(String args[]){
FILE: src/com/interview/graph/BellmanFordShortestPath.java
class BellmanFordShortestPath (line 22) | public class BellmanFordShortestPath {
class NegativeWeightCycleException (line 28) | class NegativeWeightCycleException extends RuntimeException {
method getShortestPath (line 31) | public Map<Vertex<Integer>, Integer> getShortestPath(Graph<Integer> gr...
method main (line 76) | public static void main(String args[]){
FILE: src/com/interview/graph/BinaryMaxHeap.java
class BinaryMaxHeap (line 6) | public class BinaryMaxHeap<T> {
class Node (line 10) | class Node {
method add (line 15) | public void add(int weight,T data) {
method swap (line 39) | private void swap(Node node1,Node node2){
method max (line 50) | public T max(){
method empty (line 54) | public boolean empty(){
method extractMap (line 59) | public T extractMap(){
method printHeap (line 89) | public void printHeap(){
method main (line 95) | public static void main(String args[]){
FILE: src/com/interview/graph/BinaryMinHeap.java
class BinaryMinHeap (line 22) | public class BinaryMinHeap<T> {
class Node (line 27) | public class Node {
method containsData (line 35) | public boolean containsData(T key){
method add (line 42) | public void add(int weight,T key) {
method min (line 69) | public T min(){
method empty (line 76) | public boolean empty(){
method decrease (line 83) | public void decrease(T data, int newWeight){
method getWeight (line 102) | public Integer getWeight(T key) {
method extractMinNode (line 114) | public Node extractMinNode() {
method extractMin (line 153) | public T extractMin(){
method printPositionMap (line 158) | private void printPositionMap(){
method swap (line 162) | private void swap(Node node1,Node node2){
method updatePositionMap (line 173) | private void updatePositionMap(T data1, T data2, int pos1, int pos2){
method printHeap (line 180) | public void printHeap(){
method main (line 186) | public static void main(String args[]){
FILE: src/com/interview/graph/BiparteGraph.java
class BiparteGraph (line 12) | public class BiparteGraph {
method isBiparte (line 14) | public boolean isBiparte(Graph<Integer> graph){
method isBiparteDFS (line 54) | public boolean isBiparteDFS(Graph<Integer> graph){
method isBiparteDFS (line 69) | private boolean isBiparteDFS(Vertex<Integer> vertex, Set<Vertex<Intege...
method main (line 101) | public static void main(String argsp[]){
FILE: src/com/interview/graph/Boggle.java
class Boggle (line 18) | public class Boggle {
method findWords (line 20) | public List<String> findWords(char[][] board, String[] words) {
method findWordsUtil (line 36) | private void findWordsUtil(char[][] board, Trie t , int i, int j, Stri...
class TrieNode (line 68) | class TrieNode {
method TrieNode (line 71) | public TrieNode() {
class Trie (line 75) | class Trie {
method Trie (line 78) | public Trie() {
method insert (line 83) | public void insert(String word) {
method search (line 97) | public boolean search(String word) {
method startsWith (line 111) | public boolean startsWith(String prefix) {
method printTrie (line 123) | public void printTrie() {
method printTrieUtil (line 127) | private void printTrieUtil(TrieNode root) {
method main (line 140) | public static void main(String args[]) {
FILE: src/com/interview/graph/Bridge.java
class Bridge (line 11) | public class Bridge<T> {
method getBridge (line 15) | public Set<Edge<T>> getBridge(Graph<T> graph){
method BridgeUtil (line 31) | private void BridgeUtil(Vertex<T> vertex, Set<Edge<T>> result,Map<Vert...
method main (line 54) | public static void main(String args[]){
FILE: src/com/interview/graph/CloneDirectedGraph.java
class CloneDirectedGraph (line 16) | public class CloneDirectedGraph<T> {
method clone (line 18) | public Graph<T> clone(Graph<T> graph){
method clone (line 39) | private void clone(Vertex<T> origVertex,Map<Vertex<T>,Vertex<T>> clone...
method updateMap (line 58) | private void updateMap(Map<Vertex<T>,Vertex<T>> cloneMap, Vertex<T> cl...
method main (line 71) | public static void main(String args[]){
FILE: src/com/interview/graph/CloneGraph.java
class CloneGraph (line 9) | public class CloneGraph {
class UndirectedGraphNode (line 11) | class UndirectedGraphNode {
method UndirectedGraphNode (line 14) | UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<Un...
method cloneGraph (line 17) | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
method dfs (line 29) | private void dfs(UndirectedGraphNode current, UndirectedGraphNode clon...
FILE: src/com/interview/graph/ConvertOneWordToAnother.java
class ConvertOneWordToAnother (line 15) | public class ConvertOneWordToAnother {
method convert (line 17) | public void convert(String word1, String word2, Set<String> dict) {
method replace (line 50) | public String replace(String newWord, int pos, char ch) {
method main (line 59) | public static void main(String args[]){
FILE: src/com/interview/graph/CourseSchedule.java
class CourseSchedule (line 22) | public class CourseSchedule {
method findOrder (line 23) | public int[] findOrder(int numCourses, int[][] prerequisites) {
class Neighbors (line 52) | class Neighbors {
method topSort (line 56) | private boolean topSort(int course, Neighbors[] graph, boolean[] used,...
FILE: src/com/interview/graph/CycleInDirectedGraph.java
class CycleInDirectedGraph (line 9) | public class CycleInDirectedGraph {
method hasCycle (line 11) | public boolean hasCycle(Graph<Integer> graph) {
method dfs (line 29) | private boolean dfs(Vertex<Integer> current, Set<Vertex<Integer>> whit...
method moveVertex (line 51) | private void moveVertex(Vertex<Integer> vertex, Set<Vertex<Integer>> s...
method main (line 57) | public static void main(String args[]){
FILE: src/com/interview/graph/CycleUndirectedGraph.java
class CycleUndirectedGraph (line 19) | public class CycleUndirectedGraph<T> {
method hasCycleUsingDisjointSets (line 21) | public boolean hasCycleUsingDisjointSets(Graph<T> graph){
method hasCycleDFS (line 39) | public boolean hasCycleDFS(Graph<T> graph){
method hasCycleDFSUtil (line 53) | public boolean hasCycleDFSUtil(Vertex<T> vertex, Set<Vertex<T>> visite...
method main (line 70) | public static void main(String args[]){
FILE: src/com/interview/graph/DAGShortestPathTopological.java
class DAGShortestPathTopological (line 10) | public class DAGShortestPathTopological<T> {
method shortestPath (line 12) | public Map<Vertex<T>,Integer> shortestPath(Graph<T> graph,Vertex<T> st...
method getDistance (line 30) | private int getDistance( Vertex<T> vertex,Map<Vertex<T>,Integer> dista...
method main (line 34) | public static void main(String args[]){
FILE: src/com/interview/graph/DijkstraShortestPath.java
class DijkstraShortestPath (line 18) | public class DijkstraShortestPath {
method shortestPath (line 20) | public Map<Vertex<Integer>,Integer> shortestPath(Graph<Integer> graph,...
method getVertexForEdge (line 79) | private Vertex<Integer> getVertexForEdge(Vertex<Integer> v, Edge<Integ...
method main (line 83) | public static void main(String args[]){
FILE: src/com/interview/graph/DirectedGraphConnectivity.java
class DirectedGraphConnectivity (line 8) | public class DirectedGraphConnectivity {
method scc (line 10) | public boolean scc(Graph<Integer> graph) {
method DFSUtil (line 45) | private void DFSUtil(Vertex<Integer> vertex,
method DFSUtil1 (line 57) | private void DFSUtil1(Vertex<Integer> vertex,
method main (line 68) | public static void main(String args[]){
FILE: src/com/interview/graph/DisjointSet.java
class DisjointSet (line 22) | public class DisjointSet {
class Node (line 26) | class Node {
method makeSet (line 35) | public void makeSet(long data) {
method union (line 49) | public boolean union(long data1, long data2) {
method findSet (line 75) | public long findSet(long data) {
method findSet (line 83) | private Node findSet(Node node) {
method main (line 92) | public static void main(String args[]) {
FILE: src/com/interview/graph/EulerianPathAndCircuit.java
class EulerianPathAndCircuit (line 6) | public class EulerianPathAndCircuit<T> {
type Eulerian (line 8) | public enum Eulerian{
method isConnected (line 14) | private boolean isConnected(Graph<T> graph){
method DFS (line 41) | private void DFS(Vertex<T> startVertex, Map<Vertex<T>, Boolean> visited){
method isEulerian (line 50) | public Eulerian isEulerian(Graph<T> graph){
method main (line 71) | public static void main(String args[]){
FILE: src/com/interview/graph/EvaluateDivison.java
class EvaluateDivison (line 23) | public class EvaluateDivison {
method calcEquation (line 24) | public double[] calcEquation(String[][] equations, double[] values, St...
FILE: src/com/interview/graph/FillOsWIthXsIfSurroundedByXs.java
class FillOsWIthXsIfSurroundedByXs (line 13) | public class FillOsWIthXsIfSurroundedByXs {
method solve (line 15) | public void solve(char[][] board) {
method dfs (line 41) | private void dfs(char[][] board, int i, int j) {
method main (line 65) | public static void main(String args[]){
FILE: src/com/interview/graph/FloodFillAlgorithm.java
class FloodFillAlgorithm (line 7) | public class FloodFillAlgorithm {
method fillDFS (line 9) | public void fillDFS(int screen[][], int oldColor, int newColor,int sta...
method fillUtil (line 13) | public void fillUtil(int screen[][], int currentx,int currenty, int ol...
method main (line 28) | public static void main(String args[]){
FILE: src/com/interview/graph/FloydWarshallAllPairShortestPath.java
class FloydWarshallAllPairShortestPath (line 20) | public class FloydWarshallAllPairShortestPath {
class NegativeWeightCycleException (line 22) | class NegativeWeightCycleException extends RuntimeException {
method allPairShortestPath (line 28) | public int[][] allPairShortestPath(int[][] distanceMatrix) {
method printPath (line 71) | public void printPath(int[][] path, int start, int end) {
method main (line 97) | public static void main(String args[]){
FILE: src/com/interview/graph/FordFulkerson.java
class FordFulkerson (line 22) | public class FordFulkerson {
method maxFlow (line 24) | public int maxFlow(int capacity[][], int source, int sink){
method printAugmentedPaths (line 82) | private void printAugmentedPaths(List<List<Integer>> augmentedPaths) {
method BFS (line 93) | private boolean BFS(int[][] residualCapacity, Map<Integer,Integer> par...
method main (line 125) | public static void main(String args[]){
FILE: src/com/interview/graph/Graph.java
class Graph (line 9) | public class Graph<T>{
method Graph (line 15) | public Graph(boolean isDirected){
method addEdge (line 21) | public void addEdge(long id1, long id2){
method addVertex (line 27) | public void addVertex(Vertex<T> vertex){
method addSingleVertex (line 37) | public Vertex<T> addSingleVertex(long id){
method getVertex (line 46) | public Vertex<T> getVertex(long id){
method addEdge (line 50) | public void addEdge(long id1,long id2, int weight){
method getAllEdges (line 75) | public List<Edge<T>> getAllEdges(){
method getAllVertex (line 79) | public Collection<Vertex<T>> getAllVertex(){
method setDataForVertex (line 82) | public void setDataForVertex(long id, T data){
method toString (line 89) | @Override
class Vertex (line 101) | class Vertex<T> {
method Vertex (line 107) | Vertex(long id){
method getId (line 111) | public long getId(){
method setData (line 115) | public void setData(T data){
method getData (line 119) | public T getData(){
method addAdjacentVertex (line 123) | public void addAdjacentVertex(Edge<T> e, Vertex<T> v){
method toString (line 128) | public String toString(){
method getAdjacentVertexes (line 132) | public List<Vertex<T>> getAdjacentVertexes(){
method getEdges (line 136) | public List<Edge<T>> getEdges(){
method getDegree (line 140) | public int getDegree(){
method hashCode (line 144) | @Override
method equals (line 152) | @Override
class Edge (line 167) | class Edge<T>{
method Edge (line 173) | Edge(Vertex<T> vertex1, Vertex<T> vertex2){
method Edge (line 178) | Edge(Vertex<T> vertex1, Vertex<T> vertex2,boolean isDirected,int weight){
method Edge (line 185) | Edge(Vertex<T> vertex1, Vertex<T> vertex2,boolean isDirected){
method getVertex1 (line 191) | Vertex<T> getVertex1(){
method getVertex2 (line 195) | Vertex<T> getVertex2(){
method getWeight (line 199) | int getWeight(){
method isDirected (line 203) | public boolean isDirected(){
method hashCode (line 207) | @Override
method equals (line 216) | @Override
method toString (line 238) | @Override
FILE: src/com/interview/graph/GraphColoring.java
class GraphColoring (line 16) | public class GraphColoring {
method WelshPowell (line 18) | public void WelshPowell(){
method colorGraph (line 73) | public void colorGraph(){
method getUnusedColor (line 114) | private String getUnusedColor(Map<String,Boolean> colorsUsed){
method resetColor (line 123) | private void resetColor(Map<String,Boolean> colorsUsed){
method assignColor (line 134) | private void assignColor(String color, Map<String,Boolean> colorsUsed){
method allAdjacentUnColored (line 139) | private boolean allAdjacentUnColored(Collection<Vertex<Integer>> verte...
method main (line 147) | public static void main(String args[]){
class ComparatorVertex (line 154) | class ComparatorVertex implements Comparator<Vertex<Integer>>{
method compare (line 156) | @Override
FILE: src/com/interview/graph/GraphTraversal.java
class GraphTraversal (line 12) | public class GraphTraversal {
method DFS (line 14) | public void DFS(Graph<Integer> graph){
method DFSUtil (line 24) | private void DFSUtil(Vertex<Integer> v,Set<Long> visited){
method BFS (line 33) | public void BFS(Graph<Integer> graph){
method main (line 57) | public static void main(String args[]){
FILE: src/com/interview/graph/HamiltonianCycle.java
class HamiltonianCycle (line 8) | public class HamiltonianCycle<T> {
method getHamiltonianCycle (line 10) | public boolean getHamiltonianCycle(Graph<T> graph,List<Vertex<T>> resu...
method hamiltonianUtil (line 18) | private boolean hamiltonianUtil(Vertex<T> startVertex, Vertex<T> curre...
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/graph/KruskalMST.java
class KruskalMST (line 22) | public class KruskalMST {
class EdgeComparator (line 26) | public class EdgeComparator implements Comparator<Edge<Integer>> {
method compare (line 27) | @Override
method getMST (line 37) | public List<Edge<Integer>> getMST(Graph<Integer> graph) {
method main (line 71) | public static void main(String args[]) {
FILE: src/com/interview/graph/MaximumBiparteMatching.java
class MaximumBiparteMatching (line 13) | public class MaximumBiparteMatching {
method findMaxMatching (line 15) | public int findMaxMatching(Map<Integer,List<Integer>> jobApplications,...
method matchJobs (line 26) | private boolean matchJobs(Integer candidate, Map<Integer,List<Integer>...
method main (line 47) | public static void main(String args[]){
FILE: src/com/interview/graph/MinimumHeightTree.java
class MinimumHeightTree (line 16) | public class MinimumHeightTree {
method findMinHeightTrees (line 17) | public List<Integer> findMinHeightTrees(int n, int[][] edges) {
method main (line 53) | public static void main(String args[]) {
FILE: src/com/interview/graph/NumberOfIsland.java
class NumberOfIsland (line 6) | public class NumberOfIsland {
method numberOfIsland (line 8) | public int numberOfIsland(int[][] graph){
method DFS (line 23) | private void DFS(int[][] graph, boolean[][] visited,int i,int j){
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/graph/NumberOfIslandDynamic.java
class NumberOfIslandDynamic (line 13) | public class NumberOfIslandDynamic {
method numIslands2 (line 14) | public List<Integer> numIslands2(int n, int m, int[][] positions) {
method main (line 58) | public static void main(String args[]) {
FILE: src/com/interview/graph/NumberofTriangles.java
class NumberofTriangles (line 13) | public class NumberofTriangles {
method countTriangles (line 15) | public int countTriangles(Graph<Integer> graph){
method DFS (line 24) | public int DFS(Vertex<Integer> vertex, Map<Vertex<Integer>,Boolean> vi...
method isNeighbor (line 44) | private boolean isNeighbor(Vertex<Integer> vertex, Vertex<Integer> des...
method main (line 53) | public static void main(String args[]){
FILE: src/com/interview/graph/PrimMST.java
class PrimMST (line 18) | public class PrimMST {
method primMST (line 23) | public List<Edge<Integer>> primMST(Graph<Integer> graph){
method getVertexForEdge (line 72) | private Vertex<Integer> getVertexForEdge(Vertex<Integer> v, Edge<Integ...
method main (line 76) | public static void main(String args[]){
FILE: src/com/interview/graph/PrintAllPathFromSourceToDestination.java
class PrintAllPathFromSourceToDestination (line 12) | public class PrintAllPathFromSourceToDestination {
method printPath (line 14) | public void printPath(Graph<Integer> graph,Vertex<Integer> start, Vert...
method printPath (line 19) | private void printPath(Set<Vertex<Integer>> visited,Vertex<Integer> de...
method main (line 38) | public static void main(String args[]){
FILE: src/com/interview/graph/ShortestDistanceFromExit.java
type Cell (line 6) | enum Cell{
class Point (line 12) | class Point{
method Point (line 15) | Point(int x, int y){
class ShortestDistanceFromExit (line 36) | public class ShortestDistanceFromExit {
method findShortest (line 38) | public int[][] findShortest(Cell input[][]){
method setDistance (line 59) | private void setDistance(Cell input[][], int x, int y, int distance[][]){
method setDistanceUtil (line 74) | private void setDistanceUtil(Queue<Point> q, Cell input[][], Point p, ...
method getNeighbor (line 84) | private Point getNeighbor(Cell input[][], int x, int y){
method main (line 90) | public static void main(String args[]){
FILE: src/com/interview/graph/StronglyConnectedComponent.java
class StronglyConnectedComponent (line 30) | public class StronglyConnectedComponent {
method scc (line 32) | public List<Set<Vertex<Integer>>> scc(Graph<Integer> graph) {
method reverseGraph (line 65) | private Graph<Integer> reverseGraph(Graph<Integer> graph) {
method DFSUtil (line 74) | private void DFSUtil(Vertex<Integer> vertex,
method DFSUtilForReverseGraph (line 86) | private void DFSUtilForReverseGraph(Vertex<Integer> vertex,
method main (line 98) | public static void main(String args[]){
FILE: src/com/interview/graph/TarjanStronglyConnectedComponent.java
class TarjanStronglyConnectedComponent (line 16) | public class TarjanStronglyConnectedComponent {
method scc (line 26) | public List<Set<Vertex<Integer>>> scc(Graph<Integer> graph) {
method sccUtil (line 59) | private void sccUtil(Vertex<Integer> vertex) {
method main (line 100) | public static void main(String args[]) {
FILE: src/com/interview/graph/TopologicalSort.java
class TopologicalSort (line 19) | public class TopologicalSort<T> {
method topSort (line 24) | public Deque<Vertex<T>> topSort(Graph<T> graph) {
method topSortUtil (line 36) | private void topSortUtil(Vertex<T> vertex, Deque<Vertex<T>> stack,
method main (line 48) | public static void main(String args[]){
FILE: src/com/interview/graph/TransitiveClosure.java
class TransitiveClosure (line 6) | public class TransitiveClosure {
method getTransitiveClosure (line 8) | public boolean[][] getTransitiveClosure(int [][]graph){
method main (line 30) | public static void main(String args[]){
FILE: src/com/interview/graph/TravelingSalesmanHeldKarp.java
class TravelingSalesmanHeldKarp (line 16) | public class TravelingSalesmanHeldKarp {
class Index (line 20) | private static class Index {
method equals (line 24) | @Override
method hashCode (line 35) | @Override
method createIndex (line 42) | private static Index createIndex(int vertex, Set<Integer> vertexSet) {
class SetSizeComparator (line 50) | private static class SetSizeComparator implements Comparator<Set<Integ...
method compare (line 51) | @Override
method minCost (line 57) | public int minCost(int[][] distance) {
method printTour (line 112) | private void printTour(Map<Index, Integer> parent, int totalVertices) {
method getCost (line 133) | private int getCost(Set<Integer> set, int prevVertex, Map<Index, Integ...
method generateCombination (line 141) | private List<Set<Integer>> generateCombination(int n) {
method generateCombination (line 153) | private void generateCombination(int input[], int start, int pos, List...
method createSet (line 165) | private static Set<Integer> createSet(int input[], int pos) {
FILE: src/com/interview/graph/ValidTree.java
class ValidTree (line 13) | public class ValidTree {
method validTree (line 14) | public boolean validTree(int n, int[][] edges) {
method isCycle (line 49) | boolean isCycle(int vertex, Map<Integer, List<Integer>> graph, int par...
FILE: src/com/interview/graph/WallsAndGates.java
class WallsAndGates (line 20) | public class WallsAndGates {
method wallsAndGates (line 24) | public void wallsAndGates(int[][] rooms) {
method addNeighbors (line 35) | private void addNeighbors(int[][] rooms, int row, int col, Deque<Cell...
method gates (line 47) | private void gates(int[][] rooms, Deque<Cell> queue) {
class Cell (line 57) | class Cell {
method Cell (line 61) | Cell(int row, int col) {
FILE: src/com/interview/graph/WordLadder.java
class WordLadder (line 18) | public class WordLadder {
method findLadders (line 19) | public List<List<String>> findLadders(String beginWord, String endWord...
method setParent (line 78) | private void setParent(Map<String, List<String>> parent, String startW...
method main (line 92) | public static void main(String args[]) {
FILE: src/com/interview/linklist/AddNumberRepresentedByLinkList.java
class AddNumberRepresentedByLinkList (line 11) | public class AddNumberRepresentedByLinkList {
method addWithCarry (line 15) | private Node addWithCarry(Node head1, Node head2){
method addRemaining (line 27) | private Node addRemaining(Node start, Node stop){
method add (line 39) | public Node add(Node head1, Node head2){
method main (line 78) | public static void main(String args[]){
FILE: src/com/interview/linklist/CopyLinkListWIthArbitPointer.java
class CopyLinkListWIthArbitPointer (line 15) | public class CopyLinkListWIthArbitPointer {
class RandomListNode (line 17) | static class RandomListNode {
method RandomListNode (line 20) | RandomListNode(int x) { this.label = x; }
method copyRandomList (line 23) | public RandomListNode copyRandomList(RandomListNode head) {
method main (line 59) | public static void main(String args[]){
FILE: src/com/interview/linklist/DeleteDuplicateNodes.java
class DeleteDuplicateNodes (line 16) | public class DeleteDuplicateNodes {
method deleteDuplicates (line 17) | public Node deleteDuplicates(Node head) {
FILE: src/com/interview/linklist/DeleteNAfterMNodes.java
class DeleteNAfterMNodes (line 13) | public class DeleteNAfterMNodes {
method deleteNAfterMNodes (line 15) | public void deleteNAfterMNodes(Node head,int m, int n){
method main (line 38) | public static void main(String args[]){
FILE: src/com/interview/linklist/DeleteNodeWithGreaterValueOnRight.java
class DeleteNodeWithGreaterValueOnRight (line 10) | public class DeleteNodeWithGreaterValueOnRight {
method deleteNodes (line 14) | public Node deleteNodes(Node head){
method main (line 29) | public static void main(String args[]){
FILE: src/com/interview/linklist/DoubleLinkList.java
class DoubleLinkList (line 3) | public class DoubleLinkList {
method addNode (line 5) | public Node addNode(Node head,int data){
method addAtFront (line 20) | public Node addAtFront(Node head, int data){
method print (line 30) | public void print(Node head){
method printFrontBack (line 38) | public void printFrontBack(Node head){
method find (line 52) | public Node find(Node head, int data){
method main (line 62) | public static void main(String args[]){
FILE: src/com/interview/linklist/Flatten2DList.java
class Flatten2DList (line 15) | public class Flatten2DList implements Iterator<Integer> {
method Flatten2DList (line 19) | public Flatten2DList(List<List<Integer>> vec2d) {
method next (line 23) | @Override
method hasNext (line 37) | @Override
FILE: src/com/interview/linklist/FlattenLinkList.java
class FlattenLinkList (line 11) | public class FlattenLinkList {
method flatten (line 13) | public void flatten(Node head) {
method getTail (line 25) | private Node getTail(Node head) {
method main (line 35) | public static void main(String args[]) {
FILE: src/com/interview/linklist/InsertionSortLinkList.java
class InsertionSortLinkList (line 13) | public class InsertionSortLinkList {
method insert (line 15) | private Node insert(Node head,Node curr){
method sort (line 35) | public Node sort(Node head){
method main (line 48) | public static void main(String args[]){
FILE: src/com/interview/linklist/LRUCache.java
class LRUCache (line 15) | public class LRUCache {
method LRUCache (line 22) | public LRUCache(int size){
method used (line 26) | public void used(int data){
method addIntoCache (line 41) | public void addIntoCache(int data){
method printCache (line 65) | public void printCache(){
method containsInCache (line 74) | public boolean containsInCache(int data)
method deleteFromCache (line 79) | public void deleteFromCache(int data){
method main (line 106) | public static void main(String args[]){
FILE: src/com/interview/linklist/LRUCacheLeetCode.java
class LRUCacheLeetCode (line 13) | public class LRUCacheLeetCode {
method LRUCacheLeetCode (line 17) | public LRUCacheLeetCode(int capacity) {
method get (line 22) | public int get(int key) {
method set (line 27) | public void set(int key, int value) {
class MyMap (line 31) | class MyMap extends LinkedHashMap<Integer, Integer> {
method MyMap (line 33) | MyMap(int capacity) {
method removeEldestEntry (line 37) | @Override
FILE: src/com/interview/linklist/LinkList.java
class NodeRef (line 3) | class NodeRef{
method next (line 5) | public void next(){
class Node (line 10) | class Node{
method newNode (line 17) | public static Node newNode(int data, Object... obj){
class LinkList (line 30) | public class LinkList {
method addNode (line 32) | public Node addNode(int data, Node head, Object... obj){
method addAtFront (line 52) | public Node addAtFront(Node node, Node head){
method reverse (line 60) | public Node reverse(Node head){
method reverseRecursiveEasy (line 73) | public Node reverseRecursiveEasy(Node head){
method reverseRecursive (line 84) | public void reverseRecursive(NodeRef headRef){
method addAtFront (line 101) | public Node addAtFront(int data, Node head){
method printList (line 106) | public void printList(Node head){
method find (line 113) | public Node find(Node head, int data){
method size (line 124) | public int size(Node head){
method main (line 132) | public static void main(String args[]){
FILE: src/com/interview/linklist/LinkListIsPalindrome.java
class LinkListIsPalindrome (line 12) | public class LinkListIsPalindrome {
method isPalindrome (line 14) | public boolean isPalindrome(NodeRef head,Node end){
method main (line 24) | public static void main(String args[]){
FILE: src/com/interview/linklist/LinkListToCompleteBinaryTree.java
class LinkListToCompleteBinaryTree (line 11) | public class LinkListToCompleteBinaryTree {
method convert (line 13) | public void convert(Node head){
method inorder (line 39) | public void inorder(Node head){
method main (line 48) | public static void main(String args[]){
FILE: src/com/interview/linklist/LoopInLinkList.java
class LoopInLinkList (line 14) | public class LoopInLinkList {
method hasCycle (line 16) | public boolean hasCycle(Node head){
method main (line 36) | public static void main(String args[]){
FILE: src/com/interview/linklist/MergeForLargestSum.java
class MergeForLargestSum (line 11) | public class MergeForLargestSum {
method maxChain (line 13) | Node maxChain(Node head1, Node head2){
method main (line 87) | public static void main(String args[]){
FILE: src/com/interview/linklist/MergeSortLinkList.java
class MergeSortLinkList (line 13) | public class MergeSortLinkList {
method sort (line 15) | public Node sort(Node head, boolean isAscending){
method sortedMerge (line 26) | private Node sortedMerge(Node head1, Node head2, boolean isAscending){
method frontBackSplit (line 52) | private Node frontBackSplit(Node head){
method main (line 67) | public static void main(String args[]){
FILE: src/com/interview/linklist/MiddleElementOfLinkList.java
class MiddleElementOfLinkList (line 11) | public class MiddleElementOfLinkList {
method middle (line 13) | public int middle(Node head){
method main (line 27) | public static void main(String args[]){
FILE: src/com/interview/linklist/MultiplyTwoNumbersLinkList.java
class MultiplyTwoNumbersLinkList (line 9) | public class MultiplyTwoNumbersLinkList {
method multiply (line 11) | public Node multiply(Node head1, Node head2){
method add (line 58) | private Node add(Node result, Node currentResult){
method main (line 124) | public static void main(String args[]){
FILE: src/com/interview/linklist/QuickSortSingleLinkList.java
class HeadTail (line 13) | class HeadTail{
class QuickSortSingleLinkList (line 18) | public class QuickSortSingleLinkList {
method quickSort (line 20) | public Node quickSort(Node head){
method quickSortFaster (line 61) | public Node quickSortFaster(Node head){
method quickSortUtil (line 71) | private HeadTail quickSortUtil(Node head){
method main (line 113) | public static void main(String args[]){
FILE: src/com/interview/linklist/RemoveDuplicatesSortedList.java
class RemoveDuplicatesSortedList (line 12) | public class RemoveDuplicatesSortedList {
method removeDuplicates (line 14) | public void removeDuplicates(Node head){
method main (line 28) | public static void main(String args[]){
FILE: src/com/interview/linklist/RemoveMiddleElementsOfLineSegment.java
class Point (line 13) | class Point{
method Point (line 16) | Point(int x, int y){
class RemoveMiddleElementsOfLineSegment (line 22) | public class RemoveMiddleElementsOfLineSegment {
method remove (line 24) | public void remove(Node head){
method main (line 48) | public static void main(String args[]){
FILE: src/com/interview/linklist/ReorderList.java
class ReorderList (line 9) | public class ReorderList {
method reorderList (line 11) | public void reorderList(Node head) {
method alternateMerge (line 18) | private Node alternateMerge(Node head1, Node head2) {
method reverse (line 33) | private Node reverse(Node head) {
method frontBackSplit (line 49) | private Node frontBackSplit(Node head) {
FILE: src/com/interview/linklist/ReverseAlternateKNodes.java
class ReverseAlternateKNodes (line 10) | public class ReverseAlternateKNodes {
method reverse (line 12) | public Node reverse(Node head,int k,boolean reverse){
method main (line 48) | public static void main(String args[]){
FILE: src/com/interview/linklist/ReverseAlternateNodeAndAppendAtEnd.java
class ReverseAlternateNodeAndAppendAtEnd (line 8) | public class ReverseAlternateNodeAndAppendAtEnd {
method act (line 10) | public void act(Node head){
method main (line 27) | public static void main(String args[]){
FILE: src/com/interview/linklist/ReverseKNodes.java
class ReverseKNodes (line 9) | public class ReverseKNodes {
method reverse (line 11) | public Node reverse(Node head,int k){
method main (line 31) | public static void main(String args[]){
FILE: src/com/interview/linklist/RotateList.java
class RotateList (line 12) | public class RotateList {
method rotateRight (line 13) | public Node rotateRight(Node head, int k) {
FILE: src/com/interview/linklist/ShuffleMerge.java
class ShuffleMerge (line 18) | public class ShuffleMerge {
method shuffleMergeRecursive (line 20) | public Node shuffleMergeRecursive(Node head1, Node head2){
method shuffleMerge (line 39) | public Node shuffleMerge(Node head1, Node head2){
method main (line 62) | public static void main(String args[]){
FILE: src/com/interview/linklist/SortNearlySortedList.java
class SortNearlySortedList (line 15) | public class SortNearlySortedList {
method sort (line 17) | public Node sort(Node head){
method mergeSort (line 35) | private Node mergeSort(Node head1,Node head2){
method main (line 51) | public static void main(String args[]){
FILE: src/com/interview/linklist/SortedCircularLinkList.java
class SortedCircularLinkList (line 12) | public class SortedCircularLinkList {
method add (line 14) | public Node add(Node head,int data){
method getTail (line 44) | private Node getTail(Node head){
method printList (line 52) | public void printList(Node head){
method main (line 64) | public static void main(String args[]){
FILE: src/com/interview/linklist/SortedLLToBalancedBST.java
class SortedLLToBalancedBST (line 9) | public class SortedLLToBalancedBST {
method toBalancedBST (line 11) | public Node toBalancedBST(Node head){
method toBalancedBST (line 19) | private Node toBalancedBST(NodeRef headRef, int size){
method printTreeInOrder (line 32) | public void printTreeInOrder(Node head){
method printTreePreOrder (line 41) | public void printTreePreOrder(Node head){
method main (line 50) | public static void main(String args[]){
FILE: src/com/interview/linklist/StackWithLinkListMiddleOperation.java
class StackWithLinkListMiddleOperation (line 10) | public class StackWithLinkListMiddleOperation {
method push (line 15) | public void push(int data){
method hasMore (line 32) | public boolean hasMore(){
method size (line 40) | public int size(){
method pop (line 44) | public int pop(){
method top (line 57) | public int top(){
method middle (line 63) | public int middle(){
method deleteMiddle (line 69) | public int deleteMiddle(){
method main (line 106) | public static void main(String args[]){
FILE: src/com/interview/linklist/SwapTwoNodesInDoubleLL.java
class SwapTwoNodesInDoubleLL (line 11) | public class SwapTwoNodesInDoubleLL {
method swap (line 13) | public void swap(Node nodeA, Node nodeB){
method main (line 73) | public static void main(String args[]){
FILE: src/com/interview/linklist/TripletToSumInLinkList.java
class TripletToSumInLinkList (line 12) | public class TripletToSumInLinkList {
method printTriplet (line 14) | public void printTriplet(Node head1, Node head2, Node head3,int sum){
method main (line 42) | public static void main(String args[]){
FILE: src/com/interview/misc/AddingTwoSetOfIntervals.java
class AddingTwoSetOfIntervals (line 7) | public class AddingTwoSetOfIntervals {
class Pair (line 9) | public static class Pair implements Comparable<Pair>{
method Pair (line 12) | Pair(int low,int high){
method compareTo (line 16) | @Override
method toString (line 25) | public String toString(){
method combineInterval (line 30) | public List<Pair> combineInterval(Pair[] arr1, Pair[] arr2){
method main (line 80) | public static void main(String args[]){
FILE: src/com/interview/misc/AngleBetweenHourAndMinuteHand.java
class AngleBetweenHourAndMinuteHand (line 6) | public class AngleBetweenHourAndMinuteHand {
method angle (line 8) | public double angle(int hour, int min){
method main (line 16) | public static void main(String args[]){
FILE: src/com/interview/misc/BulbSwitcher.java
class BulbSwitcher (line 11) | public class BulbSwitcher {
method bulbSwitch (line 12) | public int bulbSwitch(int n) {
FILE: src/com/interview/misc/CandiesProblem.java
class CandiesProblem (line 23) | public class CandiesProblem {
method minCandies (line 25) | public int minCandies(int ratings[]) {
method main (line 77) | public static void main(String args[]) {
FILE: src/com/interview/misc/ContainsNumberWithinKDistance.java
class ContainsNumberWithinKDistance (line 23) | public class ContainsNumberWithinKDistance {
method containsNearbyAlmostDuplicate (line 25) | public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
FILE: src/com/interview/misc/ConvertNumberIntoBase26.java
class ConvertNumberIntoBase26 (line 7) | public class ConvertNumberIntoBase26 {
method numberToBase26 (line 9) | public String numberToBase26(int n) {
method base26ToNumber (line 19) | public int base26ToNumber(String str) {
method main (line 31) | public static void main(String args[]) {
FILE: src/com/interview/misc/CountRanges.java
class CountRanges (line 21) | public class CountRanges {
method countRangeSum (line 23) | public int countRangeSum(int[] nums, int lower, int upper) {
method main (line 49) | public static void main(String args[]) {
FILE: src/com/interview/misc/DayDifferenceBetweenTwoDates.java
class DayDifferenceBetweenTwoDates (line 8) | public class DayDifferenceBetweenTwoDates {
method diff (line 12) | public int diff(int year1,int month1, int day1,int year2, int month2,i...
method main (line 38) | public static void main(String args[]){
method isLeapYear (line 43) | public boolean isLeapYear(int year){
FILE: src/com/interview/misc/DifferenceBetweenTwoTime.java
class DifferenceBetweenTwoTime (line 10) | public class DifferenceBetweenTwoTime {
method diff (line 12) | public int diff(int time1, int time2){
method main (line 26) | public static void main(String args[]){
FILE: src/com/interview/misc/FindingCelebrity.java
class Relation (line 7) | class Relation {
method knows (line 8) | boolean knows(int a, int b) {
class FindingCelebrity (line 13) | public class FindingCelebrity extends Relation {
method findCelebrity (line 15) | public int findCelebrity(int n) {
FILE: src/com/interview/misc/FloatPointConversion.java
class FloatPointConversion (line 11) | public class FloatPointConversion {
method convert (line 13) | public double convert(String input){
method toDouble (line 29) | private double toDouble(String number){
method main (line 55) | public static void main(String args[]){
FILE: src/com/interview/misc/FourPointsFormSquare.java
class Cordinate (line 3) | class Cordinate{
class FourPointsFormSquare (line 14) | public class FourPointsFormSquare {
method isSquare (line 16) | public boolean isSquare(Cordinate[] cordinates){
method compare (line 34) | private boolean compare(Cordinate startPoint, Cordinate point1, Cordin...
method distanceSquare (line 46) | private int distanceSquare(Cordinate c1, Cordinate c2){
method main (line 51) | public static void main(String args[]){
FILE: src/com/interview/misc/GetKthPermutation.java
class GetKthPermutation (line 9) | public class GetKthPermutation {
method getPermutation (line 11) | public String getPermutation(int n, int k) {
method factorial (line 42) | private int factorial(int n) {
method main (line 50) | public static void main(String args[]) {
FILE: src/com/interview/misc/HammingDistanceBetweenPair.java
class HammingDistanceBetweenPair (line 9) | public class HammingDistanceBetweenPair {
method hammingDistance (line 11) | public int hammingDistance(String input[]){
method main (line 29) | public static void main(String args[]){
FILE: src/com/interview/misc/InsertInterval.java
class InsertInterval (line 18) | public class InsertInterval {
class Interval (line 20) | public static class Interval {
method toString (line 24) | @Override
method Interval (line 32) | Interval(int s, int e) { start = s; end = e; }
method insert (line 35) | public List<Interval> insert(List<Interval> intervals, Interval newInt...
method main (line 62) | public static void main(String args[]) {
FILE: src/com/interview/misc/IntegerListParser.java
class IntegerListParser (line 16) | public class IntegerListParser {
method deserialize (line 18) | public NestedInteger deserialize(String s) {
method serialize (line 55) | public String serialize(NestedInteger nestedInteger) {
method serialize (line 61) | private void serialize(NestedInteger nestedInteger, StringBuffer resul...
method main (line 82) | public static void main(String args[]) {
class NestedInteger (line 113) | class NestedInteger {
method NestedInteger (line 116) | public NestedInteger() {
method NestedInteger (line 120) | public NestedInteger(int value) {
method isInteger (line 124) | public boolean isInteger() {
method getInteger (line 128) | public Integer getInteger() {
method setInteger (line 132) | public void setInteger(int value) {
method add (line 136) | public void add(NestedInteger ni) {
method getList (line 140) | public List<NestedInteger> getList() {
FILE: src/com/interview/misc/KthLargestInRowiseColumnWiseSorted2DArray.java
class KthLargestInRowiseColumnWiseSorted2DArray (line 9) | public class KthLargestInRowiseColumnWiseSorted2DArray {
method kthLargest (line 11) | public int kthLargest(int input[][],int k){
method main (line 42) | public static void main(String args[]){
FILE: src/com/interview/misc/LoadBalancers.java
class LoadBalancers (line 8) | public class LoadBalancers {
method addServer (line 13) | public void addServer(String name){
method removeServer (line 18) | public void removeServer(String name){
method getRandom (line 27) | public String getRandom(){
method main (line 32) | public static void main(String args[]){
FILE: src/com/interview/misc/NestedIterator.java
class NestedIterator (line 21) | public class NestedIterator implements Iterator<Integer> {
method NestedIterator (line 24) | public NestedIterator(List<NestedInteger> nestedList) {
method next (line 28) | @Override
method hasNext (line 38) | @Override
type NestedInteger (line 64) | interface NestedInteger {
method isInteger (line 65) | boolean isInteger();
method getInteger (line 66) | Integer getInteger();
method getList (line 67) | List<NestedInteger> getList();
FILE: src/com/interview/misc/NumberToWord.java
class NumberToWord (line 9) | public class NumberToWord {
method numberToWords (line 15) | public String numberToWords(int number){
method hundredsPart (line 43) | private String hundredsPart(int number){
method tenthPart (line 62) | private String tenthPart(int number){
method toString (line 81) | private String toString(int number){
method main (line 153) | public static void main(String args[]){
FILE: src/com/interview/misc/PrimeNumbersBeforeN.java
class PrimeNumbersBeforeN (line 9) | public class PrimeNumbersBeforeN {
method primeNumbers (line 11) | public List<Integer> primeNumbers(int n){
method main (line 33) | public static void main(String args[]){
FILE: src/com/interview/misc/Read4Function.java
class Read4 (line 16) | class Read4 {
method read4 (line 17) | int read4(char[] buff) {
class Read4Function (line 26) | public class Read4Function extends Read4{
class Queue (line 28) | class Queue {
method Queue (line 34) | Queue(int size) {
method isEmpty (line 39) | boolean isEmpty() {
method offer (line 43) | void offer(char b) {
method poll (line 49) | char poll() {
method Read4Function (line 58) | public Read4Function() {
method read (line 62) | public int read(char[] buf, int n) {
method main (line 89) | public static void main(String args[]) {
FILE: src/com/interview/misc/RomanNumberToDecimal.java
class RomanNumberToDecimal (line 11) | public class RomanNumberToDecimal {
method converToRoman (line 13) | public String converToRoman(int decimal){
method convertToDecimal (line 21) | public int convertToDecimal(char[] roman){
method literal (line 35) | private int literal(int decimal,StringBuffer buffer){
method literal (line 100) | private int literal(char ch){
method main (line 121) | public static void main(String args[]){
FILE: src/com/interview/misc/SparseTableRangeMinimumQuery.java
class SparseTableRangeMinimumQuery (line 16) | public class SparseTableRangeMinimumQuery {
method SparseTableRangeMinimumQuery (line 22) | public SparseTableRangeMinimumQuery(int[] input) {
method preprocess (line 28) | private int[][] preprocess(int[] input, int n) {
method rangeMinimumQuery (line 46) | public int rangeMinimumQuery(int low, int high) {
method log2 (line 56) | private static int log2(int n){
method main (line 61) | public static void main(String args[]) {
FILE: src/com/interview/multiarray/Fill2DMatrixWith1.java
class Fill2DMatrixWith1 (line 6) | public class Fill2DMatrixWith1 {
method fill (line 8) | public void fill(int input[][]){
method main (line 28) | public static void main(String args[]){
FILE: src/com/interview/multiarray/GameOfLife.java
class GameOfLife (line 18) | public class GameOfLife {
method gameOfLife (line 19) | public void gameOfLife(int[][] board) {
method copyRow (line 42) | private void copyRow(int[] source, int[] dest) {
method doesLive (line 48) | private boolean doesLive(int x, int y, int[][] board) {
FILE: src/com/interview/multiarray/LongestConsecutiveIntegerInUnsorted2DArray.java
class LongestConsecutiveIntegerInUnsorted2DArray (line 6) | public class LongestConsecutiveIntegerInUnsorted2DArray {
method longestConsecutiveInteger (line 8) | public int longestConsecutiveInteger(int input[][]){
method DFS (line 23) | private int DFS(int input[][],int i,int j,boolean visited[][],int last...
method main (line 43) | public static void main(String args[]){
FILE: src/com/interview/multiarray/MatrixCalculation.java
class MatrixCalculation (line 3) | public class MatrixCalculation {
method crossMultiply (line 7) | public String[][] crossMultiply(String[][] str){
method recur (line 25) | private void recur(StringBuffer buffer,String[][] result,String[][] st...
method main (line 40) | public static void main(String args[]){
FILE: src/com/interview/multiarray/MatrixFindAllSubSquareRectangleMatrix.java
class MatrixFindAllSubSquareRectangleMatrix (line 6) | public class MatrixFindAllSubSquareRectangleMatrix {
method printSumOfAllSquareMatrix (line 8) | public void printSumOfAllSquareMatrix(int input[][]){
method printSumOfAllRectangleMatrix (line 25) | public void printSumOfAllRectangleMatrix(int input[][]){
method main (line 42) | public static void main(String args[]){
FILE: src/com/interview/multiarray/MatrixInDiagonalOrder.java
class MatrixInDiagonalOrder (line 6) | public class MatrixInDiagonalOrder {
method printMatrix (line 8) | public void printMatrix(int [][]matrix){
method main (line 32) | public static void main(String args[]){
FILE: src/com/interview/multiarray/MatrixOf0sAnd1s.java
class MatrixOf0sAnd1s (line 7) | public class MatrixOf0sAnd1s {
method create (line 9) | public char[][] create(int n,int m){
method main (line 47) | public static void main(String args[]){
FILE: src/com/interview/multiarray/MoveCellPerCellValue.java
class Cell (line 8) | class Cell{
method Cell (line 11) | Cell(int x,int y){
class MoveCellPerCellValue (line 17) | public class MoveCellPerCellValue {
method isAllCellTraversed (line 19) | public boolean isAllCellTraversed(Cell grid[][]){
method main (line 44) | public static void main(String args[]){
FILE: src/com/interview/multiarray/Mutable2DSumRangeQuery.java
class Mutable2DSumRangeQuery (line 10) | public class Mutable2DSumRangeQuery {
method Mutable2DSumRangeQuery (line 16) | public Mutable2DSumRangeQuery(int[][] matrix) {
method update (line 32) | public void update(int row, int col, int val) {
method sumRegion (line 40) | public int sumRegion(int row1, int col1, int row2, int col2) {
FILE: src/com/interview/multiarray/RotateImage.java
class RotateImage (line 12) | public class RotateImage {
method rotate (line 14) | public void rotate(int[][] matrix) {
method print (line 29) | private void print(int arr[][]){
method main (line 38) | public static void main(String args[]){
FILE: src/com/interview/multiarray/ShortestDistanceFromAllBuildings.java
class ShortestDistanceFromAllBuildings (line 18) | public class ShortestDistanceFromAllBuildings {
class Point (line 19) | private class Point {
method Point (line 21) | Point(int row, int col, int dist) {
method shortestDistance (line 28) | public int shortestDistance(int[][] grid) {
method getNeighbors (line 64) | private List<Point> getNeighbors(Point p, int[][] grid, boolean[][] vi...
method main (line 78) | public static void main(String args[]) {
FILE: src/com/interview/multiarray/SmallestRectangleBlackPixel.java
class SmallestRectangleBlackPixel (line 10) | public class SmallestRectangleBlackPixel {
method minArea (line 11) | public int minArea(char[][] image, int x, int y) {
method searchColumns (line 25) | private int searchColumns(char[][] image, int i, int j, int top, int b...
method searchRows (line 45) | private int searchRows(char[][] image, int i, int j, int left, int rig...
method main (line 65) | public static void main(String args[]) {
FILE: src/com/interview/multiarray/SpiralGeneration.java
class SpiralGeneration (line 11) | public class SpiralGeneration {
method generateMatrix (line 12) | public int[][] generateMatrix(int n) {
method main (line 43) | public static void main(String args[]) {
FILE: src/com/interview/multiarray/SpiralPrinting.java
class SpiralPrinting (line 27) | public class SpiralPrinting {
method spiralOrder (line 29) | public List<Integer> spiralOrder(int[][] matrix) {
method main (line 68) | public static void main(String args[]){
FILE: src/com/interview/multiarray/TilingProblem.java
class Position (line 11) | class Position{
method Position (line 14) | Position(int x, int y){
method hashCode (line 18) | @Override
method equals (line 26) | @Override
class TilingProblem (line 44) | public class TilingProblem {
method fit (line 47) | public char[][] fit(int size, Position missingPosition){
method fit (line 54) | private void fit(char matrix[][], Position topLeft,
method determineQuadrant (line 74) | private Position determineQuadrant(Position topLeft, int size, Positio...
method updateMatrix (line 86) | private void updateMatrix(char matrix[][], Position topLeft, Position ...
method main (line 98) | public static void main(String args[]){
FILE: src/com/interview/multithreaded/BoundedBlockingQueue.java
class BoundedBlockingQueue (line 21) | public class BoundedBlockingQueue<T> {
method BoundedBlockingQueue (line 35) | public BoundedBlockingQueue(int size){
method poll (line 46) | public Optional<T> poll(long timeout, TimeUnit timeUnit) throws Interr...
method offer (line 81) | public boolean offer(T t, long timeout, TimeUnit timeUnit) throws Inte...
method enqueue (line 109) | private void enqueue(T t){
method dequeue (line 117) | @SuppressWarnings("unchecked")
method main (line 128) | public static void main(String args[]) throws Exception{
method verifyQueueWorks (line 132) | public static void verifyQueueWorks() throws Exception{
FILE: src/com/interview/multithreaded/CountingWord.java
class CountingWord (line 29) | public class CountingWord {
method addWord (line 33) | public void addWord(String word){
method getCount (line 46) | public long getCount(String word){
method main (line 54) | public static void main(String args[]) throws InterruptedException{
FILE: src/com/interview/multithreaded/DependencyTaskExecutor.java
class DependencyTaskExecutor (line 19) | public class DependencyTaskExecutor {
method scheduleTask (line 22) | void scheduleTask(List<Task> tasks, int threads) {
method scheduleTaskUtil (line 31) | CompletableFuture<Void> scheduleTaskUtil(Task task, Executor executor) {
method main (line 50) | public static void main(String args[]) {
type Task (line 71) | interface Task {
method name (line 72) | String name();
method dependencies (line 73) | List<Task> dependencies();
method execute (line 74) | void execute();
class SimpleSleepTask (line 77) | class SimpleSleepTask implements Task {
method SimpleSleepTask (line 81) | SimpleSleepTask(String name, int sleepTimeInMillis) {
method addDependency (line 86) | void addDependency(Task task) {
method name (line 90) | @Override
method dependencies (line 95) | @Override
method execute (line 100) | @Override
class FutureTask (line 112) | class FutureTask implements Runnable {
method FutureTask (line 117) | FutureTask(Task task, Executor executor) {
method run (line 121) | @Override
method supplyAsync (line 129) | void supplyAsync(FutureTask task, Executor executor) {
method addChain (line 133) | void addChain(FutureTask task) {
FILE: src/com/interview/multithreaded/FillupMatrix.java
class FillupMatrix (line 27) | public class FillupMatrix {
method FillupMatrix (line 32) | public FillupMatrix(int size){
method updateMatrix (line 38) | public void updateMatrix(){
method updateMatrix (line 43) | private void updateMatrix(long pos){
method next (line 50) | private long next(){
method getVal (line 55) | public boolean getVal(int x, int y){
method main (line 59) | public static void main(String args[]) throws InterruptedException{
FILE: src/com/interview/multithreaded/MinMaxKeeper.java
class MinMaxKeeper (line 24) | public class MinMaxKeeper {
method updateMinMax (line 33) | public void updateMinMax(int value){
method getMin (line 62) | public int getMin(){
method getMax (line 66) | public int getMax(){
method main (line 70) | public static void main(String args[]) throws InterruptedException{
class GenerateRand (line 86) | static class GenerateRand implements Runnable{
method GenerateRand (line 89) | public GenerateRand(MinMaxKeeper mmKeeper, int index) {
method run (line 93) | @Override
FILE: src/com/interview/multithreaded/PrintInSequence.java
class PrintInSequence (line 10) | public class PrintInSequence {
method increment (line 16) | public void increment() {
method decrement (line 28) | public void decrement() {
method printVar (line 41) | public void printVar() {
method main (line 48) | public static void main(String args[]) {
method runIncrement (line 62) | private void runIncrement() {
method runPrint (line 68) | private void runPrint() {
method runDecrement (line 74) | private void runDecrement() {
FILE: src/com/interview/multithreaded/RealTimeCounter.java
class RealTimeCounter (line 28) | public class RealTimeCounter {
method RealTimeCounter (line 34) | private RealTimeCounter(){
method getInstance (line 41) | public static RealTimeCounter getInstance(){
method getTotalEvents (line 52) | public long getTotalEvents(){
method addEvent (line 60) | public void addEvent(){
method incrementPosition (line 64) | void incrementPosition(){
method main (line 70) | public static void main(String args[]){
class PositionUpdater (line 98) | class PositionUpdater extends TimerTask{
method PositionUpdater (line 103) | PositionUpdater(RealTimeCounter realTimeCounter) {
method start (line 107) | public void start(){
method run (line 110) | @Override
FILE: src/com/interview/multithreaded/SingleQueueDomainTableUpdate.java
class Data (line 16) | class Data{
method getUpdate (line 19) | public String getUpdate() {
method getDomain (line 22) | public String getDomain() {
type DomainLock (line 27) | interface DomainLock{
method acquireLock (line 28) | boolean acquireLock(String domain);
method releaseLock (line 29) | boolean releaseLock(String domain);
method isLocked (line 30) | boolean isLocked(String domain);
class ThreadPoolManager (line 33) | class ThreadPoolManager{
method ThreadPoolManager (line 35) | public ThreadPoolManager(int numOfThreads){
type DatabaseLayer (line 40) | interface DatabaseLayer{
method applyUpdates (line 41) | public void applyUpdates(String domain,String update);
class ThreadWorker (line 44) | class ThreadWorker implements Runnable{
method ThreadWorker (line 50) | public ThreadWorker(QueueManager mgr){
method run (line 53) | @Override
type QueueHandle (line 87) | interface QueueHandle{
method getNextData (line 89) | public Data getNextData();
class Pair (line 92) | class Pair{
class QueueManager (line 97) | class QueueManager{
method QueueManager (line 99) | public QueueManager(QueueHandle queueHandle){
method getDataFromFrontOfQueue (line 103) | public synchronized Pair getDataFromFrontOfQueue(DomainLock domainLock){
class SingleQueueDomainTableUpdate (line 117) | public class SingleQueueDomainTableUpdate {
FILE: src/com/interview/multithreaded/SpinLockMutex.java
class Mutex (line 6) | class Mutex {
method ice (line 18) | private synchronized int ice(int oldValue, int newValue) {
method acquireLock (line 27) | void acquireLock() {
method releaseLock (line 31) | void releaseLock() {
class SpinLockMutex (line 37) | public class SpinLockMutex {
method changeBuffer (line 42) | public void changeBuffer(String str) {
method getBuffer (line 46) | public String getBuffer() {
method main (line 50) | public static void main(String args[]) throws Exception{
FILE: src/com/interview/multithreaded/ThreadPoolExample.java
class ThreadPoolExample (line 14) | public class ThreadPoolExample {
method doWork (line 18) | public void doWork() throws Exception{
method main (line 30) | public static void main(String args[]) throws Exception{
class Count10 (line 37) | class Count10 implements Callable<String>{
method Count10 (line 40) | Count10(int i){
method call (line 43) | @Override
FILE: src/com/interview/multithreaded/ThreadPoolImpl.java
class ThreadPool (line 6) | class ThreadPool {
method run (line 8) | public Thread run(Runnable runnable) {
class ThreadPoolImpl (line 22) | public class ThreadPoolImpl {
method ThreadPoolImpl (line 27) | public ThreadPoolImpl(int size, ThreadPool threadPool) {
method setMax (line 32) | public void setMax(int size){
method run (line 47) | public void run(Runnable thread) {
method execute (line 54) | private void execute() {
class ExecutingRunnable (line 62) | class ExecutingRunnable implements Runnable {
method run (line 63) | @Override
class RunnableThreads (line 98) | class RunnableThreads implements Runnable {
method RunnableThreads (line 101) | RunnableThreads(Runnable r) {
method run (line 105) | @Override
method main (line 112) | public static void main(String args[]) throws InterruptedException{
class MyRunnable (line 131) | class MyRunnable implements Runnable{
method MyRunnable (line 133) | MyRunnable(int index){
method run (line 136) | @Override
FILE: src/com/interview/number/AggregateNumber.java
class AggregateNumber (line 7) | public class AggregateNumber {
method isAggregate (line 10) | public boolean isAggregate(int[] number){
method getNumber (line 45) | private int getNumber(int[] number, int start, int end){
method main (line 54) | public static void main(String args[]){
FILE: src/com/interview/number/AllStrobogrammaticNumber.java
class AllStrobogrammaticNumber (line 12) | public class AllStrobogrammaticNumber {
method strobogrammaticInRange (line 15) | public int strobogrammaticInRange(String low, String high) {
method strobogrammaticInRangeUtil (line 24) | private int strobogrammaticInRangeUtil(String low, String high, int le...
FILE: src/com/interview/number/ArithemeticProgressionExists.java
class ArithemeticProgressionExists (line 6) | public class ArithemeticProgressionExists {
method exists (line 8) | public boolean exists(int input[]){
method main (line 25) | public static void main(String args[]){
FILE: src/com/interview/number/ArrayMultiplication.java
class ArrayMultiplication (line 5) | public class ArrayMultiplication {
method multiplyDivideAndConquer (line 7) | public int[] multiplyDivideAndConquer(int arr1[],int arr2[],int low1,i...
method shift (line 38) | private int[] shift(int arr[],int n){
method simpleMultiplication (line 47) | public int[] simpleMultiplication(int arr1[],int arr2[],int low1,int h...
method addToResult (line 75) | private void addToResult(int[] result,int temp[],int start){
method multiplicationImproved (line 87) | public int multiplicationImproved(int x, int y, int len){
method power (line 102) | private int power(int n){
method main (line 107) | public static void main(String args[]){
FILE: src/com/interview/number/BasicCalculator.java
class BasicCalculator (line 18) | public class BasicCalculator {
method calculate (line 19) | public int calculate(String s) {
FILE: src/com/interview/number/BinomialCoefficient.java
class BinomialCoefficient (line 10) | public class BinomialCoefficient {
method calculate (line 12) | public int calculate(int n, int k){
method main (line 24) | public static void main(String args[]){
FILE: src/com/interview/number/ConvertToBaseN.java
class ConvertToBaseN (line 3) | public class ConvertToBaseN {
method baseN (line 5) | int baseN(int num,int base){
method main (line 19) | public static void main(String args[]){
FILE: src/com/interview/number/CountNoOf2s.java
class CountNoOf2s (line 6) | public class CountNoOf2s {
method count2s (line 8) | public int count2s(int n){
method main (line 29) | public static void main(String args[]){
FILE: src/com/interview/number/CountNumbersNotIncluding4.java
class CountNumbersNotIncluding4 (line 6) | public class CountNumbersNotIncluding4 {
method count (line 8) | public int count(int n){
method main (line 33) | public static void main(String args[]){
FILE: src/com/interview/number/DivisionWithoutDivisionOperator.java
class DivisionWithoutDivisionOperator (line 3) | public class DivisionWithoutDivisionOperator {
class Pair (line 5) | public static class Pair {
method divide (line 10) | public Pair divide(int number, int divisor) {
method divideRec (line 22) | public int divideRec(int number, int divisor){
method efficientDivide (line 30) | public Pair efficientDivide(int divident, int divisor) {
method efficientDivideRec (line 54) | public int efficientDivideRec(int divident, int divisor){
method main (line 69) | public static void main(String args[]) {
FILE: src/com/interview/number/EuclideanAlgoForGCD.java
class EuclideanAlgoForGCD (line 7) | public class EuclideanAlgoForGCD {
method gcd (line 9) | public int gcd(int num1, int num2){
method gcdRec (line 26) | public int gcdRec(int num1, int num2){
method main (line 33) | public static void main(String args[]){
FILE: src/com/interview/number/FactorialOfLargeNumber.java
class FactorialOfLargeNumber (line 23) | public class FactorialOfLargeNumber {
method calculate (line 25) | public int calculate(int result[], int n){
method multiply (line 35) | private int multiply(int result[], int x, int size){
method main (line 55) | public static void main(String args[]){
FILE: src/com/interview/number/GenerateSignature.java
class GenerateSignature (line 14) | public class GenerateSignature {
method generate (line 16) | public int[] generate(char[] input) {
method reverse (line 41) | private void reverse(int[] result, int start, int end) {
method main (line 52) | public static void main(String args[]){
FILE: src/com/interview/number/LargestMultipleOf3inArray.java
class LargestMultipleOf3inArray (line 10) | public class LargestMultipleOf3inArray {
method swap (line 12) | public void swap(int input[],int i, int j){
method reverse (line 17) | private void reverse(int input[]){
method largestMultiple (line 23) | public int[] largestMultiple(int input[]){
method main (line 111) | public static void main(String args[]){
FILE: src/com/interview/number/LuckyNumbers.java
class LuckyNumbers (line 6) | public class LuckyNumbers {
method isLuck (line 8) | public boolean isLuck(int n,int counter){
method main (line 19) | public static void main(String args[]){
FILE: src/com/interview/number/MedianOf3Number.java
class MedianOf3Number (line 3) | public class MedianOf3Number {
method median (line 5) | public int median(int arr[]){
method median2Comparison (line 26) | public int median2Comparison(int arr[]){
method medianXORMethod (line 40) | public int medianXORMethod(int arr[]){
method main (line 47) | public static void main(String args[]){
FILE: src/com/interview/number/MthNumberInNSizeArray.java
class MthNumberInNSizeArray (line 12) | public class MthNumberInNSizeArray {
method find (line 14) | public int[] find(int n, int m) {
method find (line 21) | private void find(int result[], boolean used[], int start, int n, int ...
method binarySearch (line 33) | private int binarySearch(int m, int start, int end, int factorial) {
method fillupRemaining (line 48) | private void fillupRemaining(int result[], boolean used[], int index) {
method nthUnused (line 62) | private int nthUnused(boolean used[], int n) {
method factorial (line 75) | private int factorial(int n) {
method main (line 83) | public static void main(String args[]) {
FILE: src/com/interview/number/NBy2PairSumToK.java
class NBy2PairSumToK (line 8) | public class NBy2PairSumToK {
method pair (line 12) | public boolean pair(int input[],int k){
method main (line 34) | public static void main(String args[]){
FILE: src/com/interview/number/NextLargestPalindrome.java
class NextLargestPalindrome (line 6) | public class NextLargestPalindrome {
method nextPalindrome (line 8) | public void nextPalindrome(int num[]){
method printArray (line 54) | public void printArray(int num[]){
method main (line 60) | public static void main(String args[]){
FILE: src/com/interview/number/NotIncluding4.java
class NotIncluding4 (line 10) | public class NotIncluding4 {
method number (line 12) | public int number(int chinaNumber){
method main (line 31) | public static void main(String args[]){
FILE: src/com/interview/number/NumberOfCombinationsForStairs.java
class NumberOfCombinationsForStairs (line 14) | public class NumberOfCombinationsForStairs {
method numberOfWays (line 19) | public int numberOfWays(int n,int k){
method main (line 47) | public static void main(String args[]){
FILE: src/com/interview/number/PermutationBiggerThanNumber.java
class PermutationBiggerThanNumber (line 18) | public class PermutationBiggerThanNumber {
method nextPermutation (line 20) | public void nextPermutation(int[] nums) {
method reverse (line 37) | private void reverse(int nums[], int start, int end) {
method ceiling (line 47) | private int ceiling(int val, int start, int end, int[] nums) {
method main (line 61) | public static void main(String args[]){
FILE: src/com/interview/number/PermutationLargerThanGivenArray.java
class PermutationLargerThanGivenArray (line 11) | public class PermutationLargerThanGivenArray {
method findBiggerNumber (line 13) | public int[] findBiggerNumber(int src[],int dest[]){
method sortRemaining (line 23) | private void sortRemaining(int src[],int result[],boolean used[],int p...
method findNumber (line 34) | private boolean findNumber(int src[],int dest[],int result[],int pos,b...
method main (line 79) | public static void main(String args[]){
FILE: src/com/interview/number/PowerFunction.java
class PowerFunction (line 15) | public class PowerFunction {
method power (line 17) | public int power(int n, int m){
method powerUsingBit (line 30) | public double powerUsingBit(double x, int n) {
method main (line 53) | public static void main(String args[]){
FILE: src/com/interview/number/RearrangeNumberInArrayToFormLargestNumber.java
class RearrangeNumberInArrayToFormLargestNumber (line 12) | public class RearrangeNumberInArrayToFormLargestNumber {
method largestNumber (line 14) | public String largestNumber(int[] nums) {
method main (line 41) | public static void main(String args[]){
class IntegerComparator (line 51) | class IntegerComparator implements Comparator<Integer> {
method compare (line 52) | @Override
FILE: src/com/interview/number/RussianPeasantMultiplication.java
class RussianPeasantMultiplication (line 9) | public class RussianPeasantMultiplication {
method multiply (line 11) | public int multiply(int a,int b){
method main (line 23) | public static void main(String args[]){
FILE: src/com/interview/number/SmallestNumberGreaterThanGiveNumberIncreasingSequence.java
class SmallestNumberGreaterThanGiveNumberIncreasingSequence (line 13) | public class SmallestNumberGreaterThanGiveNumberIncreasingSequence {
method getNextInt (line 15) | public int[] getNextInt(int []input){
method getNextInt (line 27) | private boolean getNextInt(int input[], int result[], int pos){
method fillRestOfArray (line 67) | private void fillRestOfArray(int result[],int pos,int val){
method getHigherNumber (line 74) | private int getHigherNumber(int input, int i, int len){
method main (line 81) | public static void main(String args[]){
FILE: src/com/interview/number/SquareRoot.java
class SquareRoot (line 6) | public class SquareRoot {
method findRoot (line 8) | double findRoot(int num){
method main (line 19) | public static void main(String args[]){
FILE: src/com/interview/number/StrobogrammaticNumber.java
class StrobogrammaticNumber (line 7) | public class StrobogrammaticNumber {
method isStrobogrammatic (line 8) | public boolean isStrobogrammatic(String num) {
FILE: src/com/interview/number/Trailing0sinFactorial.java
class Trailing0sinFactorial (line 9) | public class Trailing0sinFactorial {
method trailing0s (line 11) | public int trailing0s(int num){
method main (line 21) | public static void main(String args[]){
FILE: src/com/interview/number/UniquePartitionOfInteger.java
class UniquePartitionOfInteger (line 11) | public class UniquePartitionOfInteger {
method partition (line 13) | public void partition(int n){
method partition (line 18) | private void partition(int n, int max,List<Integer> result){
method main (line 34) | public static void main(String args[]){
FILE: src/com/interview/playground/TestInnerClass.java
class TestInnerClass (line 8) | public class TestInnerClass {
method test (line 12) | public Okay test() {
method test1 (line 19) | public void test1() {
method main (line 28) | public static void main(String args[]) {
type Okay (line 34) | interface Okay {
method next (line 35) | int next();
FILE: src/com/interview/random/Rand7UsingRand5.java
class Rand7UsingRand5 (line 3) | public class Rand7UsingRand5 {
method rand7 (line 5) | public int rand7(){
method rand5 (line 13) | private int rand5(){
method main (line 17) | public static void main(String args[]){
FILE: src/com/interview/random/RandomCountrySelectionByPopluation.java
class RandomCountrySelectionByPopluation (line 3) | public class RandomCountrySelectionByPopluation {
method getRandom (line 5) | public int getRandom(int []arr){
method main (line 33) | public static void main(String args[]){
FILE: src/com/interview/random/SelectMRandomNumbersInStream.java
class SelectMRandomNumbersInStream (line 7) | public class SelectMRandomNumbersInStream {
method selectRandom (line 9) | public int[] selectRandom(int arr[],int m){
method main (line 24) | public static void main(String args[]){
FILE: src/com/interview/random/ShuffleArray.java
class ShuffleArray (line 7) | public class ShuffleArray {
method shuffle (line 9) | public void shuffle(int arr[]){
method swap (line 17) | private void swap(int arr[],int a,int b){
method main (line 23) | public static void main(String args[]){
FILE: src/com/interview/recursion/AllAdjacentCombination.java
class AllAdjacentCombination (line 14) | public class AllAdjacentCombination {
method combination (line 16) | public void combination(int input[],int result[],int k,int pos,int r){
method formNumber (line 31) | private int formNumber(int input[], int start, int end){
method main (line 39) | public static void main(String args[]){
FILE: src/com/interview/recursion/Bracketology.java
class Bracketology (line 6) | public class Bracketology {
method matchBracket (line 8) | public boolean matchBracket(char str[],int openCount,int pos){
method printArray (line 30) | private void printArray(char result[]){
method bracketPermutation (line 37) | public void bracketPermutation(char result[],int n, int pos,int openCo...
method matchBracket (line 52) | public boolean matchBracket(char []brackets){
method getOpeningCharacter (line 74) | private Character getOpeningCharacter(char ch){
method main (line 85) | public static void main(String args[]){
FILE: src/com/interview/recursion/ChainWordsToFormCircle.java
class ChainWordsToFormCircle (line 15) | public class ChainWordsToFormCircle {
method formCircle (line 17) | public List<String> formCircle(String input[]){
method formCircle (line 31) | private boolean formCircle(String input[], List<String> result,boolean...
method main (line 61) | public static void main(String args[]){
FILE: src/com/interview/recursion/Combination.java
class Combination (line 5) | public class Combination {
method combination (line 7) | public void combination(char input[]){
method combination (line 30) | private void combination(char input[],int count[],int pos, char output...
method print (line 43) | private void print(char result[],int pos){
method combinationEasy (line 50) | public void combinationEasy(char[] input) {
method combinationEasy (line 56) | private void combinationEasy(char[] input, int pos, List<Character> r) {
method main (line 70) | public static void main(String args[]){
FILE: src/com/interview/recursion/CombinationOfSizeK.java
class CombinationOfSizeK (line 6) | public class CombinationOfSizeK {
method combination (line 8) | public void combination(int arr[],int k){
method combinationUtil (line 13) | private void combinationUtil(int arr[],int k, int pos,int result[],int...
method main (line 27) | public static void main(String args[]){
FILE: src/com/interview/recursion/CombinationWithStar.java
class CombinationWithStar (line 16) | public class CombinationWithStar {
method combine (line 18) | public void combine(char input[], int pos, boolean used[]){
method printArray (line 27) | private void printArray(char result[], boolean used[]){
method main (line 38) | public static void main(String args[]){
FILE: src/com/interview/recursion/DifferentWaysToAddParentheses.java
class DifferentWaysToAddParentheses (line 8) | public class DifferentWaysToAddParentheses {
method diffWaysToCompute (line 9) | public List<Integer> diffWaysToCompute(String str) {
method diffWaysToComputeUtil (line 24) | private List<Integer> diffWaysToComputeUtil(List<Integer> operands, Li...
method operate (line 46) | private long operate(int val1, int val2, char op) {
method main (line 58) | public static void main(String args[]) {
FILE: src/com/interview/recursion/FancyShuffle.java
class FancyShuffle (line 18) | public class FancyShuffle {
method shuffle (line 20) | public char[] shuffle(char input[]){
method shuffleUtil (line 49) | private boolean shuffleUtil(char input[], int freq[], char result[], i...
method main (line 71) | public static void main(String args[]) {
FILE: src/com/interview/recursion/InterpretationOfArray.java
class InterpretationOfArray (line 9) | public class InterpretationOfArray {
method interpret (line 11) | public void interpret(int arr[]){
method interpret (line 28) | private void interpret(int len,int pos,List<Character> result,char[][]...
method print (line 47) | private void print(List<Character> result){
method getRepresentation (line 54) | private char getRepresentation(int number){
method main (line 61) | public static void main(String args[]){
FILE: src/com/interview/recursion/KeyPadPermutation.java
class KeyPadPermutation (line 6) | public class KeyPadPermutation {
method permute (line 8) | public void permute(int input[]) {
method permute (line 13) | private void permute(int input[], int pos, char result[]) {
method getCharSetForNumber (line 29) | private char[] getCharSetForNumber(int num) {
method main (line 43) | public static void main(String args[]){
FILE: src/com/interview/recursion/LongestAbsolutePath.java
class LongestAbsolutePath (line 26) | public class LongestAbsolutePath {
method lengthLongestPath (line 27) | public int lengthLongestPath(String input) {
method lengthLongestPath (line 40) | public int lengthLongestPath(Queue<Node> queue, Node root, int current...
class Node (line 60) | class Node {
method Node (line 64) | Node(String file, int level) {
method Node (line 68) | Node(String file) {
method lengthLongestPathIterative (line 84) | public int lengthLongestPathIterative(String input) {
FILE: src/com/interview/recursion/MinimumEditForReversePolishNotation.java
class MinimumEditForReversePolishNotation (line 6) | public class MinimumEditForReversePolishNotation {
method minimum (line 8) | public int minimum(char input[]){
method minimum (line 12) | private int minimum(char input[],int pos,int countXs){
method main (line 48) | public static void main(String args[]){
FILE: src/com/interview/recursion/NQueenProblem.java
class NQueenProblem (line 19) | public class NQueenProblem {
class Position (line 21) | class Position {
method Position (line 23) | Position(int row, int col) {
method solveNQueenOneSolution (line 29) | public Position[] solveNQueenOneSolution(int n) {
method solveNQueenOneSolutionUtil (line 39) | private boolean solveNQueenOneSolutionUtil(int n, int row, Position[] ...
method solveNQueens (line 68) | public List<List<String>> solveNQueens(int n) {
method solve (line 75) | public void solve(int current, Position[] positions, List<List<String>...
method main (line 110) | public static void main(String args[]) {
FILE: src/com/interview/recursion/OneEditApart.java
class OneEditApart (line 14) | public class OneEditApart {
method isOneEditDistance (line 16) | public boolean isOneEditDistance(String s, String t) {
method main (line 52) | public static void main(String args[]){
FILE: src/com/interview/recursion/OperatorAdditionForTarget.java
class OperatorAdditionForTarget (line 14) | public class OperatorAdditionForTarget {
method addOperators (line 15) | public List<String> addOperators(String num, int target) {
method dfs (line 25) | private void dfs(String nums, int pos, int target, long runningTotal, ...
method main (line 55) | public static void main(String args[]) {
FILE: src/com/interview/recursion/OptimalDivision.java
class OptimalDivision (line 9) | public class OptimalDivision {
method optimalDivision (line 10) | public String optimalDivision(int[] nums) {
method optimalDivison (line 16) | private Result optimalDivison(int[] nums, int start, int end, boolean ...
class Result (line 55) | class Result {
method Result (line 58) | Result(double val, String str) {
method main (line 64) | public static void main(String args[]) {
FILE: src/com/interview/recursion/PrintAllPathFromTopLeftToBottomRight.java
class PrintAllPathFromTopLeftToBottomRight (line 8) | public class PrintAllPathFromTopLeftToBottomRight {
method print (line 11) | public void print(int arr[][],int row, int col,int result[],int pos){
method main (line 26) | public static void main(String args[]){
FILE: src/com/interview/recursion/PrintAllSubsequence.java
class PrintAllSubsequence (line 12) | public class PrintAllSubsequence {
method print (line 13) | public void print(int[] input) {
method print (line 21) | private void print(int[] input, int[] output, int len, int current, bo...
method main (line 39) | public static void main(String args[]) {
FILE: src/com/interview/recursion/PrintArrayInAdjacentWay.java
class PrintArrayInAdjacentWay (line 24) | public class PrintArrayInAdjacentWay {
method printArray (line 26) | public void printArray(int len,int k){
method printArray (line 31) | private void printArray(int len, int pos,List<Integer> result,int k){
method numberOfWaysPossible (line 50) | public int numberOfWaysPossible(int input[],int pos){
method numberOfWaysPossibleFaster (line 76) | public int numberOfWaysPossibleFaster(int input[]){
method main (line 92) | public static void main(String args[]){
FILE: src/com/interview/recursion/PrintArrayInCustomizedFormat.java
class PrintArrayInCustomizedFormat (line 9) | public class PrintArrayInCustomizedFormat {
method print (line 11) | void print(char str[][]){
method DFS (line 26) | private void DFS(char str[][],int pos,int distance,Map<Character,Boole...
method main (line 43) | public static void main(String args[]){
FILE: src/com/interview/recursion/PrintSumCombination.java
class PrintSumCombination (line 25) | public class PrintSumCombination {
method combinationSum (line 27) | public List<List<Integer>> combinationSum(int[] candidates, int target) {
method combinationSumUtil (line 38) | private void combinationSumUtil(int[] candidates, int target, List<Int...
method main (line 61) | public static void main(String args[]) {
FILE: src/com/interview/recursion/ReconstructItinerary.java
class ReconstructItinerary (line 15) | public class ReconstructItinerary {
method findItinerary (line 16) | public List<String> findItinerary(String[][] tickets) {
method findItineraryUtil (line 28) | boolean findItineraryUtil(List<Itinerary> input, boolean[] used, Strin...
class Itinerary (line 51) | class Itinerary implements Comparable<Itinerary> {
method Itinerary (line 54) | Itinerary(String start, String dest) {
method compareTo (line 59) | @Override
method main (line 69) | public static void main(String args[]) {
FILE: src/com/interview/recursion/RemoveInvalidParenthesis.java
class RemoveInvalidParenthesis (line 15) | public class RemoveInvalidParenthesis {
method removeInvalidParentheses (line 17) | public List<String> removeInvalidParentheses(String s) {
method DFS (line 31) | public void DFS(Set<String> res, String s, int i, int rmL, int rmR, in...
method main (line 56) | public static void main(String args[]) {
FILE: src/com/interview/recursion/RestoreIPAddresses.java
class RestoreIPAddresses (line 14) | public class RestoreIPAddresses {
method restoreIpAddresses (line 15) | public List<String> restoreIpAddresses(String s) {
method restoreIpAddressesUtil (line 22) | private void restoreIpAddressesUtil(String s, int start, int count, Li...
FILE: src/com/interview/recursion/SetPairTogether.java
class SetPairTogether (line 17) | public class SetPairTogether {
method findMinimumSwaps (line 19) | public int findMinimumSwaps(int input[], Map<Integer, Integer> pair) {
method findMinimumSwapsUtil (line 27) | public int findMinimumSwapsUtil(int input[], Map<Integer, Integer> pai...
method swap (line 57) | private void swap(Map<Integer, Integer> index, int input[], int i, int...
method main (line 66) | public static void main(String args[]) {
FILE: src/com/interview/recursion/StringInterleaving.java
class StringInterleaving (line 3) | public class StringInterleaving {
method printArray (line 5) | private void printArray(char[] str){
method interleaving (line 12) | public void interleaving(char[] str1,char[] str2,int len1,int len2,int...
method main (line 29) | public static void main(String args[]){
FILE: src/com/interview/recursion/StringPermutation.java
class StringPermutation (line 15) | public class StringPermutation {
method permute (line 17) | public List<String> permute(char input[]) {
method permuteUtil (line 42) | public void permuteUtil(char str[], int count[], char result[], int le...
method printArray (line 59) | private void printArray(char input[]) {
method main (line 66) | public static void main(String args[]) {
FILE: src/com/interview/recursion/StringPermutationRotation.java
class StringPermutationRotation (line 3) | public class StringPermutationRotation {
method swap (line 5) | private void swap(char arr[],int i, int j){
method printArray (line 11) | private void printArray(char str[]){
method permute (line 18) | public void permute(char[] str,int pos){
method main (line 30) | public static void main(String args[]){
FILE: src/com/interview/recursion/SudokuSolver.java
class SudokuSolver (line 13) | public class SudokuSolver {
method solveSudoku (line 15) | public void solveSudoku(char[][] input) {
method solveSudokuUtil (line 33) | private boolean solveSudokuUtil(char[][] input, boolean[][] horizontal...
method main (line 65) | public static void main(String args[]) {
FILE: src/com/interview/recursion/WordCombination.java
class WordCombination (line 18) | public class WordCombination {
method printCombinations (line 20) | public void printCombinations(List<List<String>> input) {
method print (line 25) | private void print(List<List<String>> input, int[] result, int pos) {
method main (line 42) | public static void main(String args[]){
FILE: src/com/interview/recursion/WordPattern.java
class WordPattern (line 14) | public class WordPattern {
method wordPatternMatch (line 15) | public boolean wordPatternMatch(String pattern, String str) {
method wordPatternMatch (line 21) | public boolean wordPatternMatch(String pattern, String str, int pos1, ...
method main (line 48) | public static void main(String args[]) {
FILE: src/com/interview/regex/MultiSpaceReplacement.java
class MultiSpaceReplacement (line 6) | public class MultiSpaceReplacement {
method replace (line 8) | public void replace(String str){
method main (line 15) | public static void main(String args[]){
FILE: src/com/interview/sort/CountingSort.java
class CountingSort (line 3) | public class CountingSort {
method sort (line 7) | public void sort(int arr[]) {
method sort1 (line 23) | public void sort1(int arr[]) {
method main (line 45) | public static void main(String args[]) {
FILE: src/com/interview/sort/HeapSort.java
class HeapSort (line 25) | public class HeapSort {
method sort (line 27) | public void sort(int arr[]){
method heapify (line 38) | private void heapify(int arr[], int end){
method swap (line 64) | private void swap(int arr[], int x, int y){
method heapAdd (line 70) | private void heapAdd(int arr[], int end){
method main (line 82) | public static void main(String args[]){
FILE: src/com/interview/sort/IterativeQuickSort.java
class IterativeQuickSort (line 11) | public class IterativeQuickSort {
method sort (line 13) | public void sort(int arr[]){
method partition (line 41) | private int partition(int arr[], int low,int high){
method swap (line 57) | private void swap(int arr[],int a,int b){
method main (line 63) | public static void main(String args[]){
FILE: src/com/interview/sort/MergeSort.java
class MergeSort (line 12) | public class MergeSort {
method sort (line 14) | public void sort(int input[]){
method sort (line 18) | private void sort(int input[], int low, int high){
method sortedMerge (line 29) | private void sortedMerge(int input[], int low, int high){
method printArray (line 55) | public void printArray(int input[]){
method main (line 62) | public static void main(String args[]){
FILE: src/com/interview/sort/PanCakeSorting.java
class PanCakeSorting (line 17) | public class PanCakeSorting {
method sort (line 19) | public void sort(int arr[]){
method findMax (line 27) | private int findMax(int arr[],int pos){
method flip (line 37) | private void flip(int arr[],int pos){
method swap (line 43) | private void swap(int arr[],int i,int j){
method main (line 49) | public static void main(String args[]){
FILE: src/com/interview/sort/QuickSort.java
class QuickSort (line 3) | public class QuickSort {
method swap (line 5) | private void swap(int A[],int i,int j)
method split (line 11) | private int split(int A[],int low,int high)
method split1 (line 37) | private int split1(int A[],int low,int high){
method sort (line 62) | public void sort(int A[],int low,int high)
method printArray (line 73) | private void printArray(int arr[]){
method main (line 78) | public static void main(String args[]){
FILE: src/com/interview/sort/RadixSort.java
class RadixSort (line 3) | public class RadixSort {
method countSort (line 5) | private void countSort(int arr[],int exp){
method max (line 28) | private int max(int arr[]){
method radixSort (line 38) | public void radixSort(int arr[]){
method main (line 46) | public static void main(String args[]){
FILE: src/com/interview/sort/Sort0toN3.java
class Sort0toN3 (line 6) | public class Sort0toN3 {
method sort (line 8) | public void sort(int arr[],int n){
method sort (line 15) | private void sort(int arr[],int n, int exp){
method main (line 36) | public static void main(String args[]){
FILE: src/com/interview/sort/SortArrayByFrequence.java
class SortArrayByFrequence (line 11) | public class SortArrayByFrequence {
class SortNode (line 13) | class SortNode{
class FrequenceComparator (line 18) | class FrequenceComparator implements Comparator<Integer>{
method FrequenceComparator (line 20) | FrequenceComparator(Map<Integer,SortNode> countMap){
method compare (line 23) | @Override
method sortByFrequence (line 38) | public void sortByFrequence(Integer arr[]){
method main (line 58) | public static void main(String args[]){
FILE: src/com/interview/stackqueue/CircularQueue.java
class CircularQueue (line 3) | public class CircularQueue<T> {
method CircularQueue (line 7) | public CircularQueue(int size){
method offer (line 13) | public void offer(T t){
method top (line 26) | public T top(){
method poll (line 34) | public T poll(){
method isEmpty (line 50) | public boolean isEmpty(){
method isFull (line 57) | public boolean isFull(){
method main (line 64) | public static void main(String args[]){
FILE: src/com/interview/stackqueue/MaximumHistogram.java
class MaximumHistogram (line 38) | public class MaximumHistogram {
method maxHistogram (line 40) | public int maxHistogram(int input[]){
method main (line 88) | public static void main(String args[]){
FILE: src/com/interview/stackqueue/MedianFinder.java
class MedianFinder (line 14) | public class MedianFinder {
method MedianFinder (line 19) | public MedianFinder() {
method addNum (line 25) | public void addNum(int num) {
method findMedian (line 49) | public double findMedian() {
method main (line 57) | public static void main(String args[]) {
FILE: src/com/interview/stackqueue/RealTimeCounter.java
class RealTimeCounter (line 6) | public class RealTimeCounter {
method add (line 11) | public void add(long currentTimeInMills){
method getCallsInLastSec (line 21) | public long getCallsInLastSec(long currentTimeInMills){
method main (line 29) | public static void main(String args[]){
FILE: src/com/interview/stackqueue/RealTimeCounterUsingCircularQueue.java
class RealTimeCounterUsingCircularQueue (line 6) | public class RealTimeCounterUsingCircularQueue {
class Node (line 8) | class Node {
method add (line 21) | public void add(long time) {
method getCount (line 55) | public int getCount(int time){
method main (line 68) | public static void main(String args[]){
FILE: src/com/interview/stackqueue/RemoveDuplicateMaintainingOrder.java
class RemoveDuplicateMaintainingOrder (line 15) | public class RemoveDuplicateMaintainingOrder {
method removeDuplicateLetters (line 16) | public String removeDuplicateLetters(String s) {
method main (line 52) | public static void main(String args[]) {
FILE: src/com/interview/stackqueue/RemoveExtraBrackets.java
class RemoveExtraBrackets (line 39) | public class RemoveExtraBrackets {
method remove (line 41) | public int remove(char input[]){
method removeWithoutExtraSpace (line 81) | public int removeWithoutExtraSpace(char input[]){
method printArray (line 122) | public static void printArray(char input[], int size) {
method main (line 129) | public static void main(String args[]){
FILE: src/com/interview/stackqueue/ReverseStackUsingRecursion.java
class ReverseStackUsingRecursion (line 10) | public class ReverseStackUsingRecursion {
method reverse (line 12) | public void reverse(Deque<Integer> stack){
method pushAtBottom (line 22) | private void pushAtBottom(Deque<Integer> stack,int data){
method main (line 32) | public static void main(String args[]){
FILE: src/com/interview/stackqueue/SimplyPath.java
class SimplyPath (line 21) | public class SimplyPath {
method simplifyPath (line 23) | public String simplifyPath(String path) {
method main (line 46) | public static void main(String args[]){
FILE: src/com/interview/stackqueue/StockSpanProblem.java
class StockSpanProblem (line 19) | public class StockSpanProblem {
method stockSpan (line 20) | public static int[] stockSpan(int[] prices){
method main (line 39) | public static void main(String[] args) {
FILE: src/com/interview/string/AnagramOfFirstAsSubstring.java
class AnagramOfFirstAsSubstring (line 16) | public class AnagramOfFirstAsSubstring {
method isSubString (line 18) | public boolean isSubString(char str1[], char str2[]) {
method containsAndUpdate (line 49) | private boolean containsAndUpdate(Map<Character, Integer> currentCount,
method incrementCount (line 70) | private void incrementCount(Character ch, Map<Character, Integer> coun...
method main (line 79) | public static void main(String args[]){
FILE: src/com/interview/string/CycleLeaderIteration.java
class CycleLeaderIteration (line 3) | public class CycleLeaderIteration {
method iterate (line 6) | public void iterate(char str[],int start,int end){
method main (line 29) | public static void main(String args[]){
FILE: src/com/interview/string/GroupAnagramsTogether.java
class GroupAnagramsTogether (line 8) | public class GroupAnagramsTogether {
method groupAnagrams (line 9) | public List<List<String>> groupAnagrams(String[] strs) {
FILE: src/com/interview/string/InPlaceTransformationOfString.java
class InPlaceTransformationOfString (line 6) | public class InPlaceTransformationOfString {
method reverse (line 8) | private void reverse(char []str, int low, int high){
method swap (line 16) | private void swap(char str[],int index1,int index2){
method cycleLeaderIteration (line 22) | public void cycleLeaderIteration(char []str,int start,int end){
method inPlaceTransformationImproved (line 47) | public void inPlaceTransformationImproved(char str[]){
method get3PowerK1 (line 70) | private int get3PowerK1(int size){
method main (line 78) | public static void main(String args[]){
FILE: src/com/interview/string/LexicographicRankInPermutation.java
class LexicographicRankInPermutation (line 3) | public class LexicographicRankInPermutation {
method findNumberOfSmallerCharactersOnRight (line 9) | private int findNumberOfSmallerCharactersOnRight(int index,char []str){
method factorial (line 19) | private int factorial(int n){
method rank (line 27) | public int rank(char []str){
method main (line 38) | public static void main(String args[]){
FILE: src/com/interview/string/LongestPalindromeSubstring.java
class LongestPalindromeSubstring (line 16) | public class LongestPalindromeSubstring {
method longestPalindromeSubstringEasy (line 18) | public int longestPalindromeSubstringEasy(char arr[]) {
method longestPalindromicSubstringLinear (line 60) | public int longestPalindromicSubstringLinear(char input[]) {
method longestPalindromeDynamic (line 129) | public int longestPalindromeDynamic(char []str){
method main (line 161) | public static void main(String args[]) {
FILE: src/com/interview/string/LongestSubstringWithKDistinctCharacters.java
class LongestSubstringWithKDistinctCharacters (line 19) | public class LongestSubstringWithKDistinctCharacters {
method lengthOfLongestSubstringKDistinct (line 20) | public int lengthOfLongestSubstringKDistinct(String s, int k) {
method lengthOfLongestSubstringKDistinctUsingMap (line 49) | public int lengthOfLongestSubstringKDistinctUsingMap(String s, int k) {
FILE: src/com/interview/string/LongestSubstringWithoutRepetingCharacter.java
class LongestSubstringWithoutRepetingCharacter (line 11) | public class LongestSubstringWithoutRepetingCharacter {
method lengthOfLongestSubstring (line 13) | public int lengthOfLongestSubstring(String s) {
method main (line 34) | public static void main(String args[]){
FILE: src/com/interview/string/MultiplyStrings.java
class MultiplyStrings (line 6) | public class MultiplyStrings {
method multiply (line 8) | public String multiply(String num1, String num2) {
method multiply (line 13) | private String multiply(String num1, String num2, int start1, int end1...
method simpleMultiply (line 38) | private String simpleMultiply(String num1, String num2) {
method append0s (line 66) | private String append0s(String v1, int count ) {
method add (line 74) | public String add(char[] num1,char[] num2){
method main (line 108) | public static void main(String args[]) {
FILE: src/com/interview/string/NTMatch.java
class NTMatch (line 18) | public class NTMatch {
method match (line 20) | public boolean match(char str[]){
method buildKMP (line 46) | private int[] buildKMP(char str[]){
method main (line 71) | public static void main(String args[]){
FILE: src/com/interview/string/PalindromePair.java
class PalindromePair (line 20) | public class PalindromePair {
method palindromePairs (line 22) | public List<List<Integer>> palindromePairs(String[] words) {
method isPalindrome (line 59) | private boolean isPalindrome(String word) {
method createList (line 72) | private void createList(int i1, int i2, List<List<Integer>> result) {
method main (line 82) | public static void main(String args[]) {
FILE: src/com/interview/string/PrintAnagramTogether.java
class PrintAnagramTogether (line 8) | public class PrintAnagramTogether {
method print (line 10) | public void print(String[] string){
method main (line 34) | public static void main(String args[]){
FILE: src/com/interview/string/RabinKarpSearch.java
class RabinKarpSearch (line 15) | public class RabinKarpSearch {
method patternSearch (line 19) | public int patternSearch(char[] text, char[] pattern){
method recalculateHash (line 35) | private long recalculateHash(char[] str,int oldIndex, int newIndex,lon...
method createHash (line 42) | private long createHash(char[] str, int end){
method checkEqual (line 50) | private boolean checkEqual(char str1[],int start1,int end1, char str2[...
method main (line 64) | public static void main(String args[]){
FILE: src/com/interview/string/RearrangeDuplicateCharsdDistanceAway.java
class RearrangeDuplicateCharsdDistanceAway (line 13) | public class RearrangeDuplicateCharsdDistanceAway {
class CharCount (line 15) | class CharCount implements Comparable<CharCount>{
method hashCode (line 18) | @Override
method equals (line 26) | @Override
method getOuterType (line 41) | private RearrangeDuplicateCharsdDistanceAway getOuterType() {
method toString (line 46) | @Override
method compareTo (line 50) | @Override
method rearrangeExactKDistanceAway (line 61) | public boolean rearrangeExactKDistanceAway(char input[],int d){
method getAllFeasibleCharacters (line 99) | private void getAllFeasibleCharacters(char output[], int k,int pos,Set...
method rearrangeAtleastkDistanceAway (line 105) | public boolean rearrangeAtleastkDistanceAway(char input[],int k){
method rearrangeAtleastkDistanceAway (line 119) | public boolean rearrangeAtleastkDistanceAway(Map<Character,Integer> ch...
method main (line 145) | public static void main(String args[]){
FILE: src/com/interview/string/RemoveConsecutiveDuplicate.java
class RemoveConsecutiveDuplicate (line 14) | public class RemoveConsecutiveDuplicate {
method removeDuplicates (line 16) | public int removeDuplicates(char input[]){
method main (line 30) | public static void main(String args[]){
FILE: src/com/interview/string/RunLengthEncoding.java
class RunLengthEncoding
Condensed preview — 646 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,359K chars).
[
{
"path": ".gitignore",
"chars": 157,
"preview": "interview.iml\ninterview.ipr\ninterview.iws\nbuild/\n.gradle/\n.classpath\n.project\n.settings/\n/bin/\n/out\n.DS_Store\npython/gra"
},
{
"path": ".idea/misc.xml",
"chars": 215,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"ProjectRootManager\" version=\"2\" language"
},
{
"path": ".idea/vcs.xml",
"chars": 167,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <component name=\"VcsDirectoryMappings\">\n <mapping dire"
},
{
"path": "C++/Arrays/Trapping the rain water.cpp",
"chars": 636,
"preview": "#include <iostream>\nusing namespace std;\n\nint trapped_water(int array[],int size){\n int amount = 0;\n int left[size"
},
{
"path": "C++/Bit Manipulation/Checking Whether K-th Bit is Set or Not.cpp",
"chars": 318,
"preview": "#include<iostream>\nusing namespace std;\nint main(){\n int n,k;\n cout << \"Enter the number and the value of K : \";\n "
},
{
"path": "C++/Bit Manipulation/Clearing the K-th bit of a number.cpp",
"chars": 274,
"preview": "#include<iostream>\nusing namespace std;\nint main(){\n int n,k,mask;\n cout << \"Enter the number and the value of K :"
},
{
"path": "C++/Bit Manipulation/Setting the K-th bit of a number.cpp",
"chars": 262,
"preview": "#include<iostream>\nusing namespace std;\nint main(){\n int n,k;\n cout << \"Enter the number and the value of K :\";\n "
},
{
"path": "C++/Bit Manipulation/Toggling Rightmost Set Bit of a number.cpp",
"chars": 224,
"preview": "#include<iostream>\nusing namespace std;\nint main(){\n int n;\n cout << \"Enter the number : \";\n cin >> n ;\n n ="
},
{
"path": "C++/Bit Manipulation/Toggling the K-th bit of a number.cpp",
"chars": 273,
"preview": "#include<iostream>\nusing namespace std;\nint main(){\n int n,k,mask;\n cout << \"Enter the number and the value of K :"
},
{
"path": "C++/Dynamic Programming/Edit Distance.cpp",
"chars": 487,
"preview": "int editDistance(string s1, string s2){\n int m = s1.length();\n int n = s2.length();\n int dp[m+1][n+1];\n for "
},
{
"path": "C++/Dynamic Programming/Longest Common Subsequence.cpp",
"chars": 470,
"preview": "int lcs(string x,string y){\n int m = x.size(),n = y.size();\n int dp[m+1][n+1];\n for(int i=0;i<=m;i++){\n "
},
{
"path": "C++/Dynamic Programming/Longest Common Substring.cpp",
"chars": 655,
"preview": "#include <iostream>\nusing namespace std;\n\nint longest_common_substring(string x,string y){\n int m = x.size();\n in"
},
{
"path": "C++/Dynamic Programming/Longest Increasing Subsequence.cpp",
"chars": 415,
"preview": "int lis(int array[],int n){\n int dp[n],lis_value = -1;\n for(int i=0;i<n;i++){\n dp[i] = 1;\n }\n for(int"
},
{
"path": "C++/Dynamic Programming/Longest palindromic Subsequence.cpp",
"chars": 682,
"preview": "#include <iostream>\nusing namespace std;\nint longest_palindromic_subsequence(string str){\n int table[str.size()][str."
},
{
"path": "C++/Dynamic Programming/Matrix Chain Multiplication.cpp",
"chars": 446,
"preview": "int mcm(int p[], int n){\n int m[n][n];\n int i, j, k, L, q;\n for (i = 1; i < n; i++)\n m[i][i] = 0;\n fo"
},
{
"path": "C++/Graph Algorithms/All Pair Shortest Path Problem.cpp",
"chars": 744,
"preview": "#include<iostream>\n#include<vector>\nusing namespace std;\n\nvoid floydWarshall(vector<vector<int>> &graph){\n for (int k"
},
{
"path": "C++/Graph Algorithms/Breadth First Search.cpp",
"chars": 843,
"preview": "#include<iostream>\n#include<vector>\n#include<list>\n#include<queue>\nusing namespace std;\nvoid breadth_first_search(vector"
},
{
"path": "C++/Graph Algorithms/Connected Components Algorithm DFS.cpp",
"chars": 934,
"preview": "#include<iostream>\n#include<vector>\n#include<list>\nusing namespace std;\n\nvoid connectedComponentsDFS(vector<list<int>> g"
},
{
"path": "C++/Graph Algorithms/Depth First Search.cpp",
"chars": 837,
"preview": "#include<iostream>\n#include<vector>\n#include<list>\n#include<stack>\nusing namespace std;\nvoid depth_first_search(vector<l"
},
{
"path": "C++/Graph Algorithms/Kruskal's Minimum Spanning Tree Algorithm.cpp",
"chars": 2550,
"preview": "#include<iostream>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n\nstruct edge{int src,des,weight;};\n\nclass U"
},
{
"path": "C++/Graph Algorithms/Prims Minimum Spanning Tree Algorithm.cpp",
"chars": 1646,
"preview": "#include<iostream>\n#include<climits>\n#include<vector>\n#include<queue>\n#include<list>\nusing namespace std;\n\nconst int INF"
},
{
"path": "C++/Graph Algorithms/Recursive Depth First Search.cpp",
"chars": 707,
"preview": "#include<iostream>\n#include<vector>\n#include<list>\nusing namespace std;\nvoid depth_first_search(vector<list<int>> graph,"
},
{
"path": "C++/Graph Algorithms/Single Shortest Path Bellman Ford Algorithm.cpp",
"chars": 1364,
"preview": "#include<iostream>\n#include<vector>\n#include<climits>\nusing namespace std;\n\nstruct edge {int src, des, weight;};\n\npair<b"
},
{
"path": "C++/Graph Algorithms/Single Source Shortest Path Dijkstra Algorithm.cpp",
"chars": 1607,
"preview": "#include<iostream>\n#include<queue>\n#include<vector>\n#include<list>\n#include<climits>\nusing namespace std;\nstruct compare"
},
{
"path": "C++/Graph Algorithms/Topological Sorting.cpp",
"chars": 1166,
"preview": "#include<iostream>\n#include<vector>\n#include<list>\nusing namespace std;\n\nvoid topologicalSortDFS(vector<list<int>> graph"
},
{
"path": "C++/Heaps - Priority Queues/K-th Largest element of the stream.cpp",
"chars": 727,
"preview": "#include <iostream>\n#include <queue>\nusing namespace std;\n\nint main(){\n int n,k;\n priority_queue<int,vector<int>,g"
},
{
"path": "C++/Linked List/Reverse a linked list recursively.cpp",
"chars": 54,
"preview": "void reverse_list(list_node *head){\n list_node *\n}\n"
},
{
"path": "C++/Number Theory Algorithms/Divisors.cpp",
"chars": 466,
"preview": "#include<iostream>\n#include<set>\nusing namespace std;\nset<int> generateDivisors(long long int num){\n set<int> divisor"
},
{
"path": "C++/Number Theory Algorithms/Sieve of Eratosthenes.cpp",
"chars": 533,
"preview": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n\nconst int MAX = 1000*1000;\nconst int LMT ="
},
{
"path": "C++/Recursion/Partition of array on the pivot.cpp",
"chars": 403,
"preview": "#include<iostream>\nusing namespace std;\nvoid partition(int array[],int low,int high){\n int i = low-1, pivot = array[h"
},
{
"path": "C++/Recursion/Permutation of a string.cpp",
"chars": 460,
"preview": "#include <iostream>\nusing namespace std;\n\nvoid permutation(char str[],int k,int n){\n if(k == n){\n for(int j = "
},
{
"path": "C++/Segment Tree/Segment Tree.cpp",
"chars": 960,
"preview": "void buildTree (int tree[],int array[], int index, int low, int high) {\n\tif (low == high)\n\t\ttree[index] = array[low];\n\te"
},
{
"path": "C++/Stacks - Queue/CircularQueue.cpp",
"chars": 1663,
"preview": "#include <iostream>\nusing namespace std;\nclass circular_queue\n{\n\tprivate :\n\t\tint *array ;\n\t\tint front, back ;\n\t\tint MAX;"
},
{
"path": "C++/String Algorithms/KMP.cpp",
"chars": 828,
"preview": "vector<int> computePrefix(string pat){\n int m = pat.size();\n vector<int> longestPrefix(m);\n for(int i = 1, k = "
},
{
"path": "C++/String Algorithms/Trie.cpp",
"chars": 653,
"preview": "struct Trie {\n\tTrie* child[26];\n\tbool isLeaf;\n\n\tTrie() {\n\t\tmemset(child, 0, sizeof(child));\n\t\tisLeaf = 0;\n\t}\n\n\tvoid push"
},
{
"path": "C++/Union Find/Union Find.cpp",
"chars": 1947,
"preview": "#include<iostream>\nusing namespace std;\n\nclass UnionFind {\n int *parent, *ranks, _size;\npublic:\n UnionFind(){\n "
},
{
"path": "LICENSE",
"chars": 11323,
"preview": "Apache License\n Version 2.0, January 2004\n http://www.apache.org/licens"
},
{
"path": "README.md",
"chars": 1596,
"preview": "\n<h2>Please visit my wiki link for full list of questions</h2>\n<h3>https://github.com/mission-peace/interview/wiki</h3>\n"
},
{
"path": "build.gradle",
"chars": 530,
"preview": "apply plugin: 'java'\napply plugin: 'idea'\napply plugin: 'eclipse'\napply plugin: \"jacoco\"\n\nsourceCompatibility = '1.8'\nta"
},
{
"path": "gradle/wrapper/gradle-wrapper.properties",
"chars": 231,
"preview": "#Sat Apr 02 16:59:09 PDT 2016\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
},
{
"path": "gradlew",
"chars": 4971,
"preview": "#!/usr/bin/env bash\n\n##############################################################################\n##\n## Gradle start "
},
{
"path": "python/array/arrayaddition.py",
"chars": 918,
"preview": "def add(arr1, arr2):\n\n l = max(len(arr1), len(arr2))\n result = [0 for j in range(l)]\n c = 0\n i = len(arr1) -"
},
{
"path": "python/array/commonthreesortedarray.py",
"chars": 761,
"preview": "# http://www.geeksforgeeks.org/find-common-elements-three-sorted-arrays/\n\ndef common_elements(input1, input2, input3):\n "
},
{
"path": "python/array/countinversionofsize3.py",
"chars": 574,
"preview": "# http://www.geeksforgeeks.org/count-inversions-of-size-three-in-a-give-array/\n\ndef find_inversions(input):\n inversio"
},
{
"path": "python/array/flip0smaximum1s.py",
"chars": 883,
"preview": "# http://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/\n\ndef flip_0s_to_"
},
{
"path": "python/array/longestsamesumspan.py",
"chars": 785,
"preview": "# http://www.geeksforgeeks.org/longest-span-sum-two-binary-arrays/\n# java code https://github.com/mission-peace/intervie"
},
{
"path": "python/array/maximumsumpathtwoarrays.py",
"chars": 1016,
"preview": "# http://www.geeksforgeeks.org/maximum-sum-path-across-two-arrays/\n\ndef max_sum(input1, input2):\n max_sum = 0\n i ="
},
{
"path": "python/array/maxproductsubarray.py",
"chars": 653,
"preview": "# http://www.geeksforgeeks.org/maximum-product-subarray/\n\ndef max_product(input):\n max_ending = 1\n min_ending = 1"
},
{
"path": "python/array/numberoftrianglesunsortedarray.py",
"chars": 492,
"preview": "# http://www.geeksforgeeks.org/find-number-of-triangles-possible/\n\ndef number_of_triangles(input):\n input.sort()\n "
},
{
"path": "python/array/positiveandnegativealternativelymaintainingorder.py",
"chars": 1127,
"preview": "# http://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/\n\ndef rearrange(input)"
},
{
"path": "python/array/rearrangearrayperindex.py",
"chars": 570,
"preview": "# http://www.geeksforgeeks.org/rearrange-array-arrj-becomes-arri-j/\n\ndef rearrange(input):\n for i in range(len(input)"
},
{
"path": "python/array/reorderarraybyindex.py",
"chars": 600,
"preview": "# http://www.geeksforgeeks.org/reorder-a-array-according-to-given-indexes/\n\ndef reorder(input, index):\n if len(input)"
},
{
"path": "python/array/rotationwithmaxsum.py",
"chars": 581,
"preview": "# http://www.geeksforgeeks.org/find-maximum-value-of-sum-iarri-with-only-rotations-on-given-array-allowed/\n\ndef max_sum("
},
{
"path": "python/array/smallestintegernotrepresentedbysubsetsum.py",
"chars": 374,
"preview": "# http://www.geeksforgeeks.org/find-smallest-value-represented-sum-subset-given-array/\n\ndef find_smallest_integer(input)"
},
{
"path": "python/array/tripletsumlessthantotal.py",
"chars": 531,
"preview": "# http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/\n\ndef find_all_triplet(input, total):\n"
},
{
"path": "python/array/zigzagarrangement.py",
"chars": 550,
"preview": "# http://www.geeksforgeeks.org/convert-array-into-zig-zag-fashion/\n\ndef rearrange(input):\n is_less = True\n for i i"
},
{
"path": "python/dynamic/bitonicsequence.py",
"chars": 1382,
"preview": "\"\"\"\nProblem Statement\n=================\n\nFind the length of the longest Bitonic Sequence in a given sequence of numbers."
},
{
"path": "python/dynamic/boxstacking.py",
"chars": 3218,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven different dimensions and unlimited supply of boxes for each dimension, st"
},
{
"path": "python/dynamic/breakword.py",
"chars": 4887,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven a string and a dictionary, split the string in to multiple words so that "
},
{
"path": "python/dynamic/coin_change_num_ways.py",
"chars": 2081,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven a total and coins of certain denominations find number of ways total can "
},
{
"path": "python/dynamic/coinchangingmincoins.py",
"chars": 2300,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven coins of certain denominations with infinite supply find minimum number o"
},
{
"path": "python/dynamic/count_num_A.py",
"chars": 1488,
"preview": "\"\"\"\nProblem Statement\n=================\n\nImagine you have a special keyboard with the following keys:\n\nKey 1: Prints 'A"
},
{
"path": "python/dynamic/count_num_binary_without_consec_1.py",
"chars": 608,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven a positive integer N, count all the numbers from 1 to 2^N, whose binary r"
},
{
"path": "python/dynamic/cutting_rod.py",
"chars": 1458,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven a rod of length n inches and an array of prices that contains prices of a"
},
{
"path": "python/dynamic/dice_throw_ways.py",
"chars": 1000,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven n dice each with m faces, numbered from 1 to m, find the number of ways t"
},
{
"path": "python/dynamic/editdistance.py",
"chars": 2241,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven two strings str1 and str2, find the minimum number of edits (edit one cha"
},
{
"path": "python/dynamic/egg_drop.py",
"chars": 1571,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven a certain number of eggs and a certain number of floors, determine the mi"
},
{
"path": "python/dynamic/knapsack_01.py",
"chars": 2542,
"preview": "\"\"\"\nProblem Statement\n=================\n\n0/1 Knapsack Problem - Given items of certain weights/values and maximum allowe"
},
{
"path": "python/dynamic/kth_ugly_number.py",
"chars": 1015,
"preview": "\"\"\"\nProblem Statement\n=================\n\nUgly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1"
},
{
"path": "python/dynamic/longest_common_subsequence.py",
"chars": 2129,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven two sequences A = [A1, A2, A3,..., An] and B = [B1, B2, B3,..., Bm], find"
},
{
"path": "python/dynamic/longest_common_substring.py",
"chars": 2273,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven two sequences A = [A1, A2, A3,..., An] and B = [B1, B2, B3,..., Bm], find"
},
{
"path": "python/dynamic/longest_increasing_subsequence.py",
"chars": 2565,
"preview": "\"\"\"\nProblem Statement\n=================\n\nFind a subsequence in given array in which the subsequence's elements are in so"
},
{
"path": "python/dynamic/longest_palindromic_subsequence.py",
"chars": 2016,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven a string find longest palindromic subsequence in this string.\n\nComplexity"
},
{
"path": "python/dynamic/matrix_chain_order.py",
"chars": 1424,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven an array p[] which represents the chain of matrices such that the ith mat"
},
{
"path": "python/dynamic/maximum_increasing_subsequence.py",
"chars": 956,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven an array of n positive integers. Write a program to find the sum of maxim"
},
{
"path": "python/dynamic/nth_fibonacci.py",
"chars": 663,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven the number n, find the nth fibanacci number.\n\nThe fibonacci series is 0, "
},
{
"path": "python/dynamic/num_bst.py",
"chars": 949,
"preview": "\"\"\"\nProblem Statement\n=================\nCount number of binary search trees created for array of size n. The solution is"
},
{
"path": "python/dynamic/num_paths_nm_matrix.py",
"chars": 978,
"preview": "\"\"\"\nProblem Statement\n=================\n\nCount the number of Paths from 1,1 to N,M in an NxM matrix.\n\nAnalysis\n--------\n"
},
{
"path": "python/dynamic/num_trees_preorder.py",
"chars": 1099,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven the number of nodes N, in a pre-order sequence how many unique trees can "
},
{
"path": "python/dynamic/optimal_bst.py",
"chars": 2400,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of"
},
{
"path": "python/dynamic/stockbuysellktransactions.py",
"chars": 3014,
"preview": "\"\"\"\"\nProblem Statement\n=================\n\nGiven certain stock values over a period of days (d days) and a number K, the "
},
{
"path": "python/dynamic/string_interleaving.py",
"chars": 2039,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven three strings A, B and C. Write a function that checks whether C is an in"
},
{
"path": "python/dynamic/sub_rectangular_maximum_sum.py",
"chars": 2209,
"preview": "\"\"\"\nProblem Statement\n=================\n\nWrite a program to find maximum sum rectangle in give 2D matrix. Assume there i"
},
{
"path": "python/dynamic/subset_sum.py",
"chars": 1537,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven an array of non negative numbers and a total, is there subset of numbers "
},
{
"path": "python/dynamic/symbolexpressionevaluation.py",
"chars": 2222,
"preview": "\"\"\"\nProblem Statement\n=================\n\nLet there be a binary operation for 3 symbols a, b, c and result of these binar"
},
{
"path": "python/dynamic/weighted_job_scheduling_max_profit.py",
"chars": 1192,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven set of jobs with start and end interval and profit, how to maximize profi"
},
{
"path": "python/geometry/skylinedrawing.py",
"chars": 1865,
"preview": "# https://leetcode.com/problems/the-skyline-problem/\n\nclass BuildingPoint(object):\n\n def __init__(self, point, is_sta"
},
{
"path": "python/graph/cycledirectedgraph.py",
"chars": 1233,
"preview": "# detect cycle in directed graph\n# https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/CycleI"
},
{
"path": "python/graph/cycleundirectedgraph.py",
"chars": 1629,
"preview": "# detect cycle in undirected graph\n# https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/Cycl"
},
{
"path": "python/graph/dijkstrashortestpath.py",
"chars": 1683,
"preview": "#dijkstra's algorithm\n\n# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/Dijkst"
},
{
"path": "python/graph/disjointset.py",
"chars": 1697,
"preview": "# disjoint sets\n# https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/DisjointSet.java\n\nclass"
},
{
"path": "python/graph/floydwarshall.py",
"chars": 1836,
"preview": "# floyd warshall all pair shortest path\n# java code https://github.com/mission-peace/interview/blob/master/src/com/inter"
},
{
"path": "python/graph/fordfulkerson.py",
"chars": 2115,
"preview": "#ford fulkerson method Edomonds Karp algorithm for finding max flow\n# java code https://github.com/mission-peace/intervi"
},
{
"path": "python/graph/graph.py",
"chars": 2564,
"preview": "#Graph class\n# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/Graph.java\n\nclas"
},
{
"path": "python/graph/graphtraversal.py",
"chars": 1109,
"preview": "#doing BFS and DFS traversal of the graph\n# java code https://github.com/mission-peace/interview/blob/master/src/com/int"
},
{
"path": "python/graph/kruskalmst.py",
"chars": 1224,
"preview": "# kruskal minimum spanning tree\n# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/gra"
},
{
"path": "python/graph/primmst.py",
"chars": 1619,
"preview": "#Prim's MST\n# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/PrimMST.java\n\nfro"
},
{
"path": "python/graph/priorityqueue.py",
"chars": 2850,
"preview": "# add to heapq things like removing any item and changing key value\n# implementation of priority queue to support contai"
},
{
"path": "python/graph/topologicalsort.py",
"chars": 905,
"preview": "#topological sort\n# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/Topological"
},
{
"path": "python/recursion/setpairtogether.py",
"chars": 1383,
"preview": "# http://www.geeksforgeeks.org/minimum-number-of-swaps-required-for-arranging-pairs-adjacent-to-each-other/\n\ndef find_mi"
},
{
"path": "python/recursion/stringpermutation.py",
"chars": 900,
"preview": "# string permutation in lexicographically order with repetition of characters in the string\n\ndef permute(input):\n cou"
},
{
"path": "python/string/Z_Algorithm.py",
"chars": 1438,
"preview": "#author: Pankaj Kumar\n\n#time complexity: O(length(string) + length(pattern))\n\n#space complexity: O(length(string) + leng"
},
{
"path": "python/string/knuthmorrispratt.py",
"chars": 1104,
"preview": "# Knuth-Morris-Pratt algorithm \n\n\n# Compute temporary array to maintain size of suffix which is same as prefix\n# Time/s"
},
{
"path": "python/string/rabinkarp.py",
"chars": 1598,
"preview": "#Rabin Karp algorithm\n# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/string/RabinK"
},
{
"path": "python/tree/binary_tree.py",
"chars": 1058,
"preview": "from collections import namedtuple\n\nColor = namedtuple(\"Color\", \"RED BLACK\")\n\n\nclass Node:\n def __init__(self):\n "
},
{
"path": "python/tree/construct_tree_from_inorder_preorder.py",
"chars": 704,
"preview": "from binary_tree import Node\n\n\nclass ConstructTreeFromInorderPreOrder:\n def __init__(self):\n self.index = 0\n\n "
},
{
"path": "python/tree/fenwick_tree.py",
"chars": 1849,
"preview": "########################################################################################################################"
},
{
"path": "python/tree/largest_bst_in_binary_tree.py",
"chars": 2324,
"preview": "\"\"\" Given a binary tree, find size of largest binary search subtree in this binary tree.\n\nApproach\n--------\n\nTraverse tr"
},
{
"path": "python/tree/max_depth_binary_tree.py",
"chars": 904,
"preview": "\"\"\"\nProblem Statement\n=================\n\nGiven a binary tree, write a program to find the maximum depth at any given nod"
},
{
"path": "python/tree/morris_traversal.py",
"chars": 2174,
"preview": "\"\"\"Morris Traversal of a Binary Tree.\n\nVideo\n-----\n\n* https://youtu.be/wGXB9OWhPTg\n\nAnalysis\n--------\n\n* Time complexity"
},
{
"path": "python/tree/segmenttreesum.py",
"chars": 2213,
"preview": "def create_segment_tree(input):\n size = next_power_of_2(len(input));\n segment_tree = [0 for x in range(2*size - 1)"
},
{
"path": "src/com/interview/array/AdditiveNumber.java",
"chars": 1694,
"preview": "package com.interview.array;\n\nimport java.math.BigInteger;\n\n/**\n * Date 04/24/2016\n * @author Tushar Roy\n *\n * Additive "
},
{
"path": "src/com/interview/array/ArrayAddition.java",
"chars": 1293,
"preview": "package com.interview.array;\n\npublic class ArrayAddition {\n\n public int[] add(int arr1[], int arr2[]){\n int l "
},
{
"path": "src/com/interview/array/BestMeetingPoint.java",
"chars": 1927,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\n/**\n * D"
},
{
"path": "src/com/interview/array/BuySellStockProfit.java",
"chars": 1372,
"preview": "package com.interview.array;\n\n/**\n * Date 03/04/2016\n * @author Tushar Roy\n *\n * Best time to buy and sell stocks.\n * 1)"
},
{
"path": "src/com/interview/array/CheckIfArrayElementsAreConsecutive.java",
"chars": 1086,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/check-if-array-elements-are-consecutive/\n */\npublic cl"
},
{
"path": "src/com/interview/array/ChunkMerge.java",
"chars": 4690,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.ut"
},
{
"path": "src/com/interview/array/CommonThreeSortedArray.java",
"chars": 1430,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Date 01/01/2016\n * @author Tush"
},
{
"path": "src/com/interview/array/ConvertAnArrayIntoDecreaseIncreaseFashion.java",
"chars": 1713,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n\n/**\n * Convert an unsorted array into an array such that\n * a <"
},
{
"path": "src/com/interview/array/CountInversionOfSize3.java",
"chars": 1178,
"preview": "package com.interview.array;\n\n/**\n * Date 12/29/15\n * @author Tushar Roy\n *\n * Given input array find number of inversio"
},
{
"path": "src/com/interview/array/CountSmallerOnRight.java",
"chars": 2505,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Date 03/01/2016\n * @author Tush"
},
{
"path": "src/com/interview/array/DivideNumbersInEqualGroupWithClosestSum.java",
"chars": 1641,
"preview": "package com.interview.array;\n\n/**\n * This solution is incorrect. It is greedy approach which will not work\n * e.g 1,6,6,"
},
{
"path": "src/com/interview/array/DuplicateNumberDetection.java",
"chars": 1022,
"preview": "package com.interview.array;\n\n/**\n * Date 03/04/2016\n * @author Tushar Roy\n *\n * Given an array of size n + 1 with eleme"
},
{
"path": "src/com/interview/array/DuplicateWithinkIndices.java",
"chars": 838,
"preview": "package com.interview.array;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\n/**\n * Write a function that determines w"
},
{
"path": "src/com/interview/array/FindElementsOccurringNByKTimesTetris.java",
"chars": 2207,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/given-an-array-of-of-size-n-finds-all-the-elements-tha"
},
{
"path": "src/com/interview/array/FirstPositiveMissing.java",
"chars": 1210,
"preview": "package com.interview.array;\n\n/**\n * https://leetcode.com/problems/first-missing-positive/\n */\npublic class FirstPositiv"
},
{
"path": "src/com/interview/array/Flip0sMaximum1s.java",
"chars": 1470,
"preview": "package com.interview.array;\n\n/**\n * Date 12/29/2015\n * @author Tushar Roy\n *\n * Given input array of 0s and 1s and numb"
},
{
"path": "src/com/interview/array/FourSum.java",
"chars": 3008,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport "
},
{
"path": "src/com/interview/array/GasStationCircle.java",
"chars": 2732,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/find-a-tour-that-visits-all-stations/\n * You can solve"
},
{
"path": "src/com/interview/array/GreedyTextJustification.java",
"chars": 5516,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Date 03/12/2016\n * @author Tush"
},
{
"path": "src/com/interview/array/GroupElementsInSizeM.java",
"chars": 2388,
"preview": "package com.interview.array;\n\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.u"
},
{
"path": "src/com/interview/array/HIndex.java",
"chars": 1323,
"preview": "package com.interview.array;\n\n/**\n * Given an array of citations (each citation is a non-negative integer) of a research"
},
{
"path": "src/com/interview/array/IncreasingSubsequnceOfLength3WithMaxProduct.java",
"chars": 2156,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/increasing-subsequence-of-length-three-with-maximum-pr"
},
{
"path": "src/com/interview/array/IncreasingTripletSubsequence.java",
"chars": 1228,
"preview": "package com.interview.array;\n\n/**\n * Date 03/06/2016\n * @author Tushar Roy\n *\n * Find if there exists an increasing trip"
},
{
"path": "src/com/interview/array/JumpGame.java",
"chars": 1673,
"preview": "package com.interview.array;\n\n/**\n * Date 07/31/2016\n * @author Tushar Roy\n *\n * Given an array of non-negative integers"
},
{
"path": "src/com/interview/array/KadaneWrapArray.java",
"chars": 2162,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/maximum-contiguous-circular-sum/\n * Test cases\n * All "
},
{
"path": "src/com/interview/array/KthElementInArray.java",
"chars": 1634,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Kth largest element in an array.\n * Use quickselect of qu"
},
{
"path": "src/com/interview/array/KthLargestInTwoSortedArray.java",
"chars": 3776,
"preview": "package com.interview.array;\n\n/**\n * http://stackoverflow.com/questions/4686823/given-2-sorted-arrays-of-integers-find-t"
},
{
"path": "src/com/interview/array/LargerElementOnRight.java",
"chars": 1623,
"preview": "package com.interview.array;\n\nimport java.util.Deque;\nimport java.util.LinkedList;\n\n/**\n * http://www.geeksforgeeks.org/"
},
{
"path": "src/com/interview/array/LargestMountain.java",
"chars": 1268,
"preview": "package com.interview.array;\n\n/**\n * https://leetcode.com/problems/longest-mountain-in-array/description/\n */\npublic cla"
},
{
"path": "src/com/interview/array/LargestSubArrayWithEqual0sAnd1s.java",
"chars": 1214,
"preview": "package com.interview.array;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * http://www.geeksforgeeks.org/large"
},
{
"path": "src/com/interview/array/LeetCodeCandy.java",
"chars": 1292,
"preview": "package com.interview.array;\n\n/**\n * References\n * https://leetcode.com/problems/candy/\n */\npublic class LeetCodeCandy {"
},
{
"path": "src/com/interview/array/LongestConsecutiveSubsequence.java",
"chars": 1216,
"preview": "package com.interview.array;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Date 12/03/2016\n * @author Tushar "
},
{
"path": "src/com/interview/array/LongestIncreasingSubSequenceOlogNMethod.java",
"chars": 2571,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Date 08/01/2015\n * @author Tushar Roy\n *\n * Given an arra"
},
{
"path": "src/com/interview/array/LongestSameSumSpan.java",
"chars": 1400,
"preview": "package com.interview.array;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Date 12/29/2015\n * @author Tushar "
},
{
"path": "src/com/interview/array/LongestSubstringWithAtMost2Char.java",
"chars": 1733,
"preview": "package com.interview.array;\n\n/**\n * Longest Substring with At Most Two Distinct Characters\n * https://leetcode.com/prob"
},
{
"path": "src/com/interview/array/MaxNumberFromTwoArray.java",
"chars": 2914,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\nimport java.util.Deque;\nimport java.util.LinkedList;\n\n/**\n * Date"
},
{
"path": "src/com/interview/array/MaxProductSubarray.java",
"chars": 1651,
"preview": "package com.interview.array;\n\n/**\n * Date 04/`7/2016\n * @author Tushar Roy\n *\n * Find the contiguous subarray within an "
},
{
"path": "src/com/interview/array/MaxRepeatingNumber.java",
"chars": 1086,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/find-the-maximum-repeating-number-in-ok-time/\n * Given"
},
{
"path": "src/com/interview/array/MaximumGap.java",
"chars": 2000,
"preview": "package com.interview.array;\n\n/**\n * Date 03/12/2016\n * @author Tushar Roy\n *\n * Given an unsorted array find maximum ga"
},
{
"path": "src/com/interview/array/MaximumIminusJSuchThatAiGTAj.java",
"chars": 1413,
"preview": "package com.interview.array;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\n\n/**\n * http://www.geeksforgeeks.o"
},
{
"path": "src/com/interview/array/MaximumMinimumArrangement.java",
"chars": 1172,
"preview": "package com.interview.array;\n\n/**\n * Date 04/16/2016\n * @author Tushar Roy\n *\n * Given a sorted array of positive intege"
},
{
"path": "src/com/interview/array/MaximumOfSubarrayOfSizeK.java",
"chars": 2122,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/maximum-of-all-subarrays-of-size-k/\n * Test cases\n * i"
},
{
"path": "src/com/interview/array/MaximumSumPathTwoArrays.java",
"chars": 1776,
"preview": "package com.interview.array;\n\n/**\n * Date 12/31/2015\n * @author Tushar Roy\n *\n * Given two sorted arrays such the arrays"
},
{
"path": "src/com/interview/array/MaximumSumThreeNonOverlappingSubarray.java",
"chars": 2142,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\nimport java.util.Deque;\nimport java.util.LinkedList;\nimport java."
},
{
"path": "src/com/interview/array/MeetingRooms.java",
"chars": 1958,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\nimport java.util.PriorityQueue;\n\n/**\n * Date 05/01/2016\n * @autho"
},
{
"path": "src/com/interview/array/MinimumDistanceBetweenTwoNumbers.java",
"chars": 1382,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/find-the-minimum-distance-between-two-numbers/\n */\npub"
},
{
"path": "src/com/interview/array/MinimumNumberFromSequence.java",
"chars": 1398,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Date 02/26/2016\n * @author Tushar Roy\n *\n * Time complexi"
},
{
"path": "src/com/interview/array/MinimumSortedWhichSortsEntireArray.java",
"chars": 1437,
"preview": "package com.interview.array;\n\n/**\n *http://www.geeksforgeeks.org/minimum-length-unsorted-subarray-sorting-which-makes-th"
},
{
"path": "src/com/interview/array/MissingRanges.java",
"chars": 1406,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\n/**\n * G"
},
{
"path": "src/com/interview/array/MoveAllZerosToEnd.java",
"chars": 713,
"preview": "package com.interview.array;\n\npublic class MoveAllZerosToEnd {\n\n public void moveZeros(int arr[]){\n int slow ="
},
{
"path": "src/com/interview/array/MultiplyAllFieldsExceptOwnPosition.java",
"chars": 621,
"preview": "package com.interview.array;\n\n/**\n * https://leetcode.com/problems/product-of-array-except-self/\n */\npublic class Multip"
},
{
"path": "src/com/interview/array/NthElementOfCountNumberSequence.java",
"chars": 1421,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Date 07/20/2015\n * @author Tush"
},
{
"path": "src/com/interview/array/NumberOfTrianglesInUnsortedArray.java",
"chars": 872,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * http://www.geeksforgeeks.org/find-number-of-triangles-pos"
},
{
"path": "src/com/interview/array/PositiveAndNegativeNumberAlternatively.java",
"chars": 1264,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/rearrange-positive-and-negative-numbers-publish/\n */\np"
},
{
"path": "src/com/interview/array/PositiveAndNegativeNumberAlternativelyMaintainingOrder.java",
"chars": 2096,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Date 12/31/2015\n * @author Tushar Roy\n *\n * Given an arra"
},
{
"path": "src/com/interview/array/RearrangeArrayPerIndex.java",
"chars": 1291,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Date 12/30/2015\n *\n * Given an array of size n where elem"
},
{
"path": "src/com/interview/array/RearrangeSuchThatArriBecomesArrArri.java",
"chars": 889,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/rearrange-given-array-place/\n */\npublic class Rearrang"
},
{
"path": "src/com/interview/array/ReorderArrayByIndex.java",
"chars": 1363,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Date 12/29/2015\n * @author Tushar Roy\n *\n * Given two arr"
},
{
"path": "src/com/interview/array/RepeatingAndMissingNumber.java",
"chars": 1089,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/find-a-repeating-and-a-missing-number/\n */\npublic clas"
},
{
"path": "src/com/interview/array/RotationWithMaxSum.java",
"chars": 1055,
"preview": "package com.interview.array;\n\n/**\n * Date 12/30/2015\n * @author Tushar Roy\n *\n * Given an input array find which rotatio"
},
{
"path": "src/com/interview/array/SelfCrossing.java",
"chars": 1076,
"preview": "package com.interview.array;\n\n/**\n * Created by tushar_v_roy on 3/10/16.\n */\npublic class SelfCrossing {\n\n public boo"
},
{
"path": "src/com/interview/array/ShortestPalindrome.java",
"chars": 2117,
"preview": "package com.interview.array;\n\n/**\n * Date 03/04/2016\n * @author Tushar Roy\n *\n * How to append minimum numbers of charac"
},
{
"path": "src/com/interview/array/SmallestIntegerNotRepresentedBySubsetSum.java",
"chars": 1462,
"preview": "package com.interview.array;\n\n/**\n * Date 12/31/2015\n * @author Tushar Roy\n *\n * Given array in non decreasing order fin"
},
{
"path": "src/com/interview/array/SmallestSubarrayWithAtleastKSum.java",
"chars": 1455,
"preview": "package com.interview.array;\n\n/**\n * https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/description/\n *"
},
{
"path": "src/com/interview/array/SortedArrayTransformation.java",
"chars": 1144,
"preview": "package com.interview.array;\n\n/**\n * Date 10/08/2016\n * @author Tushar Roy\n *\n * Given a sorted array of integers nums a"
},
{
"path": "src/com/interview/array/StableMarriageProblem.java",
"chars": 2525,
"preview": "package com.interview.array;\n\npublic class StableMarriageProblem {\n\n private boolean checkIfNewIsBetter(int priority["
},
{
"path": "src/com/interview/array/SubarrayWithGivenSum.java",
"chars": 1165,
"preview": "package com.interview.array;\n\n/**\n * http://www.geeksforgeeks.org/find-subarray-with-given-sum/\n */\npublic class Subarra"
},
{
"path": "src/com/interview/array/SummaryRanges.java",
"chars": 1476,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\n/**\n * D"
},
{
"path": "src/com/interview/array/ThreeSumSmallerThanTarget.java",
"chars": 894,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Given an array of n integers nums and a target, find the "
},
{
"path": "src/com/interview/array/TrappingWater.java",
"chars": 1135,
"preview": "package com.interview.array;\n/**\n * References\n * https://oj.leetcode.com/problems/trapping-rain-water/\n * https://leetc"
},
{
"path": "src/com/interview/array/TripletInArray.java",
"chars": 2614,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * http:/"
},
{
"path": "src/com/interview/array/TripletSumLessThanTotal.java",
"chars": 1051,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Date 12/29/2015\n * @author Tushar Roy\n *\n * Given array w"
},
{
"path": "src/com/interview/array/TugOfWar.java",
"chars": 1315,
"preview": "package com.interview.array;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/*\n * http://www.geeksforgeeks.org/tug"
},
{
"path": "src/com/interview/array/WaterContainer.java",
"chars": 878,
"preview": "package com.interview.array;\n\n/**\n * Given n non-negative integers a1, a2, ..., an, where each represents a point at coo"
},
{
"path": "src/com/interview/array/WiggleSort.java",
"chars": 2133,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Date 03/23/2016\n * @author Tushar Roy\n *\n * Convert an un"
},
{
"path": "src/com/interview/array/ZigZagArrangement.java",
"chars": 1185,
"preview": "package com.interview.array;\n\nimport java.util.Arrays;\n\n/**\n * Date 12/30/2015\n * @author Tushar Roy\n *\n * Given an arra"
},
{
"path": "src/com/interview/binarysearch/ArithmeticProgressionSearch.java",
"chars": 976,
"preview": "package com.interview.binarysearch;\n\n/**\n * http://www.careercup.com/question?id=4798365246160896\n */\npublic class Arith"
},
{
"path": "src/com/interview/binarysearch/BinarySearch.java",
"chars": 915,
"preview": "package com.interview.binarysearch;\n\n/**\n * Regular binary search\n */\npublic class BinarySearch {\n\n public int search"
},
{
"path": "src/com/interview/binarysearch/CircularBinarySearch.java",
"chars": 2509,
"preview": "package com.interview.binarysearch;\n\n/**\n * http://www.careercup.com/question?id=4877486110277632\n * Given a circle with"
},
{
"path": "src/com/interview/binarysearch/CountNDistinctPairsWithDifferenceK.java",
"chars": 1131,
"preview": "package com.interview.binarysearch;\n\nimport java.util.Arrays;\n\n/**\n * http://www.geeksforgeeks.org/count-pairs-differenc"
},
{
"path": "src/com/interview/binarysearch/FirstOccurrenceOfNumberInSortedArray.java",
"chars": 902,
"preview": "package com.interview.binarysearch;\n\n/**\n * http://www.geeksforgeeks.org/check-for-majority-element-in-a-sorted-array/\n "
},
{
"path": "src/com/interview/binarysearch/FloorAndCeilingSortedArray.java",
"chars": 1391,
"preview": "package com.interview.binarysearch;\n\n/**\n * http://www.geeksforgeeks.org/search-floor-and-ceil-in-a-sorted-array/\n */\npu"
},
{
"path": "src/com/interview/binarysearch/MedianOfTwoSortedArray.java",
"chars": 1860,
"preview": "package com.interview.binarysearch;\n\n/**\n * http://www.geeksforgeeks.org/median-of-two-sorted-arrays/\n */\npublic class M"
},
{
"path": "src/com/interview/binarysearch/MedianOfTwoSortedArrayOfDifferentLength.java",
"chars": 3241,
"preview": "package com.interview.binarysearch;\n\n/**\n * There are two sorted arrays nums1 and nums2 of size m and n respectively.\n *"
},
{
"path": "src/com/interview/binarysearch/MinimumInSortedRotatedArray.java",
"chars": 691,
"preview": "package com.interview.binarysearch;\n\n/**\n * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n */\npubl"
},
{
"path": "src/com/interview/binarysearch/MissingNumberInConsecutiveNumbers.java",
"chars": 1014,
"preview": "package com.interview.binarysearch;\n\n/**\n * Find missing number in consecutive numbers.\n */\npublic class MissingNumberIn"
},
{
"path": "src/com/interview/binarysearch/MonotonicallyIncreasingFunctionBecomesPositive.java",
"chars": 1095,
"preview": "package com.interview.binarysearch;\n\n/**\n * http://www.geeksforgeeks.org/find-the-point-where-a-function-becomes-negativ"
},
{
"path": "src/com/interview/binarysearch/NumberOfPairWithXPowerYGreaterThanYPowerX.java",
"chars": 2201,
"preview": "package com.interview.binarysearch;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * ht"
},
{
"path": "src/com/interview/binarysearch/PeakElement.java",
"chars": 1479,
"preview": "package com.interview.binarysearch;\n\n/**\n * @author Tushar Roy\n * Date 01/17/2107\n * A peak element is an element that i"
}
]
// ... and 446 more files (download for full content)
About this extraction
This page contains the full source code of the mission-peace/interview GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 646 files (1.2 MB), approximately 332.2k tokens, and a symbol index with 2811 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.