├── README.md ├── images ├── AmortizedAnalysis2.png ├── Arbitrage.png ├── ArrayList_Amortised1.png ├── ArticulationPoints.png ├── ArticulationPointsEx.png ├── BFS.png ├── BinaryTreeHeight.png ├── BridgesInA GraphExample.png ├── Complete Bipartite graph.png ├── DFA construction KMP.png ├── DFS.png ├── Diagnol SUM.jpg ├── DijKstrasoln.jpg ├── Dijkstras.jpg ├── EdgeWeightedDAG-For job scheduling.png ├── EulerianUndirected │ ├── Euler1.png │ ├── Euler2.png │ └── Euler3.png ├── Floyd-Warshall.jpg ├── GrahamScanFullAlgo.png ├── IntervalTree.png ├── LRS.png ├── LRU.png ├── LSD Sort example.png ├── MotherVertex2.png ├── NQueen.png ├── Number_Of_Islands.png ├── SearchCost.png ├── ShortestPathDAG.png ├── SieveOfEratosthenes.png ├── StringPermutation.gif ├── Ternary-Search-Tree.png ├── TopologicalSort.png ├── TrapWater.png ├── UFTimeComplexity.png ├── UniqueBST2.GIF ├── UniquesBST1.GIF ├── ancestorMatrixToBinaryTree.jpg ├── bipartite.png ├── flattenList.png ├── grahamScanSortPoints.png ├── intersecting1.png ├── intersecting2.png ├── intersecting3.png ├── java-map-collection-cheat-sheet.gif ├── max Sum path.png ├── maximum-sum-of-subarray-close-to-k.png ├── mergeSort.png ├── minCutImage.png ├── minimum iterations.png ├── motherIndex1.png ├── mst │ ├── KrushkalsAlgo.gif │ ├── MSTComplexities.png │ └── PrimsAlgo.gif ├── nextLeafNode.jpg ├── nfaConstructionRegex.png ├── orientation_of_3_points.png ├── polygonPontInside.png ├── rabinkarp.png ├── relaxation-edge.png ├── stateDiagram.jpg ├── stringCircle.png ├── symbolGraph.png ├── tilingProblem2.jpg └── word-break-II-java.png ├── notes ├── 2'sComplement ├── AdjacencyListVsGraphs ├── AmortisedAnalysis ├── Angle Between Hour And Minute Hand ├── ArraysVsGenerics ├── AssemblyLine ├── AssignDirections ├── BST_vs_Hashing.txt ├── BackTracking ├── BigIntegerJava ├── BinaryTreeProperties ├── BuildHeapComplexity ├── BuildingBridges.txt ├── Catlan No ├── CircleIntersection ├── ComparatorAndComparable ├── CountTrailingZeroes ├── DFS_vs_TopologicalSort ├── DSDesignProblem ├── EdgeRelaxation ├── Euclids lema ├── Euiler_Circuit ├── FindLSB&MSB ├── FirstComeFirstServe ├── Floyd Cycle Detection ├── HeightOfBinaryTree ├── IntegersOppositeSign ├── JaggedArray.txt ├── Java pass By Value ├── JollyJumper ├── LazyCarterProblem ├── Lexicographic order.txt ├── MST_properties ├── MinValue ├── Minimum Number Of Flips ├── Minimum no. of iterations ├── MultiplyBy7 ├── Mutex&Semaphore ├── NearlyKSortedArrays ├── NegativeCyclesBellmanFord ├── NetworkFlowAndImplementations.pdf ├── NumberOfBSTs ├── OddNoOfTimes ├── OptimalSubStructure.txt ├── Order_statistics.ppt ├── PascalTriangle.txt ├── PrimsVsKrishkals ├── RandomPointer ├── Remove duplicates ├── RotatedStrings ├── Round Robin ├── SSCkosaraju ├── ScannerClass ├── SuffixTree.txt ├── TileFloorDP ├── Tiling Problem ├── TopKTrending words ├── TurnOffRSB ├── TwoNonRepeatingelements ├── UnionFindVsDFS ├── ValidPermutationParenthesis ├── XORElemntsRange ├── articulationPoints.pdf ├── backtracking.ppt ├── bfs_dfs ├── booleanArray ├── graphRepresentation.txt ├── heapsort-analysis-part.pdf ├── maxflowPrinceton.pdf ├── network-flow-problems.pdf └── weight_shechuding.pdf └── src ├── arrays ├── BitonicSubArray.java ├── BooleanArray.java ├── CountDistinctElementsWindow.java ├── CountFrequencies.java ├── CountingSort.java ├── DuplicateElementsKDistance.java ├── EquilibriumIndex.java ├── Find3ClosestElements.java ├── FindPair.java ├── FindTwoElementsGivenSum.java ├── FlipSubArrayForMaxZeroes.java ├── FourSum.java ├── GenerateSubSets.java ├── GroupMultipleOccurrence.java ├── Itinerary.java ├── KFrequentWords.java ├── LargestSubArrayZeroSum.java ├── LargestSumPair.java ├── LongestConsecutiveSequence.java ├── MajorityElement.java ├── MakeElementsequal.java ├── MaxDifference.java ├── MaximumAverageSubArray.java ├── MaximumDiffOfIndices.java ├── MaximumMinimum.java ├── MaximumOfAllSubArrays.java ├── MaximumProductPair.java ├── MinDistanceElements.java ├── MinimumFlipsReq.java ├── MinimumLengthUnsorted.java ├── MinimumNumberOfMoves.java ├── NextGreatest.java ├── NextGreatestNumber.java ├── NutsBolts.java ├── PancakeSorting.java ├── PossibleStringWithSpaces.java ├── PythagoreanTriplet.java ├── RearrangeEvenOdd.java ├── RearrangeItemsArray.java ├── RearrangePosNeg.java ├── RearrangePosNegOrder.java ├── ReplaceZeroes.java ├── SearchDifferenceOne.java ├── ShuffleArray.java ├── StockBuyAndSell.java ├── SubArrayGivenSum.java ├── SubArraySumNegative.java ├── SubarraySumCloseK.java ├── SummaryRanges.java ├── TripletSum.java ├── TripletsArray.java ├── binarysearching │ ├── BestFitBox.java │ ├── ElementAppearingOddTimes.java │ ├── FindElementIncDecArray.java │ ├── FindKClosestElements.java │ ├── FixedPoint.java │ ├── InfiniteSortedArray.java │ ├── MaxElementIncreasingDecreasingArray.java │ ├── PaintersProblem.java │ ├── PeakElementInAnArray.java │ ├── RotatedPivotedArray.java │ └── SortedArrayFrequency.java ├── leadersArray.java ├── sorting │ ├── Insertion.java │ ├── IterativeMergeSort.java │ └── Merge.java └── twodimensionalarrays │ ├── AntiDiagonals.java │ ├── BooleanMatrix.java │ ├── CommonElements.java │ ├── FillRandomizedArray.java │ ├── PrintAllPaths.java │ ├── Search2DSorted.java │ ├── SpiralPrintingMatrix.java │ ├── SumExceptOneMatrix.java │ ├── SumOfSubMatrix.java │ └── ToeplitzMatrix.java ├── backtracking ├── KnightsTour.java ├── NQueen.java ├── RatInMaze.java └── ShortestPathMaze.java ├── bitmanuplation ├── AddOne.java ├── AddTwoNumbers.java ├── AppearOnce.java ├── BitsFlipped.java ├── CountSetBits.java ├── ModularExponentiation.java ├── MultipleOfThree.java ├── NextPowerOfTwo.java ├── Parity.java ├── PowerOfTwo.java └── PrintPowerSet.java ├── dyanamicprogramming ├── AllWaysToAddParenthesis.java ├── BinaryStrings.java ├── BreakIntoThreeParts.java ├── ChoiceOfArea.java ├── CircularSubArraySum.java ├── CountAllPalindromeSubStr.java ├── CountDerangements.java ├── CountDistinctPalindrome.java ├── CountDistinctSubsequences.java ├── CountWaysToReachStairs.java ├── CutStrings.java ├── CuttingRod.java ├── FibonacciNumbers.java ├── FindMinSum.java ├── FindStrings.java ├── HighEffortVsLowEffort.java ├── HighwayBillBoard.java ├── KPalindrome.java ├── KadanesAlgorithm.java ├── Knapsack.java ├── LargestSubMatrixSum.java ├── LongestBitonicSubSeq.java ├── LongestPalindromicSubSequence.java ├── MaxSumNonContinuous.java ├── MinimumCoinsChange.java ├── MinimumNumberOfJumps.java ├── NonRepeatCharSubStr.java ├── NumberOfStations.java ├── NumberOfWays.java ├── OptimalStrategy.java ├── PartitionEqualSubsetSum.java ├── PossibleDecoding.java ├── PrintMaximumAs.java ├── ReachScore.java ├── RoundHouseRobbery.java ├── SetOfDenominations.java ├── SumAndDigits.java ├── UglyNumber.java ├── UnboundedKnapsack.java ├── WeightedJobScheduling.java ├── WordBreakDP.java ├── WordBreakProblem.java ├── lcs │ ├── AllLcs.java │ ├── LongestCommonSubSequence.java │ ├── LongestCommonSubString.java │ ├── MinInsertionsPalindrome.java │ └── PrintLCS.java ├── lis │ ├── ChainOfPairs.java │ ├── CircusTower.java │ ├── LongestIncreasingSubSequence.java │ ├── LongestSubSeqAdjacentDifferenceOne.java │ └── MaximumSumIncSubSeq.java └── matrix │ ├── CountAllPaths.java │ ├── CountPaths.java │ ├── CountPathsWithTurns.java │ ├── GoldMine.java │ ├── LongestPathMatrix.java │ ├── MaxSquareEqualElements.java │ ├── MaximumAverageValue.java │ ├── MaximumDecimalValue.java │ ├── MaximumWeightPath.java │ ├── MinimumCostPath.java │ ├── MinimumCostToReachDestination.java │ ├── PalindromicPaths.java │ ├── PathWithKCoins.java │ └── SnakeSequence.java ├── geometry ├── ConvexHull1.java ├── GrahamScan.java ├── IntersectingLines.java ├── Orientation.java ├── Point.java └── PointInside.java ├── graphs ├── AcyclicLP.java ├── AcyclicSP.java ├── Arbitrage.java ├── ArticulationPoints.java ├── BellmanFordSP.java ├── BipartiteGraph.java ├── BreadthFirstPaths.java ├── BreadthFirstSearchIterative.java ├── Bridges.java ├── Catch.java ├── CheckPath.java ├── ConnectedComponents.java ├── CountIslands.java ├── CountPaths.java ├── CriticalPathMethod.java ├── DepthFirstOrders.java ├── DepthFirstSearchIterative.java ├── DepthFirstSearchPaths.java ├── DepthFirstSearchRecursive.java ├── DetectCycleDiGraph.java ├── DijikstrasAdjMatrix.java ├── DijkstraShortestPath.java ├── EdgeWeightedDirectedCycle.java ├── EulerianUndirected.java ├── FloydWarshall.java ├── FordFulkerson.java ├── FordFulkersonMaxFlowAdjMatrix.java ├── GeneratePossibleCombinations.java ├── HamiltonianCycle.java ├── JumpingNumbers.java ├── KahnsAlgo.java ├── MinimumSTCut.java ├── MinimumSteps.java ├── MotherVertex.java ├── PrintPaths.java ├── SCCKosaraju.java ├── SecondDegreeConnections.java ├── ShortestPath.java ├── SortedDictionary.java ├── StringChainedCircle.java ├── Topological.java ├── WordLadder.java ├── mst │ ├── KruskalMST.java │ ├── LazyPrimMST.java │ ├── PrimMst.java │ └── PrimsMSTAdjMatrix.java ├── search │ ├── Boggle.java │ ├── CountIslandRowCol.java │ ├── FindStrings.java │ ├── FloodFill.java │ ├── KnightPositionChess.java │ ├── MatrixProbability.java │ ├── ReplaceXO.java │ ├── SearchWord2DArray.java │ ├── SnakeLadderGame.java │ ├── StringInsideMatrix.java │ ├── StringPuzzle.java │ └── TimeToRotOrange.java └── unionFind │ ├── DetectCycleUF.java │ ├── QuickFindUF.java │ ├── UF.java │ └── WeightedQuickUnionUF.java ├── greedyProgramming ├── ActivitySelectionProblem.java ├── MinimizeCashFlow.java └── TempleOfferings.java ├── inputFiles ├── BFInput ├── CPMInput ├── FordFulkersonInput ├── mediumEWG.txt ├── mediumUF.txt ├── mobydick.txt ├── movies.txt ├── newinput.txt ├── rates.txt ├── routes.txt ├── tinyCG.txt ├── tinyEWG.txt └── tinyUF.txt ├── interviews ├── BossEmployee.java ├── CollectDiamonds.java ├── Directions.java ├── MinimumStrips.java ├── NewDS.java ├── RoomFloors.java ├── RotateArray.java ├── SenderReciever.java └── SumOfDependencies.java ├── linkedlist ├── CustomSortLinkList.java ├── DetectAndRemoveLoop.java ├── FlattenLinkList2.java ├── FlattenMultiLevelList.java ├── Palindrome.java ├── RequiredClasses.java ├── ReverseLinkListGroup.java └── ReverseLinkedListWithRandomPointers.java ├── miscellaneous ├── BinomialCoefficient.java ├── BuildLowestNo.java ├── CalculateMappedStringEquation.java ├── CircularTour.java ├── ComputerSimulation.java ├── CountInversions.java ├── DataStructureDesign.java ├── DaysBetween.java ├── DigitsAfterDecimal.java ├── FirstNonRepeatingCharacterStream.java ├── GenerateSumSubSets.java ├── HornersMethod.java ├── ImplementTwoStacksArray.java ├── InMemoryFileSystem.java ├── JosephusProblem.java ├── LRUCache.java ├── LargeNumberFactorial.java ├── LargestMultipleOfThree.java ├── LongestEvenSubString.java ├── MaxTreeSum.java ├── MaximumSwaps.java ├── MinimumStrengthReq.java ├── NestedParenthesis.java ├── NewNumberSystem.java ├── NextBiggerPalindrome.java ├── NumberOfEmployees.java ├── NumberOfTriangles.java ├── OverlapIntervals.java ├── PrintMaximumAs.java ├── PrintPrimeFactors.java ├── RandomNoProbabilityDistribution.java ├── RearrangeParkingLot.java ├── RemoveMinimumElements.java ├── RobotMotion.java ├── RussianPeasantMultiply.java ├── SecondHandClockArea.java ├── SieveofEratosthenes.java ├── SubsetCondition.java ├── ThreadConflicts.java ├── TinyUrl.java ├── TransformStrings.java ├── TrappingWater.java ├── WaterInGlass.java └── WaveForm.java ├── stack ├── CelebrityProblem.java ├── CheckBalancedParenthesis.java ├── FirstGreaterNumberOnLeft.java ├── Histogram2.java ├── NextGreaterElement.java ├── QueueUsing2Stacks.java ├── SpecialStackImplementation.java ├── StackUsingTwoQueues.java └── StockSpanProblem.java ├── strings ├── AnagramDiff.java ├── ArrayOfSuffixes.java ├── CheckInterleaving.java ├── CircularSequence.java ├── CountWords.java ├── ExcelColumn.java ├── FindSubStr.java ├── FollowsPattern.java ├── GrammarRules.java ├── LexicographicLowestString.java ├── LongestCommonPrefix.java ├── LongestRepeatedSubstring.java ├── LongestSubStringKUniqueChars.java ├── MinimizeStringValue.java ├── MinimumWindow.java ├── PalindromeChunks.java ├── PrintAnagrams.java ├── RemoveAdjacentDuplicates.java ├── RemoveCharacterPalindrome.java ├── RemoveChars.java ├── RemoveDuplicates.java ├── RemoveExtraSpaces.java ├── RemoveSpaces.java ├── RepeatedSubSequence.java ├── RepeatedSubstring.java ├── RunLengthEncoding.java ├── ShortestSuperString.java ├── SortedAccordingToArray.java ├── SpecificPatternMatch.java ├── StringFormation.java ├── Subsequence.java ├── SuffixArray.java ├── SuffixArrayX.java ├── UncompressedString.java ├── ZigZagConcatenation.java ├── print │ ├── GeneralizedAbbreviation.java │ ├── GenerateBinaryStrings.java │ ├── MappedDigits.java │ ├── PermutationOfString.java │ ├── PrintInterLeavings.java │ ├── PrintParenthesis.java │ ├── PrintPatterns.java │ ├── RecursivePrint.java │ └── StringUsingSpaces.java ├── stringsorts │ ├── KeyIndexCounting.java │ └── LSDSort.java └── substringsearch │ ├── BoyerMoore.java │ ├── BruteForce.java │ ├── KMP.java │ ├── RabinKarp.java │ └── ZAlgorithm.java ├── trees ├── heap │ ├── CheckArrayHeap.java │ ├── ConnectNRopes.java │ ├── EfficientDS.java │ ├── KLargestElements.java │ ├── KthLargestElementStream.java │ ├── KthSmallestArrayElement.java │ ├── MaxNumber.java │ ├── MergeKSortedArrays.java │ ├── MinToMaxHeap.java │ ├── SortMachineNo.java │ └── StreamMedian.java ├── segmentTrees │ ├── RangeMinimumQuery.java │ └── SumRange.java ├── specialTrees │ ├── ConflictingAppointments.java │ └── IntervalTreeImplementation.java ├── tree │ ├── AddGreaterValues.java │ ├── ArrayToBST.java │ ├── BSTCeil.java │ ├── BSTOneNode.java │ ├── BST_LCA.java │ ├── BTCLList.java │ ├── BinaryTreeToBST.java │ ├── BottomView.java │ ├── BoundaryTraversal.java │ ├── BuildTreeFromAncestor.java │ ├── BuildTreeInorder.java │ ├── CheapestBranch.java │ ├── CheckBST.java │ ├── CheckBalancedBT.java │ ├── CheckLeavesLevel.java │ ├── ChildrenSumProperty.java │ ├── CloneBT.java │ ├── ClosestLeaf.java │ ├── Collision.java │ ├── CompleteBT.java │ ├── ConnectDeepestRightLeaf.java │ ├── ConnectNodes.java │ ├── ConstructTree1.java │ ├── ConstructTreeFromParent.java │ ├── ConvertToSumTree.java │ ├── CountLeaves.java │ ├── CountNodesRange.java │ ├── CousinsBT.java │ ├── DeepestLeftLeaf.java │ ├── DeepestOddLeaf.java │ ├── DeleteNodeBST.java │ ├── DiagonalSum.java │ ├── DistanceTwoNodes.java │ ├── DoubleTree.java │ ├── DuplicateSubTree.java │ ├── FindPossibleInterpretations.java │ ├── FixSwapNodes.java │ ├── FoldableTree.java │ ├── FullBinaryTree.java │ ├── GetLevel.java │ ├── IdenticalTrees.java │ ├── IdenticalTrees2.java │ ├── InorderIterator.java │ ├── InorderSuccessor.java │ ├── Isomorphic.java │ ├── KDistanceNodes.java │ ├── KthSmallestElement.java │ ├── LCAMain.java │ ├── LargestDistanceBetweenTwoNodes.java │ ├── LeavesToDLL.java │ ├── LeftView.java │ ├── LevelOrderTraversal.java │ ├── LowestCommonAncestor1.java │ ├── MaxSumPath.java │ ├── MaxSumPathBT.java │ ├── MaximumConsecutivePath.java │ ├── MaximumLeavesSum.java │ ├── MedianBST.java │ ├── MergeBST.java │ ├── MinimumElementAtADepth.java │ ├── MinimumIterations.java │ ├── MirrorTree.java │ ├── MorrisTraversal.java │ ├── MultiplicationSumOfDataLeaves.java │ ├── NextRightNode.java │ ├── NoSibling.java │ ├── Node.java │ ├── NonRecursiveTraversal.java │ ├── OnlyLeftLeaves.java │ ├── PairWithSum.java │ ├── ParentArrayBT.java │ ├── PathSum.java │ ├── PreOrderBST2.java │ ├── PreOrderSuccessor.java │ ├── PreorderBST.java │ ├── PreorderSpecialTree.java │ ├── PrintAncestors.java │ ├── PrintArrayEncoding.java │ ├── PrintNodesAtKDistance.java │ ├── PrintRangeKeys.java │ ├── PrintVerticalOrder.java │ ├── QueueLevelOrderTraversal.java │ ├── RemoveHalfNodes.java │ ├── RemoveKDistanceNodes.java │ ├── RemoveNodes.java │ ├── RequiredClasses.java │ ├── ReturnNextLeafNode.java │ ├── ReverseAlternateNodesBT.java │ ├── ReverseLevelOrder.java │ ├── ReverseLevelOrderTraversal.java │ ├── RootToLeaf.java │ ├── RootToLeafPathSum.java │ ├── RootToLeafSum.java │ ├── SortedArrayToBST.java │ ├── SpecialBT1.java │ ├── SpecifiedSum.java │ ├── SpiralLevelOrder.java │ ├── SubTree.java │ ├── SubTree2.java │ ├── SumDifference.java │ ├── SumOfLeftLeaves.java │ ├── SumTree.java │ ├── SwappedNodes.java │ ├── TopView.java │ ├── TraversalsRecursive.java │ ├── TreeDiameter.java │ ├── TreeHeight.java │ ├── TreeListRecursion.java │ ├── TreeToDLL1.java │ ├── TreeToDLL2.java │ ├── TreeToSumTree.java │ ├── TripletSum.java │ └── VerticalSum.java └── tries │ ├── ForwardDNSLookUp.java │ ├── MatchCamelCase.java │ ├── PrintAnagrams.java │ ├── ReverseDNSLookUp.java │ ├── ShortestUniquePrefix.java │ ├── TernarySearchTrees.java │ └── UniqueURL.java └── utility ├── Bag.java ├── DLLNode.java ├── DoublyLinkList.java ├── GetInputFile.java ├── LongestCommonPrefix.java ├── LpsComputation.java ├── Queue.java ├── SortFunctions.java ├── Stack.java ├── Suffix.java ├── Trie.java ├── edgeClasses ├── DirectedEdge.java ├── Edge.java └── FlowEdge.java ├── graphClasses ├── Digraph.java ├── EdgeWeightedDigraph.java ├── EdgeWeightedGraph.java ├── FlowNetwork.java ├── Graph.java └── SymbolGraph.java └── priorityQueueClasses ├── IndexMinPriorityQueue.java ├── MaxPriorityQueue.java └── MinPriorityQueue.java /README.md: -------------------------------------------------------------------------------- 1 | # JavaDS 2 | This repository consist of implementation/explination of essential data structures and algorithms including trees,Linked List, Maps, String , Graphs and various other programming paradigm in JAVA language! 3 | -------------------------------------------------------------------------------- /images/AmortizedAnalysis2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/AmortizedAnalysis2.png -------------------------------------------------------------------------------- /images/Arbitrage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/Arbitrage.png -------------------------------------------------------------------------------- /images/ArrayList_Amortised1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/ArrayList_Amortised1.png -------------------------------------------------------------------------------- /images/ArticulationPoints.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/ArticulationPoints.png -------------------------------------------------------------------------------- /images/ArticulationPointsEx.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/ArticulationPointsEx.png -------------------------------------------------------------------------------- /images/BFS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/BFS.png -------------------------------------------------------------------------------- /images/BinaryTreeHeight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/BinaryTreeHeight.png -------------------------------------------------------------------------------- /images/BridgesInA GraphExample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/BridgesInA GraphExample.png -------------------------------------------------------------------------------- /images/Complete Bipartite graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/Complete Bipartite graph.png -------------------------------------------------------------------------------- /images/DFA construction KMP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/DFA construction KMP.png -------------------------------------------------------------------------------- /images/DFS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/DFS.png -------------------------------------------------------------------------------- /images/Diagnol SUM.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/Diagnol SUM.jpg -------------------------------------------------------------------------------- /images/DijKstrasoln.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/DijKstrasoln.jpg -------------------------------------------------------------------------------- /images/Dijkstras.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/Dijkstras.jpg -------------------------------------------------------------------------------- /images/EdgeWeightedDAG-For job scheduling.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/EdgeWeightedDAG-For job scheduling.png -------------------------------------------------------------------------------- /images/EulerianUndirected/Euler1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/EulerianUndirected/Euler1.png -------------------------------------------------------------------------------- /images/EulerianUndirected/Euler2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/EulerianUndirected/Euler2.png -------------------------------------------------------------------------------- /images/EulerianUndirected/Euler3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/EulerianUndirected/Euler3.png -------------------------------------------------------------------------------- /images/Floyd-Warshall.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/Floyd-Warshall.jpg -------------------------------------------------------------------------------- /images/GrahamScanFullAlgo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/GrahamScanFullAlgo.png -------------------------------------------------------------------------------- /images/IntervalTree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/IntervalTree.png -------------------------------------------------------------------------------- /images/LRS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/LRS.png -------------------------------------------------------------------------------- /images/LRU.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/LRU.png -------------------------------------------------------------------------------- /images/LSD Sort example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/LSD Sort example.png -------------------------------------------------------------------------------- /images/MotherVertex2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/MotherVertex2.png -------------------------------------------------------------------------------- /images/NQueen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/NQueen.png -------------------------------------------------------------------------------- /images/Number_Of_Islands.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/Number_Of_Islands.png -------------------------------------------------------------------------------- /images/SearchCost.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/SearchCost.png -------------------------------------------------------------------------------- /images/ShortestPathDAG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/ShortestPathDAG.png -------------------------------------------------------------------------------- /images/SieveOfEratosthenes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/SieveOfEratosthenes.png -------------------------------------------------------------------------------- /images/StringPermutation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/StringPermutation.gif -------------------------------------------------------------------------------- /images/Ternary-Search-Tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/Ternary-Search-Tree.png -------------------------------------------------------------------------------- /images/TopologicalSort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/TopologicalSort.png -------------------------------------------------------------------------------- /images/TrapWater.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/TrapWater.png -------------------------------------------------------------------------------- /images/UFTimeComplexity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/UFTimeComplexity.png -------------------------------------------------------------------------------- /images/UniqueBST2.GIF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/UniqueBST2.GIF -------------------------------------------------------------------------------- /images/UniquesBST1.GIF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/UniquesBST1.GIF -------------------------------------------------------------------------------- /images/ancestorMatrixToBinaryTree.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/ancestorMatrixToBinaryTree.jpg -------------------------------------------------------------------------------- /images/bipartite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/bipartite.png -------------------------------------------------------------------------------- /images/flattenList.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/flattenList.png -------------------------------------------------------------------------------- /images/grahamScanSortPoints.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/grahamScanSortPoints.png -------------------------------------------------------------------------------- /images/intersecting1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/intersecting1.png -------------------------------------------------------------------------------- /images/intersecting2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/intersecting2.png -------------------------------------------------------------------------------- /images/intersecting3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/intersecting3.png -------------------------------------------------------------------------------- /images/java-map-collection-cheat-sheet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/java-map-collection-cheat-sheet.gif -------------------------------------------------------------------------------- /images/max Sum path.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/max Sum path.png -------------------------------------------------------------------------------- /images/maximum-sum-of-subarray-close-to-k.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/maximum-sum-of-subarray-close-to-k.png -------------------------------------------------------------------------------- /images/mergeSort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/mergeSort.png -------------------------------------------------------------------------------- /images/minCutImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/minCutImage.png -------------------------------------------------------------------------------- /images/minimum iterations.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/minimum iterations.png -------------------------------------------------------------------------------- /images/motherIndex1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/motherIndex1.png -------------------------------------------------------------------------------- /images/mst/KrushkalsAlgo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/mst/KrushkalsAlgo.gif -------------------------------------------------------------------------------- /images/mst/MSTComplexities.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/mst/MSTComplexities.png -------------------------------------------------------------------------------- /images/mst/PrimsAlgo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/mst/PrimsAlgo.gif -------------------------------------------------------------------------------- /images/nextLeafNode.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/nextLeafNode.jpg -------------------------------------------------------------------------------- /images/nfaConstructionRegex.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/nfaConstructionRegex.png -------------------------------------------------------------------------------- /images/orientation_of_3_points.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/orientation_of_3_points.png -------------------------------------------------------------------------------- /images/polygonPontInside.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/polygonPontInside.png -------------------------------------------------------------------------------- /images/rabinkarp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/rabinkarp.png -------------------------------------------------------------------------------- /images/relaxation-edge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/relaxation-edge.png -------------------------------------------------------------------------------- /images/stateDiagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/stateDiagram.jpg -------------------------------------------------------------------------------- /images/stringCircle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/stringCircle.png -------------------------------------------------------------------------------- /images/symbolGraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/symbolGraph.png -------------------------------------------------------------------------------- /images/tilingProblem2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/tilingProblem2.jpg -------------------------------------------------------------------------------- /images/word-break-II-java.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/images/word-break-II-java.png -------------------------------------------------------------------------------- /notes/AdjacencyListVsGraphs: -------------------------------------------------------------------------------- 1 | In both DFS AND BFS, the runtime depends on how long it takes to iterate across the outgoing edges of a given node. 2 | With an adjacency list, the runtime is directly proportional to the number of outgoing edges. 3 | Since each node is visited once, the cost is the number of nodes plus the number of edges, which is O(m + n). 4 | With am adjacency matrix, the time required to find all outgoing edges is O(n) because all n columns in the row 5 | for a node must be inspected. Summing up across all n nodes, this works out to O(n2). 6 | 7 | Hope this helps! 8 | 9 | -------------------------------------------------------------------------------- /notes/Angle Between Hour And Minute Hand: -------------------------------------------------------------------------------- 1 | One clock cycle is 360 degree. 2 | 3 | How many degree can the minute hand run per minute? 360 / 60 = 6 degree per minute. 4 | 5 | How many degree can the hour hand run per hour? 360/12 = 30 degree per hour (since hour hand run slower than minute) 6 | 7 | 8 | Since it's easier to calculate in the unit, "minute", let's get 9 | 10 | "how many degree can the hour hand run per minute"? 11 | 30 / 60 = 0.5 degree per minute. 12 | 13 | static double angle(int h, int m) { 14 | double hAngle = 0.5D * (h * 60 + m); 15 | double mAngle = 6 * m; 16 | double angle = Math.abs(hAngle - mAngle); 17 | angle = Math.min(angle, 360 - angle); 18 | return angle; 19 | } 20 | Basically: 21 | 22 | The hour hand moves at the rate of 0.5 degrees per minute 23 | The minute hand moves at the rate of of 6 degrees per minute 24 | Problem solved. -------------------------------------------------------------------------------- /notes/AssignDirections: -------------------------------------------------------------------------------- 1 | Assign directions to edges so that the directed graph remains acyclic 2 | Given a graph with both directed and undirected edges. It is given that the directed edges don’t form cycle. 3 | How to assign directions to undirected edges so that the graph (with all directed edges) remains acyclic even after 4 | the assignment? 5 | 6 | The idea is to use Topological Sorting. Following are two steps used in the algorithm. 7 | 8 | 1) Consider the subgraph with directed edges only and find topological sorting of the subgraph. 9 | 10 | 2) Use above topological sorting to assign directions to undirected edges. 11 | For every undirected edge (u, v), assign it direction from u to v if u comes before 12 | v in topological sorting, else assign it direction from v to u. -------------------------------------------------------------------------------- /notes/BST_vs_Hashing.txt: -------------------------------------------------------------------------------- 1 | Advantages of BST over Hash Table 2 | Hash Table supports following operations in Θ(1) time. 3 | 1) Search 4 | 2) Insert 5 | 3) Delete 6 | 7 | The time complexity of above operations in a self-balancing Binary Search Tree (BST) 8 | (like Red-Black Tree, AVL Tree, Splay Tree, etc) is O(Logn). 9 | So Hash Table seems to beating BST in all common operations. 10 | When should we prefer BST over Hash Tables, what are advantages. Following are some important points in favor of BSTs. 11 | 12 | We can get all keys in sorted order by just doing Inorder Traversal of BST. 13 | This is not a natural operation in Hash Tables and requires extra efforts. 14 | Doing order statistics, finding closest lower and greater elements, 15 | doing range queries are easy to do with BSTs. 16 | Like sorting, these operations are not a natural operation with Hash Tables. 17 | BSTs are easy to implement compared to hashing, we can easily implement our own customized BST. 18 | To implement Hashing, we generally rely on libraries provided by programming languages. 19 | With BSTs, all operations are guaranteed to work in O(Logn) time. 20 | But with Hashing, Θ(1) is average time and some particular operations may be costly, 21 | especially when table resizing happens. -------------------------------------------------------------------------------- /notes/BackTracking: -------------------------------------------------------------------------------- 1 | Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. 2 | Problems which are typically solved using backtracking technique have following property in common. 3 | These problems can only be solved by trying every possible configuration and each configuration is tried only once. 4 | A Naive solution for these problems is to try all configurations and output a configuration that follows given 5 | problem constraints. Backtracking works in incremental way and is an optimization over the Naive solution where 6 | all possible configurations are generated and tried. 7 | 8 | Backtracking works in an incremental way to attack problems. 9 | Typically, we start from an empty solution vector and one by one add 10 | items (Meaning of item varies from problem to problem. In context of 11 | Knight’s tour problem, an item is a Knight’s move). When we add an item, 12 | we check if adding the current item violates the problem constraint, if it does then we remove the item and 13 | try other alternatives. If none of the alternatives work out then we go to previous stage and remove the item 14 | added in the previous stage. If we reach the initial stage back then we say that no solution exists. 15 | If adding an item doesn’t violate constraints then we recursively add items one by one. 16 | If the solution vector becomes complete then we print the solution. -------------------------------------------------------------------------------- /notes/BinaryTreeProperties: -------------------------------------------------------------------------------- 1 | Binary Tree Properties: 2 | 3 | The maximum number of nodes at level ‘l’ = 2l-1. 4 | 5 | Maximum number of nodes = 2h – 1. 6 | Here h is height of a tree. Height is considered 7 | as is maximum number of nodes on root to leaf path 8 | 9 | Minimum possible height = ceil(Log2(n+1)) 10 | 11 | In Binary tree, number of leaf nodes is always one 12 | more than nodes with two children. 13 | 14 | Time Complexity of Tree Traversal: O(n) 15 | -------------------------------------------------------------------------------- /notes/BuildingBridges.txt: -------------------------------------------------------------------------------- 1 | Building Bridges: Consider a 2-D map with a horizontal river passing through its center. 2 | There are n cities on the southern bank with x-coordinates a(1) … a(n) and n cities on the northern bank 3 | with x-coordinates b(1) … b(n). You want to connect as many north-south pairs of cities as possible with 4 | bridges such that no two bridges cross. When connecting cities, you can only connect city i on the northern bank 5 | to city i on the southern bank. 6 | 7 | 8 1 4 3 5 2 6 7 8 | <---- Cities on the other bank of river----> 9 | -------------------------------------------- 10 | <--------------- River---------------> 11 | -------------------------------------------- 12 | 1 2 3 4 5 6 7 8 13 | <------- Cities on one bank of river-------> 14 | 15 | Solved using LIS 16 | 17 | http://stackoverflow.com/questions/7288585/building-bridges-problem-how-to-apply-longest-increasing-subsequence -------------------------------------------------------------------------------- /notes/Catlan No: -------------------------------------------------------------------------------- 1 | Consider all possible binary search trees with each element at the root. If there are n nodes, 2 | then for each choice of root node, there are n – 1 non-root nodes and these non-root nodes must be partitioned 3 | into those that are less than a chosen root and those that are greater than the chosen root. 4 | 5 | Let’s say node i is chosen to be the root. Then there are i – 1 nodes smaller than i and n – i nodes bigger than i. 6 | For each of these two sets of nodes, there is a certain number of possible subtrees. 7 | 8 | Let t(n) be the total number of BSTs with n nodes. The total number of BSTs with i at the root is t(i – 1) t(n – i). 9 | The two terms are multiplied together because the arrangements in the left and right subtrees are independent. 10 | That is, for each arrangement in the left tree and for each arrangement in the right tree, you get one BST with i at the root. 11 | 12 | Summing over i gives the total number of binary search trees with n nodes. 13 | 14 | t(n) = (from i=1 to n)(Sum(t(i-1)*t(n-i)); 15 | 16 | 17 | i=0, count[0]=1 //empty tree 18 | 19 | i=1, count[1]=1 //one tree 20 | 21 | i=2, count[2]=count[0]*count[1] // 0 is root 22 | + count[1]*count[0] // 1 is root 23 | 24 | i=3, count[3]=count[0]*count[2] // 1 is root 25 | + count[1]*count[1] // 2 is root 26 | + count[2]*count[0] // 3 is root 27 | 28 | i=4, count[4]=count[0]*count[3] // 1 is root 29 | + count[1]*count[2] // 2 is root 30 | + count[2]*count[1] // 3 is root 31 | + count[3]*count[0] // 4 is root 32 | .. 33 | .. 34 | .. 35 | 36 | i=n, count[n] = sum(count[0..k]*count[k+1...n]) 0 <= k < n-1 37 | 38 | 39 | See images -------------------------------------------------------------------------------- /notes/CircleIntersection: -------------------------------------------------------------------------------- 1 | Given 'n' circles (each defined by center and radius) 2 | 3 | Write an algorithm to detect if circles intersect with any other circle in the same plane 4 | 5 | Better than O(n^2) complexity 6 | 7 | 8 | Two circles intersect if, and only if, the distance between their centers is between the sum 9 | and the difference of their radii. Given two circles (x0,y0,R0) and (x1,y1,R1), the formula is as follows: 10 | 11 | ABS(R0-R1) <= SQRT((x0-x1)^2+(y0-y1)^2) <= (R0+R1) 12 | Squaring both sides lets you avoid the slow SQRT, and stay with ints if your inputs are integer: 13 | 14 | (R0-R1)^2 <= (x0-x1)^2+(y0-y1)^2 <= (R0+R1)^2 15 | Since you need only a yes/no test, this check is faster than calculating the exact intersection points 16 | 17 | 18 | NlogN solution 19 | Sort the co-ordinates in x/y axis and binary search for first point on left and right where sum of radius is > distance between centers. 20 | all on left from left point and on right from right point will be the set of co-ordinates with non-intersecting circles. -------------------------------------------------------------------------------- /notes/DFS_vs_TopologicalSort: -------------------------------------------------------------------------------- 1 | Topological Sorting vs Depth First Traversal (DFS): 2 | In DFS, we print a vertex and then recursively call DFS for its adjacent vertices. 3 | In topological sorting, we need to print a vertex before its adjacent vertices. 4 | For example, in the given graph, the vertex ‘5’ should be printed before vertex ‘0’, 5 | but unlike DFS, the vertex ‘4’ should also be printed before vertex ‘0’. 6 | So Topological sorting is different from DFS. 7 | For example, a DFS of the above graph is “5 2 3 1 0 4″, but it is not a topological sorting 8 | 9 | See images/TopologicalSort.png 10 | 11 | 12 | 13 | 14 | Time Complexity: The above algorithm is simply DFS with an extra stack. So time complexity is same as DFS which is O(V+E). 15 | 16 | Applications: 17 | Topological Sorting is mainly used for scheduling jobs from the given dependencies among jobs. In computer science, 18 | applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula 19 | values in spreadsheets, logic synthesis, determining the order of compilation tasks to perform in makefiles, 20 | data serialization, and resolving symbol dependencies in linkers [2]. -------------------------------------------------------------------------------- /notes/Euclids lema: -------------------------------------------------------------------------------- 1 | Euclid’s lemma 2 | We are given two numbers x and y. We know that a number p divides their product. 3 | Can we say for sure that p also divides one of them? 4 | 5 | The answer is no. For example, consider x = 15, y = 6 and p = 9. p divides the product 15*6, 6 | but doesn’t divide any of them. 7 | 8 | What if p is prime? 9 | Euclid’s lemma states that if a prime p divides the product of two numbers (x*y), it must divide at 10 | least one of those numbers. 11 | 12 | For example x = 15, y = 6 and p = 5. p divides the product 15*6, it also divides 15. 13 | 14 | Generalization of Euclid’s lemma: 15 | If p divides x*y and p is relatively prime to x, then p must divide y. In the above example, 5 is relatively 16 | prime to 6, therefore it must divide 15. -------------------------------------------------------------------------------- /notes/Euiler_Circuit: -------------------------------------------------------------------------------- 1 | An Eulerian circuit is a traversal of all the edges of a simple graph once and only once, 2 | staring at one vertex and ending at the same vertex. You can repeat vertices as many times as you want, 3 | but you can never repeat an edge once it is traversed. 4 | 5 | The degree of a vertex is the number of edges incident with that vertex. 6 | 7 | So let G be a graph that has an Eulerian circuit. Every time we arrive at a vertex during our traversal of G, 8 | we enter via one edge and exit via another. Thus there must be an even number of edges at every vertex. 9 | Therefore, every vertex of G has even degree. -------------------------------------------------------------------------------- /notes/FindLSB&MSB: -------------------------------------------------------------------------------- 1 | //int value; 2 | int LSB = value & 1; 3 | Alternatively (which is not theoretically portable, but practically it is) 4 | 5 | //int value; 6 | int LSB = value % 2; 7 | Details: The second formula is simpler. The % operator is the remainder operator. 8 | A number's LSB is 1 iff it is an odd number and 0 otherwise. 9 | So we check the remainder of dividing with 2. The logic of the first formula is this: number 1 in binary is this: 10 | 11 | 0000...0001 12 | If you binary-AND this with an arbitraty number, all the bits of the result will be 13 | 0 except the last one because 0 AND anything else is 0. 14 | The last bit of the result will be 1 iff the last bit of your number was 1 because 1 & 1 == 1 and 1 & 0 == 0 -------------------------------------------------------------------------------- /notes/HeightOfBinaryTree: -------------------------------------------------------------------------------- 1 | 2 | The height of a complete binary tree of size N is ⎣ lg N ⎦ . 3 | 4 | It's CEIL(log2(n+1))-1 5 | 6 | the height increases by 1 when N is a power of 2. 7 | 8 | 1 node gives log2(2) = 1 9 | 3 nodes gives log2(4) = 2 10 | 7 nodes gives log2(8) = 3 11 | 15 nodes gives log2(16) = 4 -------------------------------------------------------------------------------- /notes/IntegersOppositeSign: -------------------------------------------------------------------------------- 1 | Detect if two integers have opposite signs 2 | Given two signed integers, write a function that returns true if the signs of given integers are different, 3 | otherwise false. For example, the function should return true -1 and +100, and should return false for -100 and -200. 4 | The function should not use any of the arithmetic operators. 5 | 6 | Let the given integers be x and y. The sign bit is 1 in negative numbers, and 0 in positive numbers. 7 | The XOR of x and y will have the sign bit as 1 iff they have opposite sign. In other words, 8 | XOR of x and y will be negative number number iff x and y have opposite signs. The following code use this logic. 9 | 10 | bool oppositeSigns(int x, int y) 11 | { 12 | return ((x ^ y) < 0); 13 | } -------------------------------------------------------------------------------- /notes/JaggedArray.txt: -------------------------------------------------------------------------------- 1 | Jagged array -- This is like a 2D array but with irregular subarray lengths. 2 | Its lengths are not even—they are jagged. Here we create a jagged array of two String arrays. 3 | 4 | And: 5 | The first subarray has two elements. The second one has three String elements. We loop over all these values. 6 | 7 | strings 8 | Java program that uses jagged array 9 | 10 | public class Program { 11 | public static void main(String[] args) { 12 | 13 | // Create an array of String arrays: a jagged array. 14 | String[][] values = new String[2][]; 15 | 16 | // Fill first row with 2-element array. 17 | values[0] = new String[2]; 18 | values[0][0] = "cat"; 19 | values[0][1] = "dog"; 20 | 21 | // Use 3-element array for second row. 22 | values[1] = new String[3]; 23 | values[1][0] = "fish"; 24 | values[1][1] = "bird"; 25 | values[1][2] = "lizard"; 26 | 27 | // Display rows and elements. 28 | for (String[] array : values) { 29 | for (String element : array) { 30 | System.out.print(element); 31 | System.out.print(" "); 32 | } 33 | System.out.println(); 34 | } 35 | } 36 | } 37 | 38 | Output 39 | 40 | cat dog 41 | fish bird lizard -------------------------------------------------------------------------------- /notes/JollyJumper: -------------------------------------------------------------------------------- 1 | Jolly Jumper Sequence 2 | A sequence of n numbers (n < 3000) is called Jolly Jumper if the absolute values of the differences between the successive 3 | elements take on all possible values from 1 through n-1. The definition implies that any sequence of a single integer is a jolly jumper. 4 | 5 | Examples: 6 | 7 | Input: 1 4 2 3 8 | Output: True 9 | This sequence 1 4 2 3 is Jolly Jumper because 10 | the absolute differences are 3, 2, and 1. 11 | 12 | Input: 1 4 2 -1 6 13 | Output: False 14 | The absolute differences are 3, 2, 3, 7. 15 | This does not contain all the values from 1 16 | through n-1. So, this sequence is not Jolly. 17 | 18 | Input: 11 7 4 2 1 6 19 | Output: True 20 | 21 | 22 | 23 | The idea is to maintain a boolean array to store set of absolute difference of successive elements. 24 | a) If absolute difference between two elements is more than n-1 or 0, return false. 25 | b) If an absolute difference repeated, then all absolute differences from 1 to n-1 can’t be present (Pigeon Hole Principle), return false. -------------------------------------------------------------------------------- /notes/LazyCarterProblem: -------------------------------------------------------------------------------- 1 | The Lazy Caterer’s Problem 2 | Given an integer n, denoting the number of cuts that can be made on a pancake, 3 | find the maximum number of pieces that can be formed by making n cuts. 4 | Examples: 5 | 6 | Input : n = 1 7 | Output : 2 8 | With 1 cut we can divide the pancake in 2 pieces 9 | 10 | Input : 2 11 | Output : 4 12 | With 2 cuts we can divide the pancake in 4 pieces 13 | 14 | Input : 3 15 | Output : 7 16 | We can divide the pancake in 7 parts with 3 cuts 17 | 18 | Input : 50 19 | Output : 1276 20 | 21 | If u draw various lines and circles u will find out that in order for maximum cuts the next line has to cross all the other present 22 | lines. 23 | 24 | So if u check : 25 | 26 | Let f(n) denote the maximum number of pieces 27 | that can be obtained by making n cuts. 28 | Trivially, 29 | f(0) = 1 30 | As there'd be only 1 piece without any cut. 31 | 32 | Similarly, 33 | f(1) = 2 34 | 35 | Proceeding in similar fashion we can deduce 36 | the recursive nature of the function. 37 | The function can be represented recursively as : 38 | f(n) = n + f(n-1) 39 | 40 | Hence a simple solution based on the above 41 | formula can run in O(n). 42 | 43 | 44 | We can optimize above formula. 45 | 46 | We now know , 47 | f(n) = n + f(n-1) 48 | 49 | Expanding f(n-1) and so on we have , 50 | f(n) = n + n-1 + n-2 + ...... + 1 + f(0) 51 | 52 | which gives, 53 | f(n) = (n*(n+1))/2 + 1 -------------------------------------------------------------------------------- /notes/MST_properties: -------------------------------------------------------------------------------- 1 | --> Adding an edge that connects two vertices in a tree 2 | creates a unique cycle. 3 | --> Removing an edge from a tree breaks it into two 4 | separate subtrees. 5 | These properties are the basis for proving a fundamental property of MSTs that leads to the MST algorithms. 6 | 7 | Cut property. This property, which we refer to as the cut 8 | property, has to do with identifying edges that must be in the 9 | MST of a given edge-weighted graph, by dividing vertices 10 | into two sets and examining edges that cross the division. 11 | 12 | 13 | Definition. A cut of a graph is a partition of its vertices into two nonempty disjoint sets. A crossing edge of a cut is an edge 14 | that connects a vertex in one set with a vertex in the other. 15 | 16 | 17 | Proposition J. ( Cut property) Given any cut in an edgeweighted graph, the crossing edge of minimum weight is in 18 | the MST of the graph. 19 | Proof: Let e be the crossing edge of minimum weight and 20 | let T be the MST. The proof is by contradiction: Suppose 21 | that T does not contain e. Now consider the graph formed 22 | by adding e to T. This graph has a cycle that contains e, and 23 | that cycle must contain at least one other crossing edge— 24 | say, f, which has higher weight than e (since e is minimal and 25 | all edge weights are different). We can get a spanning tree of 26 | strictly lower weight by deleting f and adding e, contradicting 27 | the assumed minimality of T. 28 | 29 | Under our assumption that edge weights 30 | are distinct, every connected graph has a 31 | unique MST and the cut property says that the shortest crossing 32 | edge for every cut must be in the MST. 33 | 34 | -------------------------------------------------------------------------------- /notes/MinValue: -------------------------------------------------------------------------------- 1 | Integer.MIN_VALUE multiplied by -1 remains the same because 2 | 3 | of silent integer overflow: Integer.MIN_VALUE is -2^31 and Integer.MAX_VALUE is 2^31-1, 4 | so -Integer.MIN_VALUE is 2^31, which is Integer.MAX_VALUE + 1, which by definition is too large for an integer. 5 | So it overflows and becomes Integer.MIN_VALUE... 6 | 7 | You can also check that: 8 | 9 | System.out.println(Integer.MAX_VALUE + 1); 10 | prints the same thing. 11 | 12 | More technically, the result is defined by 13 | 14 | If an integer addition overflows, then the result is the low-order bits of the mathematical sum as 15 | represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of 16 | the result is not the same as the sign of the mathematical sum of the two operand values. -------------------------------------------------------------------------------- /notes/Minimum Number Of Flips: -------------------------------------------------------------------------------- 1 | 2 | Give N cards facing down, you have to flip all the N cards facing up. 3 | If you are flipping ith card then, i-1,i,i+1 will flipped. For eg: if N =3, then minimum no of steps will be 1. 4 | Given N cards, we have to calculate the minimum no of steps to flip all the cards up. 5 | 6 | The cases for N=1, 2, and 3 are easy. 7 | 8 | For N = 3k, this is easy. Just flip over k cards starting with the second one. 9 | 10 | For N = 3k+1, first flip both cards on the ends, which flips over 4 cards. 11 | Then we have 3k-3 cards left over, which is divisible by 3, which can be easily flipped in k-1 moves. (k-1+2 = k+1) 12 | 13 | For N = 3k+2, first choose the first card, which flips 2 cards. 14 | Now you have 3k cards left to flip, which is easily done in k flips. (k+1) 15 | 16 | So it's n/3 with multiples of 3 and n/3 + 1 otherwise 17 | 18 | It can be further reduced to (n + 2) / 3. -------------------------------------------------------------------------------- /notes/MultiplyBy7: -------------------------------------------------------------------------------- 1 | Efficient way to multiply with 7 2 | We can multiply a number by 7 using bitwise operator. 3 | First left shift the number by 3 bits (you will get 8n) then subtract the original number 4 | from the shifted number and return the difference (8n – n). 5 | 6 | 7 | int multiplyBySeven(unsigned int n) 8 | { 9 | /* Note the inner bracket here. This is needed 10 | because precedence of '-' operator is higher 11 | than '<<' */ 12 | return ((n<<3) - n); 13 | } 14 | -------------------------------------------------------------------------------- /notes/NearlyKSortedArrays: -------------------------------------------------------------------------------- 1 | Sort a nearly sorted (or K sorted) array 2 | Given an array of n elements, where each element is at most k away from its target position, 3 | devise an algorithm that sorts in O(n log k) time. 4 | For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. 5 | 6 | We can sort such arrays more efficiently with the help of Heap data structure. Following is the detailed process that uses Heap. 7 | 1) Create a Min Heap of size k+1 with first k+1 elements. This will take O(k) time (See this GFact) 8 | 2) One by one remove min element from heap, put it in result array, and add a new element to heap from remaining elements. 9 | 10 | Removing an element and adding a new element to min heap will take Logk time. So overall complexity will be O(k) + O((n-k)*logK) 11 | 12 | The overall complexity should be O(k) + O((n-k)*logK) + O(k*logk) = O(k) + O(nlogk) because the extractMin 13 | for the remaining K+1 elements in the heap at the end will also take O(k*logk) time. -------------------------------------------------------------------------------- /notes/NegativeCyclesBellmanFord: -------------------------------------------------------------------------------- 1 | Definition. A negative cycle in an edgeweighted 2 | digraph is a directed cycle whose 3 | total weight (sum of the weights of its 4 | edges) is negative. 5 | 6 | Now, suppose that some vertex on a path from s to a 7 | reachable vertex v is also on a negative cycle. In this case, 8 | the existence of a shortest path from s to v would be a 9 | contradiction, because we could use the cycle to construct 10 | a path with weight lower than any given value. In other 11 | words, shortest paths can be an ill-posed problem if negative 12 | cycles are present. 13 | 14 | Proposition W. There exists a shortest path from s 15 | to v in an edge-weighted digraph if and only if there 16 | exists at least one directed path from s to v and no 17 | vertex on any directed path from s to v is on a negative 18 | cycle. 19 | 20 | 21 | algorithm restriction typical worst-case extra-space sweet-spot 22 | Dijkstra (eager) positive edge weights E log V E log V V worst-case guarantee 23 | topological sort edge-weighted DAGs E + V E + V V optimal for acyclic 24 | Bellman-Ford (queue-based)no negative-cycles E + V VE V widely applicable -------------------------------------------------------------------------------- /notes/NetworkFlowAndImplementations.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/notes/NetworkFlowAndImplementations.pdf -------------------------------------------------------------------------------- /notes/OddNoOfTimes: -------------------------------------------------------------------------------- 1 | Find the Number Occurring Odd Number of Times 2 | Given an array of positive integers. 3 | All numbers occur even number of times except one number which occurs odd number of times. 4 | Find the number in O(n) time & constant space. 5 | 6 | Example: 7 | I/P = [1, 2, 3, 2, 3, 1, 3] 8 | O/P = 3 9 | 10 | Algorithm: 11 | Do bitwise XOR of all the elements. Finally we get the number which has odd occurrences -------------------------------------------------------------------------------- /notes/OptimalSubStructure.txt: -------------------------------------------------------------------------------- 1 | 2) Optimal Substructure: A given problems has Optimal Substructure Property if optimal solution of the given 2 | problem can be obtained by using optimal solutions of its subproblems. 3 | For example the shortest path problem has following optimal substructure property: If a node x lies in the shortest 4 | path from a source node u to destination node v then the shortest path from u to v is combination of shortest path 5 | from u to x and shortest path from x to v. The standard All Pair Shortest Path algorithms like Floyd–Warshall and 6 | Bellman–Ford are typical examples of Dynamic Programming. 7 | On the other hand the Longest path problem doesn’t have the Optimal Substructure property. Here by Longest 8 | Path we mean longest simple path (path without cycle) between two nodes. Consider the following unweighted 9 | graph given in the CLRS book. There are two longest paths from q to t: q -> r ->t and q ->s->t. 10 | Unlike shortest paths, these longest paths do not have the optimal substructure property. 11 | For example, the longest path q->r->t is not a combination of longest path from q to r and longest path from r to t, 12 | because the longest path from q to r is q->s->t->r. 13 | 14 | See Image -------------------------------------------------------------------------------- /notes/Order_statistics.ppt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/notes/Order_statistics.ppt -------------------------------------------------------------------------------- /notes/RandomPointer: -------------------------------------------------------------------------------- 1 | Clone a linked list with next and random pointer 2 | 3 | You are given a Double Link List with one pointer of each node pointing to the next node just like in a single link list. 4 | The second pointer however CAN point to any node in the list and not just the previous node. Now write a program in O(n) time to duplicate this list. That is, write a program which will create a copy of this list. 5 | 6 | 1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, 7 | create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of N after the Nth node 8 | 2) Now copy the arbitrary link in this fashion 9 | 10 | original->next->arbitrary = original->arbitrary->next; /*TRAVERSE 11 | TWO NODES*/ 12 | This works because original->next is nothing but copy of original and Original->arbitrary->next is nothing but copy 13 | of arbitrary. 14 | 3) Now restore the original and copy linked lists in this fashion in a single loop. 15 | 16 | original->next = original->next->next; 17 | copy->next = copy->next->next; 18 | 4) Make sure that last element of original->next is NULL. 19 | 20 | Time Complexity: O(n) 21 | Auxiliary Space: O(1) -------------------------------------------------------------------------------- /notes/Remove duplicates: -------------------------------------------------------------------------------- 1 | Remove duplicates from a string in O(n) without using hash. 2 | 3 | 4 | Sort the source array. Find consecutive elements that are equal 5 | To remove duplicates, you can copy elements from later in the array over elements earlier in the array 6 | also in linear time. Simply keep a pointer to the new logical end of the container, and copy the next 7 | distinct element to that new logical end at each step 8 | 9 | 10 | You do a sort of bucket sort. 11 | 12 | make an array containing every single char 13 | make an array containing a count for it's corresponding char 14 | The only reason we're using 2 arrays like this is because you specifically disallowed hash maps. 15 | You can represent this structure however you please. If you're allowed to convert chars to int, you need only use 1 array. 16 | 17 | Since we're assuming a limited number of possible characters, Each array will be constant size, or O(1) 18 | 19 | Iterate over your string, and increment the count for each char you find. If count is already greater than 0 20 | you've found a duplicate. 21 | searching your char array for a particular char takes O(1) time, because there is a limited number of chars. 22 | 23 | you will do this search n times for a net run-time of O(n) 24 | 25 | If arrays are no good, than you can make a linked list to hold only values that you've found. It will still be 26 | constant because the size of the linked list is still bound by the number of possible characters. 27 | 28 | If you do it that way, you'll more or less be doing the exact same thing, except it cosmetically look less like 29 | a bucket-sort strategy. -------------------------------------------------------------------------------- /notes/RotatedStrings: -------------------------------------------------------------------------------- 1 | A Program to check if strings are rotations of each other or not 2 | Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1 using only one call 3 | to strstr routine? 4 | 5 | 6 | (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false) 7 | 8 | 9 | Algorithm: areRotations(str1, str2) 10 | 11 | 1. Create a temp string and store concatenation of str1 to 12 | str1 in temp. 13 | temp = str1.str1 14 | 2. If str2 is a substring of temp then str1 and str2 are 15 | rotations of each other. 16 | 17 | Example: 18 | str1 = "ABACD" 19 | str2 = "CDABA" 20 | 21 | temp = str1.str1 = "ABACDABACD" 22 | Since str2 is a substring of temp, str1 and str2 are 23 | rotations of each other. -------------------------------------------------------------------------------- /notes/TileFloorDP: -------------------------------------------------------------------------------- 1 | Given a floor of dimensions 2 x W and tiles of dimensions 2 x 1, 2 | write code to find the number of ways the floor can be tiled. 3 | 4 | width possibilities (1 = vertical, 0 = horizontal and must be in pairs) 5 | 1 1 - 1 6 | 2 2 - 11/00 7 | 3 3 - 111/100/001 8 | 4 5 - 1111/1100/1001/0011/0000 9 | 5 8 - 11111/11100/11001/10011 10 | 10000/00111/00001/00000 11 | 12 | 13 | Fib series -------------------------------------------------------------------------------- /notes/Tiling Problem: -------------------------------------------------------------------------------- 1 | Tiling Problem 2 | Given a “2 x n” board and tiles of size “2 x 1″, 3 | count the number of ways to tile the given board using the 2 x 1 tiles. 4 | A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. 5 | 6 | Examples: 7 | 8 | Input n = 3 9 | Output: 3 10 | Explanation: 11 | We need 3 tiles to tile the board of size 2 x 3. 12 | We can tile the board using following ways 13 | 1) Place all 3 tiles vertically. 14 | 2) Place first tile vertically and remaining 2 tiles horizontally. 15 | 3) Place first 2 tiles horizontally and remaining tiles vertically 16 | 17 | Input n = 4 18 | Output: 5 19 | Explanation: 20 | For a 2 x 4 board, there are 5 ways 21 | 1) All 4 vertical 22 | 2) All 4 horizontal 23 | 3) First 2 vertical, remaining 2 horizontal 24 | 4) First 2 horizontal, remaining 2 vertical 25 | 5) Corner 2 vertical, middle 2 horizontal 26 | 27 | 28 | Let “count(n)” be the count of ways to place tiles on a “2 x n” grid, we have following two ways to place first tile. 29 | 1) If we place first tile vertically, the problem reduces to “count(n-1)” 30 | 2) If we place first tile horizontally, we have to place second tile also horizontally. So the problem reduces 31 | to “count(n-2)” 32 | 33 | Therefore, count(n) can be written as below. 34 | 35 | count(n) = n if n = 1 or n = 2 36 | count(n) = count(n-1) + count(n-2) 37 | The above recurrence is noting but Fibonacci Number expression. We can find n’th Fibonacci number in O(Log n) time, 38 | see below for all method to find n’th Fibonacci Number. -------------------------------------------------------------------------------- /notes/TopKTrending words: -------------------------------------------------------------------------------- 1 | There is a big file of words which is dynamically changing. We are continuously adding some words into it. 2 | How would you keep track of top 10 trending words at each moment? 3 | 4 | If it's top 10 trending words then you should use a max-heap along with a hash-table. 5 | 6 | When a new word is added to the file then: 7 | 8 | Create a new element x with x.key=word and x.count=1. 9 | Add x to the hash-table. O(1). 10 | Add x to the max-heap. O(lgn). 11 | When an existing word is added to the file then: 12 | 13 | Find x in the hash-table. O(1). 14 | Update x.count to x.count++. 15 | When there is a need to retrieve the top 10 trending words then: 16 | 17 | Extract 10 times from the max-heap. 10*O(lgn)=O(10*lgn)=O(lgn). 18 | As you can see, all the needed operations are done in at most O(lgn). 19 | 20 | You have to use a MinHeap, not MaxHeap. So, if you have k items in the heap, the peek of the heap is the smallest; 21 | and everyone else (k - 1) is larger than the peek. 22 | Now, if a new word with count > peek.count comes in, we want to extract the min (O(logk)) 23 | and insert the new item (O(logk)).If new item has count smaller than peek, 24 | that means it is smaller than any other item in the heap (as it's a Min Heap). 25 | We just discard that word as that will not be a part of top k. -------------------------------------------------------------------------------- /notes/TurnOffRSB: -------------------------------------------------------------------------------- 1 | Turn off the rightmost set bit 2 | 3 | Examples: 4 | 5 | Input: 12 (00...01100) 6 | Output: 8 (00...01000) 7 | 8 | Input: 7 (00...00111) 9 | Output: 6 (00...00110) 10 | Let the input number be n. n-1 would have all the bits flipped after the 11 | rightmost set bit (including the set bit). So, doing n&(n-1) would give us the required result. 12 | 13 | int fun(unsigned int n) 14 | { 15 | return n&(n-1); 16 | } -------------------------------------------------------------------------------- /notes/TwoNonRepeatingelements: -------------------------------------------------------------------------------- 1 | Find the two non-repeating elements in an array of repeating elements 2 | 3 | Let x and y be the non-repeating elements we are looking for and arr[] be the input array. 4 | First calculate the XOR of all the array elements. 5 | 6 | xor = arr[0]^arr[1]^arr[2].....arr[n-1] 7 | All the bits that are set in xor will be set in one non-repeating element (x or y) and not in other. 8 | So if we take any set bit of xor and divide the elements of the array in two sets – one set of 9 | elements with same bit set and other set with same bit not set. By doing so, we will get x in one 10 | set and y in another set. Now if we do XOR of all the elements in first set, we will get first non-repeating element, 11 | and by doing same in other set we will get the second non-repeating element. 12 | 13 | Let us see an example. 14 | arr[] = {2, 4, 7, 9, 2, 4} 15 | 1) Get the XOR of all the elements. 16 | xor = 2^4^7^9^2^4 = 14 (1110) 17 | 2) Get a number which has only one set bit of the xor. 18 | Since we can easily get the rightmost set bit, let us use it. 19 | set_bit_no = xor & ~(xor-1) = (1110) & ~(1101) = 0010 20 | Now set_bit_no will have only set as rightmost set bit of xor. 21 | 3) Now divide the elements in two sets and do xor of 22 | elements in each set, and we get the non-repeating 23 | elements 7 and 9. Please see implementation for this 24 | step. -------------------------------------------------------------------------------- /notes/UnionFindVsDFS: -------------------------------------------------------------------------------- 1 | Union-find. How does the DFS-based solution for graph connectivity in CC compare 2 | with the union-find 3 | In theory, DFS is faster than union-find 4 | because it provides a constant-time guarantee, which union-find does not; in practice, 5 | this difference is negligible, and union-find is faster because it does not have to build 6 | a full representation of the graph. More important, union-find is an online algorithm 7 | (we can check whether two vertices are connected in near-constant time at any point, 8 | even while adding edges), whereas the DFS solution must first preprocess the graph. 9 | 10 | Therefore, for example, we prefer union-find when determining connectivity is our 11 | only task or when we have a large number of queries intermixed with edge insertions 12 | but may find the DFS solution more appropriate for use in a graph ADT because it 13 | makes efficient use of existing infrastructure. -------------------------------------------------------------------------------- /notes/articulationPoints.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/notes/articulationPoints.pdf -------------------------------------------------------------------------------- /notes/backtracking.ppt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/notes/backtracking.ppt -------------------------------------------------------------------------------- /notes/booleanArray: -------------------------------------------------------------------------------- 1 | A Boolean Array Puzzle 2 | Input: A array arr[] of two elements having value 0 and 1 3 | 4 | Output: Make both elements 0. 5 | 6 | Specifications: Following are the specifications to follow. 7 | 1) It is guaranteed that one element is 0 but we do not know its position. 8 | 2) We can’t say about another element it can be 0 or 1. 9 | 3) We can only complement array elements, no other operation like and, or, multi, division, …. etc. 10 | 4) We can’t use if, else and loop constructs. 11 | 5) Obviously, we can’t directly assign 0 to array elements. 12 | 13 | 14 | 15 | Method 1 16 | 17 | void changeToZero(int a[2]) 18 | { 19 | a[ a[1] ] = a[ !a[1] ]; 20 | } 21 | 22 | void changeToZero(int a[2]) 23 | { 24 | a[ !a[0] ] = a[ !a[1] ] 25 | } 26 | Method 3 27 | This method doesn’t even need complement. 28 | 29 | void changeToZero(int a[2]) 30 | { 31 | a[ a[1] ] = a[ a[0] ] 32 | } 33 | 34 | 35 | void changeToZero(int a[2]) 36 | { 37 | a[0] = a[a[0]]; 38 | a[1] = a[0]; 39 | } -------------------------------------------------------------------------------- /notes/heapsort-analysis-part.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/notes/heapsort-analysis-part.pdf -------------------------------------------------------------------------------- /notes/maxflowPrinceton.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/notes/maxflowPrinceton.pdf -------------------------------------------------------------------------------- /notes/network-flow-problems.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/notes/network-flow-problems.pdf -------------------------------------------------------------------------------- /notes/weight_shechuding.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Poorvankbhatia/Data-Structures-In-Java/8c2d4e875fb7ef998d88adb72120add3cfb30825/notes/weight_shechuding.pdf -------------------------------------------------------------------------------- /src/arrays/BooleanArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | A Boolean Array Puzzle 4 | Input: A array arr[] of two elements having value 0 and 1 5 | 6 | Output: Make both elements 0. 7 | 8 | Specifications: Following are the specifications to follow. 9 | 1) It is guaranteed that one element is 0 but we do not know its position. 10 | 2) We can’t say about another element it can be 0 or 1. 11 | 3) We can only complement array elements, no other operation like and, or, multi, division, …. etc. 12 | 4) We can’t use if, else and loop constructs. 13 | 5) Obviously, we can’t directly assign 0 to array elements. 14 | 15 | */ 16 | 17 | package arrays; 18 | 19 | import java.util.Arrays; 20 | 21 | /** 22 | * Created by poorvank on 6/12/15. 23 | */ 24 | public class BooleanArray { 25 | 26 | public static void main(String[] args) { 27 | 28 | int[] a = new int[]{0, 1}; 29 | 30 | a[a[1]] = a[a[0]]; 31 | 32 | System.out.println(Arrays.toString(a)); 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/arrays/FindTwoElementsGivenSum.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | 6 | /** 7 | * Created by poorvank on 5/8/15. 8 | */ 9 | public class FindTwoElementsGivenSum { 10 | 11 | public static void main(String[] args) { 12 | 13 | int[] result = findPairOfElemInArrWithSum(new int[]{5, 3, 8, 3}, 6); 14 | 15 | System.out.println(Arrays.toString(result)); 16 | 17 | } 18 | 19 | private static int[] findPairOfElemInArrWithSum(int[] nums, int sum) { 20 | 21 | HashMap map = new HashMap<>(); 22 | int[] result = new int[2]; 23 | 24 | for (int i = 0; i < nums.length; i++) { 25 | if (map.containsKey(sum - nums[i])) { 26 | result[0] = map.get(sum - nums[i]); 27 | result[1] = i; 28 | } else { 29 | map.put(nums[i], i); 30 | } 31 | } 32 | 33 | return result; 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/arrays/GenerateSubSets.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given array, find all possible sets of elements which add up to a given integer K.` 4 | 5 | */ 6 | 7 | package arrays; 8 | 9 | import java.util.Stack; 10 | 11 | /** 12 | * Created by poorvank on 6/6/15. 13 | */ 14 | 15 | class SubsetSum { 16 | 17 | private Stack stack = new Stack(); 18 | private int stackSum = 0; 19 | 20 | public void checkSum(int sum, int startIndex, int endIndex, int[] arr) { 21 | 22 | if (stackSum == sum) { 23 | printStack(sum); 24 | return; 25 | } 26 | 27 | for (int i = startIndex; i < endIndex; i++) { 28 | 29 | if (stackSum + arr[i] <= sum) { 30 | 31 | stackSum += arr[i]; 32 | stack.push(arr[i]); 33 | 34 | checkSum(sum, startIndex + 1, endIndex, arr); 35 | stackSum -= stack.pop(); 36 | 37 | } 38 | 39 | } 40 | 41 | } 42 | 43 | private void printStack(int sum) { 44 | 45 | StringBuilder sb = new StringBuilder(); 46 | sb.append(sum).append(" = "); 47 | for (Integer i : stack) { 48 | sb.append(i).append("+"); 49 | } 50 | System.out.println(sb.deleteCharAt(sb.length() - 1).toString()); 51 | 52 | } 53 | 54 | 55 | } 56 | 57 | public class GenerateSubSets { 58 | 59 | public static void main(String[] args) { 60 | 61 | int[] arr = new int[]{1, 3, 4, 5, 6, 2, 7, 8, 9, 10, 11, 13, 14, 15}; 62 | int sum = 15; 63 | SubsetSum subsetSum = new SubsetSum(); 64 | subsetSum.checkSum(sum, 0, arr.length - 1, arr); 65 | 66 | } 67 | 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/arrays/LargestSumPair.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given an unsorted array, find the largest pair sum in it. For example, the largest pair sum in {12, 34, 10, 6, 40} is 74. 4 | 5 | */ 6 | 7 | package arrays; 8 | 9 | /** 10 | * Created by poorvank on 5/25/15. 11 | */ 12 | public class LargestSumPair { 13 | 14 | public static void main(String[] args) { 15 | 16 | int[] array = new int[]{12, 34, 10, 6, 40}; 17 | 18 | int first = Math.max(array[0], array[1]); 19 | int second = Math.min(array[0], array[1]); 20 | 21 | for (int i = 2; i < array.length; i++) { 22 | 23 | if (array[i] > first) { 24 | second = first; 25 | first = array[i]; 26 | } else if (array[i] > second) { 27 | second = array[i]; 28 | } 29 | 30 | } 31 | 32 | System.out.println("Maximum sum = " + (first + second)); 33 | 34 | } 35 | 36 | } 37 | 38 | /* 39 | 40 | 1) Initialize both first and second largest 41 | first = max(arr[0], arr[1]) 42 | second = min(arr[0], arr[1]) 43 | 2) Loop through remaining elements (from 3rd to end) 44 | a) If the current element is greater than first, then update first 45 | and second. 46 | b) Else if the current element is greater than second then update 47 | second 48 | 3) Return (first + second) 49 | 50 | */ -------------------------------------------------------------------------------- /src/arrays/MaxDifference.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Maximum difference between two elements such that larger element appears after the smaller number 4 | Given an array arr[] of integers, find out the difference between any two elements such that larger 5 | element appears after the smaller number in arr[]. 6 | 7 | Examples: If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). 8 | If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9) 9 | 10 | */ 11 | 12 | package arrays; 13 | 14 | /** 15 | * Created by poorvank on 6/18/15. 16 | */ 17 | public class MaxDifference { 18 | 19 | public static void main(String[] args) { 20 | 21 | int[] arr = new int[]{2, 3, 10, 6, 4, 8, 1}; 22 | 23 | int minElement = arr[0]; 24 | int maxDifference = arr[1] - arr[0]; 25 | 26 | /* 27 | 28 | In this method, instead of taking difference of the picked element with every other element, 29 | we take the difference with the minimum element found so far. So we need to keep track of 2 things: 30 | 1) Maximum difference found so far (max_diff). 31 | 2) Minimum number visited so far (min_element). 32 | 33 | */ 34 | for (int i = 1; i < arr.length; i++) { 35 | 36 | if (maxDifference < arr[i] - minElement) { 37 | maxDifference = arr[i] - minElement; 38 | } 39 | if (minElement > arr[i]) { 40 | minElement = arr[i]; 41 | } 42 | 43 | } 44 | 45 | System.out.println(maxDifference); 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/arrays/MaximumAverageSubArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Find maximum average subarray of k length 4 | Given an array with positive and negative numbers, find the maximum average subarray of given length. 5 | 6 | Example: 7 | 8 | Input: arr[] = {1, 12, -5, -6, 50, 3}, k = 4 9 | Output: Maximum average subarray of length 4 begins 10 | at index 1. 11 | Maximum average is (12 - 5 - 6 + 50)/4 = 51/4 12 | 13 | */ 14 | 15 | package arrays; 16 | 17 | /** 18 | * Created by poorvank on 8/28/15. 19 | */ 20 | public class MaximumAverageSubArray { 21 | 22 | public static void main(String[] args) { 23 | 24 | int[] arr = new int[]{1, 12, -5, -6, 50, 3}; 25 | 26 | int n = arr.length; 27 | int sum = 0; 28 | int k = 4; 29 | 30 | for (int i = 0; i < k; i++) { 31 | sum += arr[i]; 32 | } 33 | int maxSum = sum; 34 | int end = 0; 35 | for (int i = k; i < n; i++) { 36 | 37 | sum = sum + arr[i] - arr[i - k]; 38 | if (sum > maxSum) { 39 | maxSum = sum; 40 | end = i; 41 | } 42 | 43 | } 44 | 45 | System.out.println("Maximum average starts at = " + (end - k + 1)); 46 | 47 | } 48 | 49 | } 50 | 51 | /* 52 | 53 | 1) Compute sum of first ‘k’ elements, i.e., elements arr[0..k-1]. Let this sum be ‘sum’. Initialize ‘max_sum’ as ‘sum’ 54 | 2) Do following for every element arr[i] where i varies from ‘k’ to ‘n-1′ 55 | …….a) Remove arr[i-k] from sum and add arr[i], i.e., do sum += arr[i] – arr[i-k] 56 | …….b) If new sum becomes more than max_sum so far, update max_sum. 57 | 3) Return ‘max_sum’ 58 | 59 | */ -------------------------------------------------------------------------------- /src/arrays/MinimumNumberOfMoves.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Minimum Moves so that all the the even elements are in front. 4 | 5 | */ 6 | package arrays; 7 | 8 | /** 9 | * Created by poorvank.b on 21/02/17. 10 | */ 11 | public class MinimumNumberOfMoves { 12 | 13 | public static void main(String[] args) { 14 | 15 | int[] array = new int[]{1,2,3}; 16 | 17 | int start=0,end=array.length-1,count=0; 18 | 19 | while (start= 0; i--) { 28 | 29 | int a = array[i]; 30 | 31 | array[i] = max; 32 | 33 | if (max < a) { 34 | max = a; 35 | } 36 | 37 | } 38 | 39 | System.out.println(Arrays.toString(array)); 40 | 41 | } 42 | 43 | } 44 | 45 | /* 46 | 47 | A tricky method is to replace all elements using one traversal of the array. 48 | The idea is to start from the rightmost element, move to the left side one by one, 49 | and keep track of the maximum element. Replace every element with the maximum element. 50 | 51 | */ -------------------------------------------------------------------------------- /src/arrays/NextGreatestNumber.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by poorvank on 7/2/15. 7 | */ 8 | public class NextGreatestNumber { 9 | 10 | public static void main(String[] args) { 11 | 12 | int n = 218765; 13 | String s = Integer.toString(n); 14 | printNextNo(s); 15 | 16 | } 17 | 18 | private static void printNextNo(String s) { 19 | 20 | int i,len=s.length(); 21 | 22 | for (i = s.length() - 1; i >= 0; i--) { 23 | if (Character.getNumericValue(s.charAt(i)) > Character.getNumericValue(s.charAt(i - 1))) { 24 | break; 25 | } 26 | } 27 | 28 | if (i == 0) { 29 | System.out.println("Not possible"); 30 | return; 31 | } 32 | 33 | System.out.println(i); 34 | 35 | int minIndex = i; 36 | int x = Character.getNumericValue(s.charAt(i-1)); 37 | 38 | for (int j = i+1; j < len; j++) 39 | if (Character.getNumericValue(s.charAt(j)) > x && Character.getNumericValue(s.charAt(j)) < Character.getNumericValue(s.charAt(minIndex))) 40 | minIndex = j; 41 | 42 | String replacedString = replacedString(s, i-1, minIndex); 43 | 44 | char[] chars = replacedString.toCharArray(); 45 | Arrays.sort(chars, i, s.length()); 46 | 47 | System.out.println(String.copyValueOf(chars)); 48 | 49 | 50 | } 51 | 52 | private static String replacedString(String s, int i, int j) { 53 | 54 | StringBuilder sb = new StringBuilder(s); 55 | char c = s.charAt(i); 56 | sb.setCharAt(i, s.charAt(j)); 57 | sb.setCharAt(j, c); 58 | 59 | return sb.toString(); 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/arrays/PossibleStringWithSpaces.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Print all possible strings that can be made by placing spaces 4 | Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. 5 | 6 | Input: str[] = "ABC" 7 | Output: ABC 8 | AB C 9 | A BC 10 | A B C 11 | 12 | */ 13 | 14 | package arrays; 15 | 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | 19 | /** 20 | * Created by poorvank on 7/31/15. 21 | */ 22 | public class PossibleStringWithSpaces { 23 | 24 | 25 | public static void main(String[] args) { 26 | 27 | String s = "ABC"; 28 | 29 | List list = new ArrayList<>(); 30 | printPermutations(s, list, 0, s.length()); 31 | 32 | } 33 | 34 | private static void printPermutations(String s, List list, int i, int n) { 35 | 36 | if (i == n) { 37 | if (list.get(list.size() - 1) != ' ') 38 | printList(list); 39 | return; 40 | } 41 | 42 | list.add(s.charAt(i)); 43 | printPermutations(s, new ArrayList<>(list), i + 1, n); 44 | 45 | list.add(' '); 46 | printPermutations(s, new ArrayList<>(list), i + 1, n); 47 | 48 | 49 | } 50 | 51 | private static void printList(List list) { 52 | 53 | StringBuilder sb = new StringBuilder(); 54 | for (Character c : list) { 55 | sb.append(c); 56 | } 57 | System.out.println(sb.toString()); 58 | } 59 | 60 | 61 | } 62 | 63 | 64 | /* 65 | 66 | The idea is to use recursion and create a buffer that one by one contains all output strings having spaces. 67 | We keep updating buffer in every recursive call. 68 | 69 | */ -------------------------------------------------------------------------------- /src/arrays/RearrangeEvenOdd.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by poorvank on 8/10/15. 7 | */ 8 | public class RearrangeEvenOdd { 9 | 10 | private static int count = 0; 11 | 12 | public static void main(String[] args) { 13 | 14 | int[] array = new int[]{13,10,21,20}; 15 | 16 | int i = -1, n = array.length; 17 | 18 | 19 | for (int j = 0; j < n; j++) { 20 | 21 | if (array[j] % 2 == 0) { 22 | i++; 23 | if(array[i]!=array[j]) { 24 | count++; 25 | swap(i,j,array); 26 | } 27 | 28 | } 29 | 30 | } 31 | 32 | System.out.println(Arrays.toString(array)); 33 | 34 | int odd = i + 1; 35 | int even = 0; 36 | 37 | 38 | while (even < odd && odd < n && /*because when even crosses odd since both incrementing*/array[even] % 2 == 0) { 39 | 40 | swap(odd, even, array); 41 | odd++; 42 | even += 2; 43 | 44 | } 45 | 46 | System.out.println(Arrays.toString(array) + " " + count); 47 | 48 | } 49 | 50 | 51 | private static void swap(int i, int j, int[] arr) { 52 | 53 | int a = arr[i]; 54 | arr[i] = arr[j]; 55 | arr[j] = a; 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/arrays/SearchDifferenceOne.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Search an element in an array where difference between adjacent elements is 1 4 | Given an array where difference between adjacent elements is 1, 5 | write an algorithm to search for an element in the array and return the 6 | position of the element (return the first occurrence). 7 | 8 | Examples: 9 | 10 | Let element to be searched be x 11 | 12 | Input: arr[] = {8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3} 13 | x = 3 14 | Output: Element 3 found at index 7 15 | 16 | Input: arr[] = {1, 2, 3, 4, 5, 4} 17 | x = 5 18 | Output: Element 5 found at index 4 19 | 20 | */ 21 | package arrays; 22 | 23 | /** 24 | * Created by poorvank on 8/1/15. 25 | */ 26 | public class SearchDifferenceOne { 27 | 28 | public static void main(String[] args) { 29 | 30 | int[] arr = new int[]{8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3}; 31 | int x = 3, n = arr.length; 32 | 33 | int i = 0; 34 | while (i < n) { 35 | 36 | if (arr[i] == x) { 37 | System.out.print("Position of " + x + " is = " + i); 38 | break; 39 | } 40 | 41 | i = i + Math.abs(arr[i] - x); 42 | 43 | } 44 | } 45 | 46 | } 47 | 48 | /* 49 | 50 | The idea is to start comparing from the leftmost element and find the difference between 51 | current array element and x. Let this difference be ‘diff’. From the given property of array, we always know that x 52 | must be at-least ‘diff’ away, so instead of searching one by one, we jump ‘diff’. 53 | 54 | */ 55 | -------------------------------------------------------------------------------- /src/arrays/TripletsArray.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by poorvank on 6/6/15. 7 | */ 8 | public class TripletsArray { 9 | 10 | public static void main(String[] args) { 11 | 12 | int[] arr = new int[]{1, 4, 15, 6, 10, 8}; 13 | int sum = 22; 14 | 15 | Arrays.sort(arr); 16 | 17 | for (int i = 0; i < arr.length; i++) { 18 | 19 | int l = i + 1; 20 | int r = arr.length - 1; 21 | 22 | while (l < r) { 23 | 24 | if (arr[i] + arr[l] + arr[r] == sum) { 25 | System.out.println(arr[i] + " " + arr[l] + " " + arr[r]); 26 | l++; 27 | r--; 28 | } else if (arr[i] + arr[l] + arr[r] < sum) { 29 | l++; 30 | } else { 31 | r--; 32 | } 33 | } 34 | 35 | } 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/arrays/leadersArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to 4 | its right side. 5 | And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. 6 | 7 | */ 8 | 9 | package arrays; 10 | 11 | /** 12 | * Created by poorvank on 4/16/15. 13 | */ 14 | public class leadersArray { 15 | 16 | public static void main(String[] args) { 17 | 18 | int[] leaderArray = new int[]{16, 17, 4, 3, 5, 2}; 19 | 20 | int max = Integer.MIN_VALUE; 21 | 22 | System.out.println("Leaders are as follows "); 23 | 24 | for (int i = leaderArray.length - 1; i >= 0; i--) { 25 | 26 | if (max < leaderArray[i]) { 27 | max = leaderArray[i]; 28 | System.out.print(max + " "); 29 | } 30 | 31 | } 32 | 33 | } 34 | } 35 | 36 | 37 | /* 38 | 39 | Method 2 (Scan from right) 40 | Scan all the elements from right to left in array and keep track of maximum till now. 41 | When maximum changes it’s value, print it. 42 | 43 | O(n) 44 | 45 | */ -------------------------------------------------------------------------------- /src/arrays/twodimensionalarrays/FillRandomizedArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array filled up with 1 to n^2 in randomized order. Fill it in a square matrix of size n. 3 | */ 4 | package arrays.twodimensionalarrays; 5 | 6 | /** 7 | * Created by poorvank.b on 15/04/17. 8 | */ 9 | public class FillRandomizedArray { 10 | 11 | private static void fillArray(int[] arr,int n) { 12 | int[][] matrix = new int[n][n]; 13 | for (int anArr : arr) { 14 | int row = (anArr - 1) / n; 15 | int col = (anArr - 1) % n; 16 | matrix[row][col] = anArr; 17 | } 18 | 19 | for (int i=0;i= 0) { 33 | 34 | if (matrix[i][j] == no) { 35 | System.out.println("Found number at : " + i + " , " + j); 36 | return; 37 | } else if (matrix[i][j] < no) { 38 | i++; 39 | } else { 40 | j--; 41 | } 42 | 43 | } 44 | 45 | System.out.print("Not found"); 46 | 47 | } 48 | 49 | } 50 | 51 | 52 | /* 53 | 54 | 1) Start with top right element 55 | 2) Loop: compare this element e with x 56 | ….i) if they are equal then return its position 57 | …ii) e < x then move it to down (if out of bound of matrix then break return false) 58 | ..iii) e > x then move it to left (if out of bound of matrix then break return false) 59 | 3) repeat the i), ii) and iii) till you find element or returned false 60 | 61 | */ -------------------------------------------------------------------------------- /src/bitmanuplation/AddTwoNumbers.java: -------------------------------------------------------------------------------- 1 | package bitmanuplation; 2 | 3 | /** 4 | * Created by poorvank on 8/27/15. 5 | */ 6 | public class AddTwoNumbers { 7 | 8 | public static void main(String[] args) { 9 | 10 | int a = 7, b = 8; 11 | 12 | System.out.println(add(a, b)); 13 | 14 | } 15 | 16 | private static int add(int a, int b) { 17 | 18 | while (b != 0) { 19 | 20 | int carry = (a & b); 21 | a = (a ^ b); 22 | b = (carry << 1); 23 | 24 | } 25 | 26 | return a; 27 | 28 | } 29 | 30 | } 31 | 32 | /* 33 | 34 | Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing 35 | AND (&) of two bits. 36 | Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. 37 | If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. 38 | To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. 39 | We calculate (x & y) << 1 and add it to x ^ y to get the required result. 40 | 41 | */ -------------------------------------------------------------------------------- /src/bitmanuplation/BitsFlipped.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Count number of bits to be flipped to convert A to B 4 | 5 | */ 6 | 7 | package bitmanuplation; 8 | 9 | import java.util.Scanner; 10 | 11 | /** 12 | * Created by poorvank on 5/2/15. 13 | */ 14 | public class BitsFlipped { 15 | 16 | public static void main(String[] args) { 17 | 18 | Scanner scanner = new Scanner(System.in); 19 | System.out.println("Enter number 1 "); 20 | int num1 = scanner.nextInt(); 21 | System.out.println("Enter number 2 "); 22 | int num2 = scanner.nextInt(); 23 | 24 | System.out.println("Number of flipped bits - " + countFlipped(num1, num2)); 25 | 26 | 27 | } 28 | 29 | 30 | private static int countFlipped(int a, int b) { 31 | 32 | int num = a ^ b; 33 | return countSetBits(num); 34 | 35 | } 36 | 37 | 38 | private static int countSetBits(int n) { 39 | 40 | int count = 0; 41 | while (n > 0) { 42 | n = n & n - 1; 43 | count++; 44 | } 45 | 46 | return count; 47 | 48 | } 49 | } 50 | 51 | 52 | /* 53 | 54 | 1. Calculate XOR of A and B. 55 | a_xor_b = A ^ B 56 | 2. Count the set bits in the above calculated XOR result. 57 | countSetBits(a_xor_b) 58 | XOR of two number will have set bits only at those places where A differs from B. 59 | 60 | Example: 61 | 62 | A = 1001001 63 | B = 0010101 64 | a_xor_b = 1011100 65 | No of bits need to flipped = set bit count in a_xor_b i.e. 4 66 | 67 | */ -------------------------------------------------------------------------------- /src/bitmanuplation/CountSetBits.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Count number of set bits in an integer 4 | 5 | */ 6 | 7 | package bitmanuplation; 8 | 9 | import java.util.Scanner; 10 | 11 | /** 12 | * Created by poorvank on 5/2/15. 13 | */ 14 | public class CountSetBits { 15 | 16 | public static void main(String[] args) { 17 | 18 | Scanner scanner = new Scanner(System.in); 19 | System.out.println("Enter number"); 20 | int n = scanner.nextInt(); 21 | 22 | System.out.println("Number of bits are - " + count(n)); 23 | 24 | } 25 | 26 | private static int count(int n) { 27 | 28 | int count = 0; 29 | while (n != 0) { 30 | 31 | n = n & (n - 1); 32 | count++; 33 | 34 | } 35 | 36 | return count; 37 | 38 | } 39 | 40 | } 41 | 42 | 43 | /* 44 | 45 | in the worst case all the bits of n are set. 46 | since the number of bits is logn to base 2.the loop is executed logn times 47 | 48 | in Brian Kernighan’s Algorithm, the number of times the loop executes is equal to number of set bits in the number. 49 | 50 | */ -------------------------------------------------------------------------------- /src/bitmanuplation/ModularExponentiation.java: -------------------------------------------------------------------------------- 1 | package bitmanuplation; 2 | 3 | /** 4 | * Created by poorvank on 21/01/17. 5 | */ 6 | public class ModularExponentiation { 7 | 8 | private int power(int x,int y,int p) { 9 | 10 | int result = 1; 11 | 12 | x = x % p; 13 | 14 | while (y>0) { 15 | 16 | if((y&1)==1) { 17 | result = (result*x)%p; 18 | } 19 | 20 | y = y>>1; 21 | x = (x*x)%p; 22 | 23 | } 24 | 25 | return result; 26 | 27 | } 28 | 29 | public static void main(String[] args) { 30 | System.out.print(new ModularExponentiation().power(3,5,13)); 31 | } 32 | 33 | } 34 | 35 | 36 | /* 37 | 38 | The problem with above solutions is, overflow may occur for large value of n or x. 39 | Therefore, power is generally evaluated under modulo of a large number. 40 | 41 | Below is the fundamental modular property that is used for efficiently computing power under modular arithmetic. 42 | 43 | (a mod p) (b mod p) ≡ (ab) mod p 44 | 45 | or equivalently 46 | 47 | ( (a mod p) (b mod p) ) mod p = (ab) mod p 48 | 49 | For example a = 50, b = 100, p = 13 50 | 50 mod 13 = 11 51 | 100 mod 13 = 9 52 | 53 | 11*9 ≡ 1500 mod 13 54 | or 55 | 11*9 mod 13 = 1500 mod 13 56 | 57 | 58 | Left Shift 59 | 60 | x = x * 2^value (normal operation) 61 | 62 | x << value (bit-wise operation) 63 | 64 | x = x * 16 (which is the same as 2^4) 65 | 66 | The left shift equivalent would be x = x << 4 67 | 68 | Right Shift 69 | 70 | x = x / 2^value (normal arithmetic operation) 71 | 72 | x >> value (bit-wise operation) 73 | 74 | x = x / 8 (which is the same as 2^3) 75 | 76 | The right shift equivalent would be x = x >> 3 77 | 78 | */ -------------------------------------------------------------------------------- /src/bitmanuplation/Parity.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a C program to find the parity of an unsigned integer 4 | 5 | */ 6 | 7 | package bitmanuplation; 8 | 9 | import java.util.Scanner; 10 | 11 | /** 12 | * Created by poorvank on 5/2/15. 13 | */ 14 | public class Parity { 15 | 16 | public static void main(String[] args) { 17 | 18 | Scanner scanner = new Scanner(System.in); 19 | System.out.println("Enter number"); 20 | 21 | int num = scanner.nextInt(); 22 | System.out.println("Parity is - " + (getParity(num) ? "odd" : "even")); 23 | 24 | 25 | } 26 | 27 | 28 | private static boolean getParity(int n) { 29 | 30 | boolean parity = false; 31 | 32 | while (n > 0) { 33 | 34 | parity = !parity; 35 | n = (n & n - 1); 36 | 37 | } 38 | 39 | return parity; 40 | 41 | } 42 | 43 | } 44 | 45 | 46 | /* 47 | 48 | Parity: Parity of a number refers to whether it contains an odd or even number of 1-bits. 49 | The number has “odd parity”, if it contains odd number of 1-bits and is “even parity” if it contains even number of 1-bits. 50 | Main idea of the below solution is – Loop while n is not 0 and in loop unset one of the set bits and invert parity. 51 | 52 | Time Complexity: The time taken by above algorithm is proportional to the number of bits set. 53 | Worst case complexity is O(Logn). 54 | 55 | Uses: Parity is used in error detection and cryptography. 56 | 57 | */ -------------------------------------------------------------------------------- /src/bitmanuplation/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Check if a number is a power of 2 or not 4 | 5 | */ 6 | 7 | package bitmanuplation; 8 | 9 | import java.util.Scanner; 10 | 11 | /** 12 | * Created by poorvank on 5/1/15. 13 | */ 14 | public class PowerOfTwo { 15 | 16 | public static void main(String[] args) { 17 | 18 | System.out.println("Enter number"); 19 | Scanner scanner = new Scanner(System.in); 20 | int n = scanner.nextInt(); 21 | 22 | if (n==0 || ((n & (n - 1)) == 0)) { 23 | System.out.println("Yes"); 24 | } else { 25 | System.out.println("Nope"); 26 | } 27 | 28 | } 29 | 30 | } 31 | /* 32 | 33 | If we have to check if the number is of the form 2^n then : 34 | n & (n-1) == 0 gives us the answer 35 | 36 | Any power of 2 minus 1 is all ones: (2 N - 1 = 111....b) 37 | 38 | 2 = 2^1. 2-1 = 1 (1b) 39 | 4 = 2^2. 4-1 = 3 (11b) 40 | 8 = 2^3. 8-1 = 7 (111b) 41 | Take 8 for example. 1000 & 0111 = 0000 42 | 43 | So that expression tests if a number is NOT a power of 2. 44 | 45 | 46 | 1.if the number is a power of two already, 47 | then one less will result in a binary number that only has the lower-order bits set. Using & there will do nothing. 48 | 49 | Example with 8: 0100 & (0100 - 1) --> (0100 & 0011) --> 0000 50 | if the number is not a power of two already, then one less will do this, which returns the highest power 51 | of two not greater than num: 52 | 53 | Example with 3: 0011 & (0011 - 1) --> (0011 & 0010) --> 0010 54 | 55 | 56 | */ -------------------------------------------------------------------------------- /src/dyanamicprogramming/CountDistinctPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Count distinct palindromic sub strings in a string 4 | 5 | */ 6 | 7 | package dyanamicprogramming; 8 | 9 | import java.util.HashSet; 10 | import java.util.Set; 11 | 12 | /** 13 | * Created by poorvank on 04/02/17. 14 | */ 15 | public class CountDistinctPalindrome { 16 | 17 | public int count(String s) { 18 | if(null==s || s.length()==0) { 19 | return 0; 20 | } 21 | 22 | int n = s.length(); 23 | 24 | boolean[][] isPalindrome = new boolean[n][n]; 25 | 26 | Set set = new HashSet<>(); 27 | 28 | for (int i=0;i=3) { 28 | arr[i] += arr[i-3]; 29 | } 30 | if(i>=5) { 31 | arr[i] += arr[i-5]; 32 | } 33 | if(i>=10) { 34 | arr[i] += arr[i-10]; 35 | } 36 | } 37 | 38 | System.out.println(Arrays.toString(arr) + " \nNo of ways - " + arr[n]); 39 | 40 | } 41 | 42 | } 43 | 44 | /* 45 | 46 | The idea is to create a table of size n+1 to store counts of all scores from 0 to n. 47 | For every possible move (3, 5 and 10), increment values in table. 48 | 49 | 50 | 51 | For exercise problem we can use this recurrence relation 52 | 53 | T(n) = T(n-3)+T(n-5)+T(n-10) 54 | 55 | T(0)=T(1)=T(2)=T(4)=T(7)=0 56 | T(3)=T(5)=T(6)=T(9)=1 57 | T(8)=T(10)=2 58 | 59 | Now use memoization technique to compute n>10 . 60 | 61 | */ -------------------------------------------------------------------------------- /src/dyanamicprogramming/RoundHouseRobbery.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | all houses at this 4 | place are arranged in a circle. That means the first house is the neighbor of the last 5 | one. Meanwhile, the security system for these houses remain the same as for those in 6 | the previous street. 7 | Given a list of non-negative integers representing the amount of money of each 8 | house, determine the maximum amount of money you can rob tonight without alerting 9 | the police. 10 | 11 | */ 12 | 13 | package dyanamicprogramming; 14 | 15 | /** 16 | * Created by poorvank on 8/25/15. 17 | */ 18 | public class RoundHouseRobbery { 19 | 20 | public static void main(String[] args) { 21 | 22 | int[] arr = new int[]{4, 5, 17, 3, 12, 29, 31}; 23 | int n = arr.length; 24 | //Include 1st house 25 | int[] dp = new int[arr.length - 1]; 26 | 27 | dp[0] = arr[0]; 28 | dp[1] = Math.max(dp[0], arr[1]); 29 | 30 | for (int i = 2; i < n - 1; i++) { 31 | dp[i] = Math.max(dp[i - 1], dp[i - 2] + arr[i]); 32 | } 33 | 34 | //Include Last house 35 | int[] dr = new int[arr.length]; 36 | 37 | dr[0] = 0; 38 | dr[1] = arr[1]; 39 | 40 | for (int i = 2; i < n; i++) { 41 | dr[i] = Math.max(dr[i - 1], dr[i - 2] + arr[i]); 42 | } 43 | 44 | System.out.println(Math.max(dp[n - 2], dr[n - 1])); 45 | 46 | } 47 | 48 | } 49 | 50 | /* 51 | 52 | There are two cases here 1) 1st element is 53 | included and last is not included 2) 1st is not included and last is included. Therefore, 54 | we can use the similar dynamic programming approach to scan the array twice and 55 | get the larger value. 56 | 57 | */ -------------------------------------------------------------------------------- /src/dyanamicprogramming/SumAndDigits.java: -------------------------------------------------------------------------------- 1 | package dyanamicprogramming; 2 | 3 | /** 4 | * Created by poorvank on 9/9/15. 5 | */ 6 | public class SumAndDigits { 7 | 8 | public static void main(String[] args) { 9 | 10 | int n = 2, s = 4; 11 | System.out.println(noOfCombinations(n, s)); 12 | 13 | } 14 | 15 | private static int noOfCombinations(int n, int s) { 16 | 17 | if (n == 0) { 18 | return 1; 19 | } 20 | 21 | int count = 0; 22 | 23 | for (int i = s; i >= 0; i--) { 24 | 25 | count += noOfCombinations(n - 1, s - i); 26 | 27 | } 28 | 29 | return count; 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/dyanamicprogramming/WordBreakDP.java: -------------------------------------------------------------------------------- 1 | package dyanamicprogramming; 2 | 3 | /** 4 | * Created by poorvank on 7/30/15. 5 | */ 6 | public class WordBreakDP { 7 | 8 | public static void main(String[] args) { 9 | 10 | String str = "man"; 11 | System.out.println(wordBreak(str)); 12 | 13 | } 14 | 15 | 16 | private static boolean wordBreak(String str) { 17 | 18 | int size = str.length(); 19 | boolean[] validWord = new boolean[size + 1]; 20 | 21 | validWord[0] = true; 22 | 23 | 24 | for (int i = 0; i <= size; i++) { 25 | 26 | for (int j=0;j 0-(i-1) can be segmented using dictionary 50 | Initial state validWord[0] == true 51 | 52 | 53 | Complexity : Time: O(n square) 54 | 55 | Memory: O(N) 56 | 57 | */ -------------------------------------------------------------------------------- /src/dyanamicprogramming/lis/MaximumSumIncSubSeq.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given an array of n positive integers. Write a program to find the sum of maximum sum 4 | subsequence of the given array such that the intgers in the subsequence are sorted in increasing order. 5 | For example, if input is {1, 101, 2, 3, 100, 4, 5}, then output should be 106 (1 + 2 + 3 + 100), 6 | if the input array is {3, 4, 5, 10}, then output should be 22 (3 + 4 + 5 + 10) and if the input array is 7 | {10, 5, 4, 3}, then output should be 10 8 | 9 | */ 10 | 11 | package dyanamicprogramming.lis; 12 | 13 | /** 14 | * Created by poorvank on 5/22/15. 15 | */ 16 | public class MaximumSumIncSubSeq { 17 | 18 | public static void main(String[] args) { 19 | 20 | int[] array = new int[]{10, 8, 4, 9}; 21 | maxSequence(array); 22 | } 23 | 24 | 25 | private static void maxSequence(int[] array) { 26 | 27 | int[] sumArray = new int[array.length]; 28 | 29 | System.arraycopy(array, 0, sumArray, 0, sumArray.length); 30 | 31 | for (int i = 1; i < array.length; i++) { 32 | for (int j = 0; j < i; j++) { 33 | if (array[i] > array[j] && sumArray[i] < sumArray[j] + array[i]) { 34 | sumArray[i] = sumArray[j] + array[i]; 35 | } 36 | } 37 | } 38 | 39 | int max = 0; 40 | 41 | for (int aSumArray : sumArray) { 42 | if (max < aSumArray) 43 | max = aSumArray; 44 | } 45 | 46 | System.out.println(max); 47 | } 48 | 49 | } 50 | 51 | /* 52 | 53 | Refer Longest Increasing Subsequence 54 | 55 | */ 56 | -------------------------------------------------------------------------------- /src/dyanamicprogramming/matrix/CountAllPaths.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Count all possible paths from top left to bottom right of a mXn matrix 4 | The problem is to count all the possible paths from top left to bottom right of a mXn matrix 5 | with the constraints that from each cell you can either move only to right or down 6 | 7 | */ 8 | package dyanamicprogramming.matrix; 9 | 10 | /** 11 | * Created by poorvank on 5/28/15. 12 | */ 13 | public class CountAllPaths { 14 | 15 | public static void main(String[] args) { 16 | 17 | int[][] matrix = new int[][]{{1, 2, 3}, {4, 5, 6}}; 18 | System.out.println(recursive(matrix.length-1, matrix[0].length-1)); 19 | DPMethod(matrix, matrix.length, matrix[0].length); 20 | } 21 | 22 | private static int recursive( int row, int col) { 23 | 24 | if (row == 0 || col == 0) { 25 | return 1; 26 | } 27 | 28 | return recursive(row - 1, col) + recursive(row, col - 1); 29 | 30 | } 31 | 32 | private static void DPMethod(int[][] matrix, int row, int col) { 33 | 34 | int[][] count = new int[row][col]; 35 | 36 | // Count of paths to reach any cell in first column is 1 37 | for (int i = 0; i < row; i++) 38 | count[i][0] = 1; 39 | 40 | // Count of paths to reach any cell in first column is 1 41 | for (int j = 0; j < col; j++) 42 | count[0][j] = 1; 43 | 44 | for (int i = 1; i < row; i++) { 45 | for (int j = 1; j < col; j++) { 46 | count[i][j] = count[i - 1][j] + count[i][j - 1]; 47 | } 48 | } 49 | 50 | System.out.println(count[row - 1][col - 1]); 51 | 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/geometry/Point.java: -------------------------------------------------------------------------------- 1 | package geometry; 2 | 3 | /** 4 | * Created by poorvank on 15/12/16. 5 | */ 6 | public class Point { 7 | int x,y; 8 | 9 | public Point(int x, int y) { 10 | this.x = x; 11 | this.y = y; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return "Point{" + 17 | "x=" + x + 18 | ", y=" + y + 19 | '}'; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/graphs/PrintPaths.java: -------------------------------------------------------------------------------- 1 | package graphs; 2 | 3 | import utility.graphClasses.Graph; 4 | 5 | import java.util.ArrayList; 6 | 7 | /** 8 | * Created by poorvank on 4/2/15. 9 | */ 10 | public class PrintPaths { 11 | 12 | public static void main(String[] args) { 13 | 14 | Graph graph = new Graph(4); 15 | graph.addEdge(0,1); 16 | graph.addEdge(1,2); 17 | graph.addEdge(2,3); 18 | 19 | 20 | boolean[] visited = new boolean[graph.getVertexCount()]; 21 | 22 | for (int i = 0; i < graph.getVertexCount(); i++) { 23 | visited[i] = false; 24 | } 25 | print(0, 2, visited, new ArrayList(), graph); 26 | 27 | } 28 | 29 | private static void print(int s, int d, boolean[] visited, ArrayList arrayList, Graph graph) { 30 | 31 | visited[s] = true; 32 | arrayList.add(s); 33 | 34 | if (s == d) { 35 | System.out.println(arrayList.toString()); 36 | } else { 37 | 38 | for (Integer i : graph.getAdj(s)) { 39 | //prevent cycle 40 | if (!visited[i]) { 41 | print(i, d, visited, arrayList, graph); 42 | } 43 | } 44 | 45 | } 46 | 47 | arrayList.remove(arrayList.size() - 1); 48 | visited[s] = false; 49 | 50 | } 51 | 52 | } 53 | 54 | 55 | /* 56 | 57 | The idea is to do Depth First Traversal of given directed graph. 58 | Start the traversal from source. Keep storing the visited vertices in an array say ‘path[]’. 59 | If we reach the destination vertexToConsider, print contents of path[]. 60 | The important thing is to mark current vertices in path[] as visited also, so that the traversal doesn’t go in a cycle. 61 | 62 | */ -------------------------------------------------------------------------------- /src/graphs/ShortestPath.java: -------------------------------------------------------------------------------- 1 | package graphs; 2 | 3 | /** 4 | * Created by poorvank on 4/6/15. 5 | */ 6 | public class ShortestPath { 7 | 8 | public static void main(String[] args) { 9 | 10 | int graph[][] = new int[][]{{0, 10, 3, 2}, 11 | {-1, 0, -1, 7}, 12 | {-1, -1, 0, 6}, 13 | {-1, -1, -1, 0} 14 | }; 15 | 16 | System.out.println("MIN WEIGHT - " + minWeightPath(0, 3, 2, graph)); 17 | 18 | } 19 | 20 | 21 | private static int minWeightPath(int source, int destination, int edgeCount, int[][] graph) { 22 | 23 | 24 | if (edgeCount < 0) { 25 | return Integer.MAX_VALUE; 26 | } 27 | 28 | if (edgeCount == 1 && graph[source][destination] != -1) { 29 | return graph[source][destination]; 30 | } 31 | 32 | if (edgeCount == 0 && source == destination) { 33 | return 0; 34 | } 35 | 36 | int res = Integer.MAX_VALUE; 37 | 38 | for (int i = 0; i < 4; i++) { 39 | 40 | /* 41 | If we don't put source!=i && destination!=i check 42 | infinite loop occurs in case of graph[source][i]==0 43 | 44 | */ 45 | 46 | if (graph[source][i] != -1 && source != i && destination != i) { 47 | 48 | int rec_res = minWeightPath(i, destination, edgeCount - 1, graph); 49 | if (rec_res != -1) { 50 | res = min(res, rec_res + graph[source][i]); 51 | } 52 | 53 | 54 | } 55 | 56 | } 57 | 58 | return res; 59 | 60 | 61 | } 62 | 63 | private static int min(int a, int b) { 64 | 65 | return a < b ? a : b; 66 | 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/graphs/unionFind/DetectCycleUF.java: -------------------------------------------------------------------------------- 1 | package graphs.unionFind; 2 | 3 | import utility.edgeClasses.Edge; 4 | import utility.graphClasses.EdgeWeightedGraph; 5 | 6 | /** 7 | * Created by poorvank on 18/06/16. 8 | */ 9 | public class DetectCycleUF { 10 | 11 | public static void main(String[] args) { 12 | 13 | EdgeWeightedGraph graph = new EdgeWeightedGraph(6); 14 | Edge e1 = new Edge(0,1,2.2); 15 | Edge e2 = new Edge(1,2,3.2); 16 | Edge e3 = new Edge(2,3,4.4); 17 | Edge e4 = new Edge(3,4,3.2); 18 | Edge e5 = new Edge(4,5,2.2); 19 | Edge e6 = new Edge(5,2,8.7); 20 | graph.addEdge(e1); 21 | graph.addEdge(e2); 22 | graph.addEdge(e3); 23 | graph.addEdge(e4); 24 | graph.addEdge(e5); 25 | graph.addEdge(e6); 26 | 27 | UF uf =new UF(graph.getVertexCount()); 28 | 29 | boolean hasCycle = false; 30 | 31 | for (Edge e : graph.edges()) { 32 | int source = e.either(); 33 | int destination = e.other(source); 34 | 35 | if(!uf.isConnected(source,destination)) { 36 | uf.union(source,destination); 37 | } else { 38 | System.out.println("Cycle found between vertices - " + source + " and " + destination); 39 | hasCycle = true; 40 | break; 41 | } 42 | 43 | } 44 | 45 | if(!hasCycle) { 46 | System.out.println("No cycle found"); 47 | } 48 | 49 | 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/inputFiles/BFInput: -------------------------------------------------------------------------------- 1 | 8 2 | 15 3 | 4 5 0.35 4 | 5 4 0.35 5 | 4 7 0.37 6 | 5 7 0.28 7 | 7 5 0.28 8 | 5 1 0.32 9 | 0 4 0.38 10 | 0 2 0.26 11 | 7 3 0.39 12 | 1 3 0.29 13 | 2 7 0.34 14 | 6 2 -1.20 15 | 3 6 0.52 16 | 6 0 -1.40 17 | 6 4 -1.25 -------------------------------------------------------------------------------- /src/inputFiles/CPMInput: -------------------------------------------------------------------------------- 1 | 10 2 | 41.0 1 7 9 3 | 51.0 2 4 | 50.0 5 | 36.0 6 | 38.0 7 | 45.0 8 | 21.0 3 8 9 | 32.0 3 8 10 | 32.0 2 11 | 29.0 4 6 -------------------------------------------------------------------------------- /src/inputFiles/FordFulkersonInput: -------------------------------------------------------------------------------- 1 | 6 2 | 0 2 3.0 0.0 3 | 0 1 2.0 0.0 4 | 1 4 1.0 0.0 5 | 1 3 3.0 0.0 6 | 2 3 1.0 0.0 7 | 2 4 1.0 0.0 8 | 3 5 2.0 0.0 9 | 4 5 3.0 0.0 -------------------------------------------------------------------------------- /src/inputFiles/newinput.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 13 3 | 5 4 0.35 4 | 4 7 0.37 5 | 5 7 0.28 6 | 5 1 0.32 7 | 4 0 0.38 8 | 0 2 0.26 9 | 3 7 0.39 10 | 1 3 0.29 11 | 7 2 0.34 12 | 6 2 0.40 13 | 3 6 0.52 14 | 6 0 0.58 15 | 6 4 0.93 -------------------------------------------------------------------------------- /src/inputFiles/rates.txt: -------------------------------------------------------------------------------- 1 | 5 2 | USD 1 0.741 0.657 1.061 1.005 3 | EUR 1.349 1 0.888 1.433 1.366 4 | GBP 1.521 1.126 1 1.614 1.538 5 | CHF 0.942 0.698 0.619 1 0.953 6 | CAD 0.995 0.732 0.650 1.049 1 -------------------------------------------------------------------------------- /src/inputFiles/routes.txt: -------------------------------------------------------------------------------- 1 | JFK MCO 2 | ORD DEN 3 | ORD HOU 4 | DFW PHX 5 | JFK ATL 6 | ORD DFW 7 | ORD PHX 8 | ATL HOU 9 | DEN PHX 10 | PHX LAX 11 | JFK ORD 12 | DEN LAS 13 | DFW HOU 14 | ORD ATL 15 | LAS LAX 16 | ATL MCO 17 | HOU MCO 18 | LAS PHX 19 | -------------------------------------------------------------------------------- /src/inputFiles/tinyCG.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 8 3 | 0 5 4 | 2 4 5 | 2 3 6 | 1 2 7 | 0 1 8 | 3 4 9 | 3 5 10 | 0 2 11 | -------------------------------------------------------------------------------- /src/inputFiles/tinyEWG.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 16 3 | 4 5 0.35 4 | 4 7 0.37 5 | 5 7 0.28 6 | 0 7 0.16 7 | 1 5 0.32 8 | 0 4 0.38 9 | 2 3 0.17 10 | 1 7 0.19 11 | 0 2 0.26 12 | 1 2 0.36 13 | 1 3 0.29 14 | 2 7 0.34 15 | 6 2 0.40 16 | 3 6 0.52 17 | 6 0 0.58 18 | 6 4 0.93 19 | -------------------------------------------------------------------------------- /src/inputFiles/tinyUF.txt: -------------------------------------------------------------------------------- 1 | 10 2 | 4 3 3 | 3 8 4 | 6 5 5 | 9 4 6 | 2 1 7 | 8 9 8 | 5 0 9 | 7 2 10 | 6 1 11 | 1 0 12 | 6 7 13 | -------------------------------------------------------------------------------- /src/interviews/RoomFloors.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a building with infinite number of floors. The number of rooms on each floor are 20,21,20,21.. and so on starting from 4 | the ground floor. The room number starts from 1 and keeps on increasing. Given a room number, 5 | find the floor on which room lies and the position of room from the left. 6 | 7 | */ 8 | 9 | package interviews; 10 | 11 | /** 12 | * Created by poorvank on 7/9/15. 13 | */ 14 | public class RoomFloors { 15 | 16 | public static void main(String[] args) { 17 | 18 | findFloor(41); 19 | findFloor(56); 20 | 21 | 22 | } 23 | 24 | private static void findFloor(int n) { 25 | 26 | int x = n % 41; 27 | int room = 0; 28 | int floor = (n / 41) * 2; 29 | 30 | //if room number is a divisor of 41 meaning it is the last on even numbered floor 31 | if (x == 0) { 32 | room = 21; 33 | } 34 | // Dry run and understand 35 | else if (x > 0 && x < 21) { 36 | floor++; 37 | room = x; 38 | } 39 | //if greater than or equal to 21 then its 2 floors up 40 | else { 41 | room = x - 20; 42 | floor = floor + 2; 43 | } 44 | 45 | System.out.println("floor = " + floor + " room no =" + room); 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/interviews/SumOfDependencies.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | You were given a directed graph with n nodes. Given graph was connected. 4 | If there is an edge from u to v then u depends on v. Find out the sum of dependencies for every node. 5 | 6 | */ 7 | 8 | package interviews; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * Created by poorvank on 4/25/15. 15 | */ 16 | 17 | class DGraphNode { 18 | 19 | int info; 20 | List childList; 21 | 22 | public DGraphNode(int n) { 23 | info = n; 24 | childList = new ArrayList<>(); 25 | } 26 | 27 | 28 | } 29 | 30 | class DGraph { 31 | 32 | int count; 33 | DGraphNode[] array; 34 | 35 | public DGraph(int n) { 36 | count = n; 37 | array = new DGraphNode[n]; 38 | 39 | for (int i = 0; i < n; i++) { 40 | array[i] = new DGraphNode(i); 41 | } 42 | } 43 | 44 | public void addEdge(int a, int b) { 45 | 46 | array[a].childList.add(b); 47 | 48 | } 49 | 50 | public int sumOfDependencies() { 51 | 52 | int sum = 0; 53 | for (int i = 0; i < array.length; i++) { 54 | sum += array[i].childList.size(); 55 | } 56 | 57 | return sum; 58 | 59 | } 60 | 61 | 62 | } 63 | 64 | public class SumOfDependencies { 65 | 66 | public static void main(String[] args) { 67 | 68 | DGraph graph = new DGraph(4); 69 | 70 | graph.addEdge(0, 2); 71 | graph.addEdge(0, 4); 72 | graph.addEdge(2, 4); 73 | graph.addEdge(1, 4); 74 | 75 | System.out.println("Sum of dependencies = " + graph.sumOfDependencies()); 76 | 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/linkedlist/CustomSortLinkList.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Sort a linked list of 0s, 1s and 2s 4 | Given a linked list of 0s, 1s and 2s, sort it. 5 | 6 | */ 7 | 8 | package linkedlist; 9 | 10 | /** 11 | * Created by poorvank on 5/7/15. 12 | */ 13 | public class CustomSortLinkList { 14 | 15 | public static void main(String[] args) { 16 | 17 | LLNode head = Input.listInput(); 18 | LinkedList.printList(head); 19 | sort(head); 20 | System.out.println(); 21 | LinkedList.printList(head); 22 | 23 | } 24 | 25 | private static void sort(LLNode head) { 26 | 27 | int[] countArr = new int[]{0, 0, 0}; 28 | 29 | LLNode tmp = head; 30 | 31 | while (tmp != null) { 32 | countArr[tmp.info]++; 33 | tmp = tmp.link; 34 | } 35 | 36 | tmp = head; 37 | 38 | int i = 0; 39 | 40 | while (tmp != null) { 41 | 42 | if (countArr[i] == 0) { 43 | i++; 44 | } else { 45 | tmp.info = i; 46 | tmp = tmp.link; 47 | countArr[i]--; 48 | } 49 | 50 | } 51 | 52 | } 53 | 54 | } 55 | 56 | /* 57 | 58 | Following steps can be used to sort the given linked list. 59 | 1) Traverse the list and count the number of 0s, 1s and 2s. Let the counts be n1, n2 and n3 respectively. 60 | 2) Traverse the list again, fill the first n1 nodes with 0, then n2 nodes with 1 and finally n3 nodes with 2. 61 | 62 | */ -------------------------------------------------------------------------------- /src/miscellaneous/BinomialCoefficient.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Write a function that takes two parameters n and k and returns the value of Binomial Coefficient 4 | C(n, k). For example, your function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2. 5 | 6 | */ 7 | 8 | package miscellaneous; 9 | 10 | /** 11 | * Created by poorvank on 7/5/15. 12 | */ 13 | public class BinomialCoefficient { 14 | 15 | public static void main(String[] args) { 16 | 17 | int n = 8, k = 2; 18 | 19 | System.out.println(calculateBinomialCoefficient(n, k)); 20 | 21 | } 22 | 23 | private static int calculateBinomialCoefficient(int n, int k) { 24 | 25 | if (k < n - k) { 26 | k = n - k; 27 | } 28 | 29 | int res = 1; 30 | 31 | for (int i = 0; i < k; i++) { 32 | 33 | res *= (n - i); 34 | res /= (i + 1); 35 | 36 | } 37 | 38 | return res; 39 | 40 | } 41 | 42 | } 43 | 44 | /* 45 | 46 | The value of C(n, k) can be calculated in O(k) time and O(1) extra space. 47 | 48 | C(n, k) = n! / (n-k)! * k! 49 | = [n * (n-1) *....* 1] / [ ( (n-k) * (n-k-1) * .... * 1) * 50 | ( k * (k-1) * .... * 1 ) ] 51 | After simplifying, we get 52 | C(n, k) = [n * (n-1) * .... * (n-k+1)] / [k * (k-1) * .... * 1] 53 | 54 | Also, C(n, k) = C(n, n-k) // we can change r to n-r if r > n-r 55 | 56 | */ -------------------------------------------------------------------------------- /src/miscellaneous/DigitsAfterDecimal.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a positive integer n, print first k digits after point in value of 1/n. 4 | Your program should avoid overflow and floating point arithmetic. 5 | 6 | */ 7 | 8 | package miscellaneous; 9 | 10 | import java.util.Scanner; 11 | 12 | public class DigitsAfterDecimal { 13 | 14 | public static void main(String[] args) { 15 | 16 | System.out.println("Enter the number : "); 17 | Scanner sc = new Scanner(System.in); 18 | int n = sc.nextInt(); 19 | 20 | System.out.println("Enter number of digits after decimal : "); 21 | int k = sc.nextInt(); 22 | 23 | int rem = 1; 24 | 25 | for (int i = 1; i <= k; i++) { 26 | 27 | System.out.println("digit number " + i + " is = " + (10 * rem) / n); 28 | 29 | rem = (rem * 10) % n; 30 | } 31 | 32 | } 33 | 34 | } 35 | 36 | /* 37 | 38 | 39 | Let us consider an example n = 7, k = 3. 40 | The first digit of 1/7 is ‘1’, it can be obtained by doing integer value of 10/7. 41 | Remainder of 10/7 is 3. Next digit is 4 which can be obtained by taking integer value of 30/7. 42 | Remainder of 30/7 is 2. Next digits is 2 which can be obtained by taking integer value of 20/7 43 | 44 | 45 | */ -------------------------------------------------------------------------------- /src/miscellaneous/HornersMethod.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + … + c1x + c0 and a value of x, 4 | find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer. 5 | 6 | Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for xn-1 and so on. 7 | 8 | */ 9 | 10 | package miscellaneous; 11 | 12 | /** 13 | * Created by poorvank on 04/07/16. 14 | */ 15 | public class HornersMethod { 16 | 17 | private int x; 18 | 19 | public HornersMethod(int x) { 20 | this.x = x; 21 | } 22 | 23 | public int calculate(int[] pol) { 24 | 25 | int n = pol.length; 26 | int result = pol[0]; 27 | 28 | for (int i=1;i> 1; 31 | 32 | } 33 | 34 | return result; 35 | 36 | } 37 | 38 | } 39 | 40 | /* 41 | 42 | How does this work? 43 | The value of a*b is same as (a*2)*(b/2) if b is even, otherwise the value is same as ((a*2)*(b/2) + a). 44 | In the while loop, we keep multiplying ‘a’ with 2 and keep dividing ‘b’ by 2. If ‘b’ becomes odd in loop, 45 | we add ‘a’ to ‘res’. When value of ‘b’ becomes 1, the value of ‘res’ + ‘a’, gives us the result. 46 | Note that when ‘b’ is a power of 2, the ‘res’ would remain 0 and ‘a’ would have the multiplication. 47 | 48 | 49 | */ -------------------------------------------------------------------------------- /src/miscellaneous/SubsetCondition.java: -------------------------------------------------------------------------------- 1 | package miscellaneous; 2 | 3 | import java.util.TreeSet; 4 | 5 | /** 6 | * Created by poorvank.b on 02/12/17. 7 | */ 8 | public class SubsetCondition { 9 | 10 | public static int count(int[] arr) { 11 | 12 | TreeSet set = new TreeSet<>(); 13 | for (int element : arr) { 14 | set.add(element); 15 | } 16 | 17 | int n = arr.length; 18 | int[] greaterOnRight = new int[n]; 19 | int[] greaterOnLeft = new int[n]; 20 | int[] smallerOnRight = new int[n]; 21 | int[] smallerOnLeft = new int[n]; 22 | 23 | smallerOnLeft[0]=-1; 24 | greaterOnLeft[0]=-1; 25 | smallerOnRight[n-1]=-1; 26 | greaterOnRight[n-1]=-1; 27 | 28 | return 1; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/stack/CheckBalancedParenthesis.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | import utility.Stack; 3 | 4 | /** 5 | * Created by poorvank on 8/4/15. 6 | */ 7 | public class CheckBalancedParenthesis { 8 | 9 | public static void main(String[] args) { 10 | 11 | String str = "[{()}]"; 12 | System.out.print(checkBalanced(str)); 13 | 14 | 15 | } 16 | 17 | private static boolean checkBalanced(String string) { 18 | 19 | Stack stack = new Stack<>(); 20 | 21 | int i = 0; 22 | 23 | while (i < string.length()) { 24 | 25 | char character; 26 | 27 | if (string.charAt(i) == '{' || string.charAt(i) == '(' || string.charAt(i) == '[') { 28 | stack.push(string.charAt(i)); 29 | } else if (string.charAt(i) == '}' || string.charAt(i) == ')' || string.charAt(i) == ']') { 30 | if (!stack.isEmpty()) { 31 | character = stack.pop(); 32 | if (!isMatching(character, string.charAt(i))) { 33 | return false; 34 | } 35 | } else { 36 | return false; 37 | } 38 | } 39 | 40 | i++; 41 | 42 | } 43 | 44 | return stack.size() == 0; 45 | 46 | } 47 | 48 | 49 | private static boolean isMatching(char character1, char character2) { 50 | 51 | return character1 == '(' && character2 == ')' || character1 == '{' && character2 == '}' || character1 == '[' && character2 == ']'; 52 | 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/stack/FirstGreaterNumberOnLeft.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | 3 | import java.util.Arrays; 4 | import utility.Stack; 5 | /** 6 | * Created by poorvank on 8/27/15. 7 | */ 8 | public class FirstGreaterNumberOnLeft { 9 | 10 | public static void main(String[] args) { 11 | 12 | int[] arr = new int[]{5, 3, 2, 4, 8, 6}; 13 | int n = arr.length; 14 | 15 | Stack stack = new Stack<>(); 16 | stack.push(n - 1); 17 | 18 | for (int i = n - 2; i >= 0; i--) { 19 | 20 | while (!stack.isEmpty() && arr[i] > arr[stack.peek()]) { 21 | arr[stack.peek()] = arr[i]; 22 | stack.pop(); 23 | } 24 | stack.push(i); 25 | 26 | } 27 | 28 | while (!stack.isEmpty()) { 29 | arr[stack.pop()] = -1; 30 | } 31 | 32 | System.out.println(Arrays.toString(arr)); 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/strings/AnagramDiff.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | /* 4 | 5 | No of changes to convert to one string to another. Final result both are anagrams 6 | 7 | */ 8 | public class AnagramDiff { 9 | 10 | static int diff(String a,String b) { 11 | 12 | int[] count = new int[26]; 13 | 14 | if(a.length()==b.length()) { 15 | 16 | int result = 0; 17 | 18 | for (int i=0;i=1) { 24 | count[b.charAt(i)-'a']--; 25 | } 26 | } 27 | 28 | for (int i=0;i<26;i++) { 29 | if(count[i]>0) { 30 | result += count[i]; 31 | } 32 | } 33 | 34 | return result; 35 | 36 | } 37 | return -1; 38 | } 39 | 40 | public static void main(String[] args) { 41 | String a = "hhpddlnnsjfoyxpci"; 42 | String b = "ioigvjqzfbpllssuj"; 43 | System.out.println(diff(a,b)); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/strings/ArrayOfSuffixes.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by poorvank on 08/07/16. 7 | */ 8 | public class ArrayOfSuffixes { 9 | 10 | public static String[] suffixes(String str) { 11 | 12 | int length = str.length(); 13 | String[] suffix = new String[length]; 14 | for (int i=0;i generateAbbreviations(String word){ 18 | List ret = new ArrayList<>(); 19 | backtrack(ret, word, 0, "", 0); 20 | 21 | return ret; 22 | } 23 | 24 | private void backtrack(List ret, String word, int pos, String cur, int count){ 25 | if(pos==word.length()){ 26 | if(count > 0) cur += count; 27 | ret.add(cur); 28 | } 29 | else{ 30 | backtrack(ret, word, pos + 1, cur, count + 1); 31 | backtrack(ret, word, pos+1, cur + (count>0 ? count : "") + word.charAt(pos), 0); 32 | } 33 | } 34 | 35 | public static void main(String[] args) { 36 | System.out.print(new GeneralizedAbbreviation().generateAbbreviations("AB")); 37 | } 38 | 39 | } 40 | 41 | /* 42 | 43 | For every character, we can keep it or abbreviate it. To keep it, we add it to the current solution and carry on backtracking. 44 | To abbreviate it, we omit it in the current solution, but increment the count, which indicates how many characters have we abbreviated. 45 | When we reach the end or need to put a character in the current solution, and count is bigger than zero, we add the number into the solution. 46 | 47 | */ -------------------------------------------------------------------------------- /src/strings/print/GenerateBinaryStrings.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Generate all binary strings from given pattern 4 | Given a string containing of ‘0’, ‘1’ and ‘?’ wildcard characters, generate all binary strings that can be formed by 5 | replacing each wildcard character by ‘0’ or ‘1’. 6 | 7 | Input str = "1??0?101" 8 | Output: 9 | 10000101 10 | 10001101 11 | 10100101 12 | 10101101 13 | 11000101 14 | 11001101 15 | 11100101 16 | 11101101 17 | 18 | */ 19 | 20 | package strings.print; 21 | 22 | /** 23 | * Created by poorvank on 25/07/16. 24 | */ 25 | public class GenerateBinaryStrings { 26 | 27 | 28 | private static void generate(String str,int index) { 29 | 30 | if(index == str.length()) { 31 | System.out.println(str); 32 | return; 33 | } 34 | 35 | if(str.charAt(index)=='?') { 36 | 37 | StringBuilder sb = new StringBuilder(str); 38 | sb.setCharAt(index,'0'); 39 | str = sb.toString(); 40 | generate(str,index+1); 41 | 42 | 43 | 44 | sb = new StringBuilder(str); 45 | sb.setCharAt(index,'1'); 46 | str = sb.toString(); 47 | generate(str,index+1); 48 | 49 | } 50 | else { 51 | generate(str,index+1); 52 | } 53 | 54 | } 55 | 56 | public static void main(String[] args) { 57 | 58 | String s = "1??0?101"; 59 | 60 | generate(s,0); 61 | 62 | } 63 | 64 | } 65 | 66 | /* 67 | 68 | We pass index of next character to the recursive function. If the current character is a wildcard character ‘?’, 69 | we replace it by ‘0’ or ‘1’ and recurse for remaining characters. We print the string if we reaches its end. 70 | 71 | */ -------------------------------------------------------------------------------- /src/strings/print/PermutationOfString.java: -------------------------------------------------------------------------------- 1 | package strings.print; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Created by poorvank on 7/21/15. 8 | */ 9 | public class PermutationOfString { 10 | 11 | static Set set = new HashSet<>(); 12 | 13 | public static void main(String[] args) { 14 | 15 | String str = "ABCA"; 16 | printPermutation("", str); 17 | 18 | } 19 | 20 | private static void printPermutation(String prefix, String str) { 21 | 22 | int n = str.length(); 23 | if (n == 0) { 24 | /* 25 | To Handle Duplicates 26 | */ 27 | if(!set.contains(prefix)) { 28 | System.out.println(prefix); 29 | set.add(prefix); 30 | } 31 | } else { 32 | for (int i = 0; i < n; i++) { 33 | 34 | 35 | /* System.out.println("prefix is - " + prefix + " - " + i); 36 | System.out.println("SS " + str + " " + str.substring(0, i) + " - " + prefix + str.charAt(i) + " - " + i);*/ 37 | 38 | printPermutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)); 39 | 40 | /* System.out.println("return " + i);*/ 41 | } 42 | } 43 | 44 | } 45 | 46 | } 47 | 48 | //See images -------------------------------------------------------------------------------- /src/trees/heap/KthSmallestArrayElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | K’th Smallest/Largest Element in Unsorted Array | Set 1 4 | Given an array and a number k where k is smaller than size of array, 5 | we need to find the k’th smallest element in the given array. It is given that ll array elements are distinct. 6 | 7 | Examples: 8 | 9 | Input: arr[] = {7, 10, 4, 3, 20, 15} 10 | k = 3 11 | Output: 7 12 | 13 | Input: arr[] = {7, 10, 4, 3, 20, 15} 14 | k = 4 15 | Output: 10 16 | 17 | */ 18 | 19 | package trees.heap; 20 | 21 | import utility.priorityQueueClasses.MinPriorityQueue; 22 | 23 | /** 24 | * Created by poorvank on 7/3/15. 25 | */ 26 | public class KthSmallestArrayElement { 27 | 28 | public static void main(String[] args) { 29 | 30 | Integer[] arr = new Integer[]{4, 7, 10}; 31 | 32 | int k = 1; 33 | 34 | MinPriorityQueue pq = new MinPriorityQueue<>(arr); 35 | 36 | int kthSmallestElement = -1; 37 | 38 | while (k!=0) { 39 | if(!pq.isEmpty()) { 40 | kthSmallestElement = pq.delMin(); 41 | } 42 | k--; 43 | } 44 | 45 | System.out.println(" smallest element is = " + kthSmallestElement); 46 | 47 | 48 | } 49 | 50 | } 51 | 52 | 53 | /* 54 | 55 | We can find k’th smallest element in time complexity better than O(nLogn). 56 | A simple optimization is to create a Min Heap of the given n elements and call extractMin() k times. 57 | 58 | */ -------------------------------------------------------------------------------- /src/trees/heap/MaxNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given two arrays where digits of one array represent a number,maximize the number 4 | by replacing it with elements of second array. 5 | eg: 6 | arr = {3,1,4,5,6} 7 | sec = {1,9,5,2,3} 8 | after replacement 9 | arr = {9,5,4,5,6} 10 | one digit of sec can be used to replace only once. 11 | 12 | */ 13 | 14 | package trees.heap; 15 | 16 | import utility.priorityQueueClasses.MaxPriorityQueue; 17 | 18 | import java.util.Arrays; 19 | 20 | /** 21 | * Created by poorvank on 12/19/15. 22 | */ 23 | public class MaxNumber { 24 | 25 | public static void main(String[] args) { 26 | 27 | Integer[] primaryArray = new Integer[]{3, 1, 4, 5, 6}; 28 | Integer[] secArray = new Integer[]{1, 9, 5, 2, 3}; 29 | int length = secArray.length; 30 | 31 | MaxPriorityQueue pq = new MaxPriorityQueue<>(secArray); 32 | 33 | for (int i=0;iprimaryArray[i]) { 40 | primaryArray[i] = pq.delMax(); 41 | } 42 | } 43 | 44 | System.out.println("New array - " + Arrays.toString(primaryArray)); 45 | 46 | } 47 | 48 | } 49 | 50 | /* 51 | 52 | construct a getMaximumElement heap of sec array.And ran a loop checking if the getMaximumElement element of sec was greater than the element 53 | in arr and then replaced it in arr and deleted the same from the maxheap. 54 | 55 | */ -------------------------------------------------------------------------------- /src/trees/heap/MinToMaxHeap.java: -------------------------------------------------------------------------------- 1 | package trees.heap; 2 | 3 | import utility.priorityQueueClasses.MaxPriorityQueue; 4 | 5 | /** 6 | * Created by poorvank on 11/06/16. 7 | */ 8 | public class MinToMaxHeap { 9 | 10 | public static void main(String[] args) { 11 | Integer[] arr = new Integer[]{3,5,9,6,8,20,10,12,18,9}; 12 | MaxPriorityQueue pq = new MaxPriorityQueue<>(arr); 13 | for (Integer element : pq) { 14 | System.out.print(element + " "); 15 | } 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/trees/tree/AddGreaterValues.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a Binary Search Tree (BST), 4 | modify it so that all greater values in the given BST are added to every node. For example, consider the following BST. 5 | 6 | 50 7 | / \ 8 | 30 70 9 | / \ / \ 10 | 20 40 60 80 11 | 12 | The above tree should be modified to following 13 | 14 | 260 15 | / \ 16 | 330 150 17 | / \ / \ 18 | 350 300 210 80 19 | 20 | */ 21 | 22 | package trees.tree; 23 | 24 | /** 25 | * Created by poorvank on 6/8/15. 26 | */ 27 | public class AddGreaterValues { 28 | 29 | private static int sum = 0; 30 | 31 | public static void main(String[] args) { 32 | 33 | Node root = Input.treeInput(); 34 | root = new AddGreaterValues().reverseInorder(root); 35 | Traversal.in_Order(root); 36 | 37 | } 38 | 39 | private Node reverseInorder(Node root) { 40 | 41 | if (root == null) { 42 | return null; 43 | } 44 | reverseInorder(root.right); 45 | sum = sum + root.info; 46 | root.info = sum; 47 | reverseInorder(root.left); 48 | return root; 49 | 50 | } 51 | 52 | } 53 | 54 | 55 | /* 56 | 57 | We can do it using a single traversal. The idea is to use following BST property. 58 | If we do reverse Inorder traversal of BST, we get all nodes in decreasing order. 59 | We do reverse Inorder traversal and keep track of the sum of all nodes visited so far, we add this sum to every node. 60 | 61 | */ -------------------------------------------------------------------------------- /src/trees/tree/ArrayToBST.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class ArrayToBST { 7 | 8 | public static void main(String[] args) { 9 | 10 | Scanner sc = new Scanner(System.in); 11 | System.out.println("Enter number of integers"); 12 | int n = sc.nextInt(); 13 | int[] arr = new int[n]; 14 | 15 | System.out.println("Enter numbers"); 16 | for (int i = 0; i < n; i++) { 17 | arr[i] = sc.nextInt(); 18 | } 19 | 20 | Arrays.sort(arr); 21 | 22 | Traversal.pre_Order(createTree(arr, 0, n - 1)); 23 | 24 | } 25 | 26 | private static Node createTree(int[] arr, int start, int end) { 27 | 28 | if (start > end) { 29 | return null; 30 | } 31 | 32 | int mid = (start + end) / 2; 33 | 34 | Node root = new Node(arr[mid]); 35 | 36 | root.left = createTree(arr, start, mid - 1); 37 | 38 | root.right = createTree(arr, mid + 1, end); 39 | 40 | return root; 41 | 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /src/trees/tree/BST_LCA.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | import java.util.Scanner; 4 | 5 | public class BST_LCA { 6 | 7 | public static void main(String[] args) { 8 | 9 | Node root = Input.treeInput(); 10 | System.out.println("Enter node 1 : "); 11 | Scanner sc = new Scanner(System.in); 12 | int n1 = sc.nextInt(); 13 | System.out.println("Enter node 2 : "); 14 | int n2 = sc.nextInt(); 15 | System.out.print("LCA Of two nodes is - " + returnLCA(root, n1, n2)); 16 | 17 | } 18 | 19 | private static int returnLCA(Node root, int n1, int n2) { 20 | 21 | if (root.info > n1 && root.info <= n2) { 22 | return root.info; 23 | } else if (root.info > n1 && root.info > n2) { 24 | return returnLCA(root.left, n1, n2); 25 | } else if (root.info < n1 && root.info < n2) { 26 | return returnLCA(root.right, n1, n2); 27 | } else { 28 | return -1; 29 | } 30 | 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /src/trees/tree/BTCLList.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | /** 4 | * Created by poorvank.b on 20/04/18. 5 | */ 6 | public class BTCLList { 7 | } 8 | -------------------------------------------------------------------------------- /src/trees/tree/BinaryTreeToBST.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | 4 | import java.util.Arrays; 5 | 6 | public class BinaryTreeToBST { 7 | 8 | private static int[] inOrder = new int[5]; 9 | private static int index = 0; 10 | 11 | public static void main(String[] args) { 12 | 13 | Node root = new Node(10); 14 | root.left = new Node(2); 15 | root.right = new Node(7); 16 | root.left.left = new Node(8); 17 | root.left.right = new Node(4); 18 | saveInOrder(root); 19 | 20 | Arrays.sort(inOrder); 21 | index = 0; 22 | 23 | System.out.println("In Order before "); 24 | Traversal.in_Order(root); 25 | System.out.println("\nIn Order after "); 26 | arrayToBST(root); 27 | Traversal.in_Order(root); 28 | 29 | 30 | } 31 | 32 | private static void saveInOrder(Node root) { 33 | 34 | if (root == null) { 35 | return; 36 | } 37 | 38 | saveInOrder(root.left); 39 | 40 | inOrder[index] = root.info; 41 | index++; 42 | 43 | saveInOrder(root.right); 44 | } 45 | 46 | private static void arrayToBST(Node root) { 47 | 48 | if (root == null) { 49 | return; 50 | } 51 | 52 | arrayToBST(root.left); 53 | 54 | root.info = inOrder[index]; 55 | index++; 56 | 57 | arrayToBST(root.right); 58 | 59 | } 60 | 61 | 62 | } -------------------------------------------------------------------------------- /src/trees/tree/CheapestBranch.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Return branch with minimum sum 4 | 5 | */ 6 | 7 | package trees.tree; 8 | 9 | /** 10 | * Created by poorvank on 6/25/15. 11 | */ 12 | public class CheapestBranch { 13 | 14 | public static void main(String[] args) { 15 | 16 | Node root = new Node(8); 17 | root.left = new Node(4); 18 | root.left.left = new Node(3); 19 | root.left.right = new Node(1); 20 | root.right = new Node(5); 21 | root.right.right = new Node(11); 22 | 23 | System.out.println(sumBranch(root)); 24 | 25 | } 26 | 27 | private static int sumBranch(Node root) { 28 | 29 | if (root == null) { 30 | return Integer.MAX_VALUE; 31 | } 32 | 33 | if (root.left == null && root.right == null) { 34 | return root.info; 35 | } 36 | 37 | int r = sumBranch(root.right); 38 | int l = sumBranch(root.left); 39 | 40 | return root.info + Math.min(l, r); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/trees/tree/CheckBST.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class CheckBST { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | if (isBST(root, Integer.MAX_VALUE, Integer.MIN_VALUE)) { 9 | System.out.println("Its a BST"); 10 | } else { 11 | System.out.println("Nope"); 12 | } 13 | 14 | } 15 | 16 | 17 | /* 18 | traverses down the tree keeping track of the narrowing min and max allowed values as it goes, 19 | looking at each node only once. 20 | */ 21 | 22 | private static boolean isBST(Node root, int max, int min) { 23 | 24 | if (root == null) { 25 | return true; 26 | } else if (root.info < min || root.info > max) { 27 | return false; 28 | } 29 | 30 | return (isBST(root.left, root.info - 1, min) && isBST(root.right, max, root.info + 1)); 31 | 32 | 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/trees/tree/CheckBalancedBT.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | 4 | public class CheckBalancedBT { 5 | 6 | public static void main(String[] args) { 7 | 8 | Node root = Input.treeInput(); 9 | Height h = new Height(0); 10 | if (check(root, new Height(0))) { 11 | System.out.println("balanced"); 12 | } else { 13 | System.out.println("Nope"); 14 | } 15 | 16 | } 17 | 18 | private static boolean check(Node root, Height h) { 19 | 20 | 21 | if (root == null) { 22 | h.value = 0; 23 | return true; 24 | } 25 | 26 | Height lHeight = new Height(0); 27 | Height rHeight = new Height(0); 28 | 29 | boolean l = check(root.left, lHeight); 30 | boolean r = check(root.right, rHeight); 31 | 32 | h.value = (lHeight.value > rHeight.value ? lHeight.value : rHeight.value) + 1; 33 | 34 | if ((lHeight.value - rHeight.value >= 2) || (rHeight.value - lHeight.value >= 2)) { 35 | return false; 36 | } 37 | 38 | return (l && r); 39 | 40 | } 41 | 42 | } 43 | 44 | /* 45 | 46 | calculating the height in the same recursion rather than calling a height() function separately. O(n) 47 | 48 | */ -------------------------------------------------------------------------------- /src/trees/tree/CheckLeavesLevel.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Check if all leaves are at same level 4 | 5 | */ 6 | 7 | package trees.tree; 8 | 9 | /** 10 | * Created by poorvank on 6/9/15. 11 | */ 12 | public class CheckLeavesLevel { 13 | 14 | private static int leafLevel = 0; 15 | 16 | public static void main(String[] args) { 17 | 18 | Node root = new Node(12); 19 | root.left = new Node(5); 20 | root.left.left = new Node(3); 21 | root.right = new Node(45); 22 | root.right.right = new Node(46); 23 | 24 | System.out.println(checkSameLevel(root, 0)); 25 | 26 | } 27 | 28 | 29 | private static boolean checkSameLevel(Node root, int level) { 30 | 31 | if (root == null) { 32 | return true; 33 | } 34 | 35 | if (root.left == null && root.right == null) { 36 | 37 | if (leafLevel == 0) { 38 | leafLevel = level; 39 | return true; 40 | } 41 | 42 | return (level == leafLevel); 43 | 44 | } 45 | 46 | return checkSameLevel(root.left, level + 1) && checkSameLevel(root.right, level + 1); 47 | 48 | } 49 | 50 | } 51 | 52 | 53 | /* 54 | 55 | The idea is to first find level of the leftmost leaf and store it in a variable leafLevel. 56 | Then compare level of all other leaves with leafLevel, 57 | if same, return true, else return false. We traverse the given Binary Tree in Preorder fashion. 58 | An argument leaflevel is passed to all calls. The value of leafLevel is initialized as 0 to 59 | indicate that the first leaf is not yet seen yet. The value is updated when we find first leaf. 60 | Level of subsequent leaves (in preorder) is compared with leafLevel. 61 | 62 | */ -------------------------------------------------------------------------------- /src/trees/tree/ChildrenSumProperty.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class ChildrenSumProperty { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | if (fulfillsSumProperty(root)) { 9 | System.out.print("children Sum Property exists"); 10 | } else { 11 | System.out.println("Nope"); 12 | } 13 | 14 | } 15 | 16 | private static boolean fulfillsSumProperty(Node root) { 17 | 18 | if (root == null || (root.left == null && root.right == null)) { 19 | return true; 20 | } 21 | 22 | int leftValue = 0, rightValue = 0; 23 | 24 | if (root.left != null) { 25 | leftValue = root.left.info; 26 | } 27 | if (root.right != null) { 28 | rightValue = root.right.info; 29 | } 30 | 31 | return ((root.info == leftValue + rightValue) && fulfillsSumProperty(root.left) && fulfillsSumProperty(root.right)); 32 | 33 | } 34 | 35 | } 36 | 37 | /* 38 | 39 | O(n), we are doing a complete traversal of the tree. 40 | 41 | */ -------------------------------------------------------------------------------- /src/trees/tree/Collision.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * Created by poorvank on 6/23/15. 7 | */ 8 | 9 | 10 | public class Collision { 11 | 12 | public static void main(String[] args) { 13 | 14 | Node root = new Node(12); 15 | root.left = new Node(5); 16 | root.left.right = new Node(3); 17 | root.right = new Node(45); 18 | root.right.left = new Node(46); 19 | 20 | HashMap map = new HashMap<>(); 21 | count(root, 0, 0, map); 22 | 23 | } 24 | 25 | private static void count(Node root, int level, int hd, HashMap map) { 26 | 27 | if (root == null) { 28 | return; 29 | } 30 | 31 | count(root.left, level + 1, hd - 1, map); 32 | count(root.right, level + 1, hd + 1, map); 33 | 34 | String str = level + "," + hd; 35 | if (map.containsKey(str)) { 36 | System.out.print("Collision for - " + map.get(str) + " && " + root.info); 37 | } else { 38 | map.put(str, root.info); 39 | } 40 | 41 | return; 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/trees/tree/ConvertToSumTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 4 | Convert a given tree to its Sum Tree 5 | Given a Binary Tree where each node has positive and negative values. Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0. 6 | 7 | For example, the following tree 8 | 9 | 10 10 | / \ 11 | -2 6 12 | / \ / \ 13 | 8 -4 7 5 14 | should be changed to 15 | 16 | 20(4-2+12+6) 17 | / \ 18 | 4(8-4) 12(7+5) 19 | / \ / \ 20 | 0 0 0 0 21 | 22 | 23 | */ 24 | 25 | package trees.tree; 26 | 27 | public class ConvertToSumTree { 28 | 29 | public static void main(String[] args) { 30 | 31 | Node root = Input.treeInput(); 32 | Traversal.pre_Order(root); 33 | convert(root); 34 | System.out.println(); 35 | Traversal.pre_Order(root); 36 | 37 | } 38 | 39 | private static int convert(Node root) { 40 | 41 | if (root == null) { 42 | return 0; 43 | } 44 | 45 | int old_val = root.info; 46 | 47 | root.info = convert(root.left) + convert(root.right); 48 | 49 | return old_val + root.info; 50 | 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /src/trees/tree/CountLeaves.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class CountLeaves { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | System.out.println("Number of leaves in tree are - " + count(root)); 9 | 10 | } 11 | 12 | private static int count(Node root) { 13 | 14 | if (root == null) { 15 | return 0; 16 | } 17 | 18 | if (root.left == null && root.right == null) { 19 | return 1; 20 | } 21 | 22 | return count(root.left) + count(root.right); 23 | 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/trees/tree/DeepestLeftLeaf.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | /** 4 | * Created by poorvank on 3/23/15. 5 | */ 6 | public class DeepestLeftLeaf { 7 | 8 | private static int max = 0; 9 | private static Node leftNode = null; 10 | 11 | public static void main(String[] args) { 12 | 13 | Node root = Input.treeInput(); 14 | deepestLeft(root, 0, true); 15 | System.out.println("Deepest left leaf node is - " + leftNode.info); 16 | 17 | 18 | } 19 | 20 | private static void deepestLeft(Node root, int level, boolean isLeft) { 21 | 22 | if (root == null) { 23 | return; 24 | } 25 | 26 | if (isLeft && root.left == null && root.right == null) { 27 | if (level > max) { 28 | max = level; 29 | leftNode = root; 30 | } 31 | } 32 | 33 | deepestLeft(root.left, level + 1, true); 34 | deepestLeft(root.right, level + 1, false); 35 | 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/trees/tree/DeepestOddLeaf.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Find depth of the deepest odd level leaf node 4 | 5 | */ 6 | 7 | package trees.tree; 8 | 9 | /** 10 | * Created by poorvank on 6/11/15. 11 | */ 12 | public class DeepestOddLeaf { 13 | 14 | public static void main(String[] args) { 15 | 16 | Node root = new Node(12); 17 | root.left = new Node(5); 18 | root.left.left = new Node(3); 19 | root.right = new Node(45); 20 | root.right.right = new Node(46); 21 | 22 | System.out.println(deepestLevel(root, 1)); 23 | 24 | } 25 | 26 | private static int deepestLevel(Node root, int level) { 27 | 28 | if (root == null) { 29 | return 0; 30 | } 31 | 32 | if ((root.right == null && root.left == null) && level % 2 != 0) { 33 | return level; 34 | } 35 | 36 | return Math.max(deepestLevel(root.left, level + 1), deepestLevel(root.right, level + 1)); 37 | 38 | } 39 | 40 | } 41 | 42 | 43 | /* 44 | 45 | 46 | The idea is to recursively traverse the given binary tree and while traversing, 47 | maintain a variable “level” which will store the current node’s level in the tree. 48 | If current node is leaf then check “level” is odd or not. If level is odd then return it. 49 | If current node is not leaf, then recursively find maximum depth in left and right subtrees, 50 | and return maximum of the two depths. 51 | 52 | */ -------------------------------------------------------------------------------- /src/trees/tree/FullBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Check whether a binary tree is a full binary tree or not 4 | A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. 5 | Conversely, there is no node in a full binary tree, which has one child node. 6 | 7 | */ 8 | 9 | package trees.tree; 10 | 11 | /** 12 | * Created by poorvank on 6/22/15. 13 | */ 14 | public class FullBinaryTree { 15 | 16 | public static void main(String[] args) { 17 | 18 | Node root = new Node(12); 19 | root.left = new Node(5); 20 | root.left.left = new Node(3); 21 | root.right = new Node(45); 22 | root.right.right = new Node(46); 23 | 24 | System.out.print(checkFullBT(root)); 25 | 26 | } 27 | 28 | private static boolean checkFullBT(Node root) { 29 | 30 | if (root == null) { 31 | return true; 32 | } 33 | 34 | if (root.left == null && root.right == null) { 35 | return true; 36 | } 37 | 38 | return ((root.left != null && root.right != null) && (checkFullBT(root.left) && checkFullBT(root.right))); 39 | 40 | } 41 | 42 | } 43 | 44 | 45 | /* 46 | 47 | To check whether a binary tree is a full binary tree we need to test the following cases:- 48 | 49 | 1) If a binary tree node is NULL then it is a full binary tree. 50 | 2) If a binary tree node does have empty left and right sub-trees, then it is a full binary tree by definition 51 | 3) If a binary tree node has left and right sub-trees, then it is a part of a full binary tree by definition. 52 | In this case recursively check if the left and right sub-trees are also binary trees themselves. 53 | 4) In all other combinations of right and left sub-trees, the binary tree is not a full binary tree. 54 | 55 | */ -------------------------------------------------------------------------------- /src/trees/tree/GetLevel.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class GetLevel { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | int level = returnLevel(root, 11, 1); 9 | if (level != -1) { 10 | System.out.println("Level is - " + level); 11 | } else { 12 | System.out.println("Nope, not present"); 13 | } 14 | 15 | } 16 | 17 | private static int returnLevel(Node root, int target, int level) { 18 | 19 | if (root == null) { 20 | return -1; 21 | } 22 | if (root.info == target) { 23 | return level; 24 | } 25 | 26 | int downLevel = returnLevel(root.left, target, level + 1); 27 | if (downLevel != -1) { 28 | return downLevel; 29 | } 30 | 31 | downLevel = returnLevel(root.right, target, level + 1); 32 | if (downLevel != -1) { 33 | return downLevel; 34 | } 35 | 36 | return -1; 37 | 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /src/trees/tree/IdenticalTrees.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class IdenticalTrees { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root1 = Input.treeInput(); 8 | Node root2 = Input.treeInput(); 9 | if (isIdentical(root1, root2)) { 10 | System.out.println("Identical"); 11 | } else { 12 | System.out.println("Nope"); 13 | } 14 | 15 | } 16 | 17 | public static boolean isIdentical(Node root1, Node root2) { 18 | 19 | if (root1 == null && root2 == null) { 20 | return true; 21 | } 22 | if (root1 != null && root2 != null) { 23 | return (root1.info == root2.info && isIdentical(root1.left, root2.left) && isIdentical(root1.right, root2.right)); 24 | } else { 25 | return false; 26 | } 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/trees/tree/Isomorphic.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Two trees are called isomorphic if one of them can be obtained from other by a series of flips, 4 | i.e. by swapping left and right children of a number of nodes. 5 | Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic. 6 | 7 | */ 8 | 9 | package trees.tree; 10 | 11 | public class Isomorphic { 12 | 13 | public static void main(String[] args) { 14 | 15 | Node root1 = Input.treeInput(); 16 | Node root2 = Input.treeInput(); 17 | System.out.println(isIsomorphic(root1, root2)); 18 | 19 | 20 | } 21 | 22 | private static boolean isIsomorphic(Node root1, Node root2) { 23 | 24 | if (root1 == null && root2 == null) { 25 | return true; 26 | } 27 | 28 | if (root1 == null || root2 == null) { 29 | return false; 30 | } 31 | 32 | if (root1.info != root2.info) { 33 | return false; 34 | } 35 | 36 | return ((isIsomorphic(root1.left, root2.left) && isIsomorphic(root1.right, root2.right)) || 37 | (isIsomorphic(root1.left, root2.right) && isIsomorphic(root1.right, root2.left))); 38 | 39 | } 40 | 41 | } 42 | 43 | /* 44 | 45 | We simultaneously traverse both trees. Let the current internal nodes of two trees being traversed be n1 and n2 respectively. There are following two conditions for subtrees rooted with n1 and n2 to be isomorphic. 46 | 1) Data of n1 and n2 is same. 47 | 2) One of the following two is true for children of n1 and n2 48 | ……a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to right child of n2. 49 | ……b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic to left child of n2. 50 | 51 | */ -------------------------------------------------------------------------------- /src/trees/tree/KDistanceNodes.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class KDistanceNodes { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | printNodes(root, 2); 9 | 10 | } 11 | 12 | private static void printNodes(Node root, int k) { 13 | 14 | if (root == null) { 15 | return; 16 | } 17 | if (k == 0) { 18 | System.out.print(root.info + " "); 19 | return; 20 | } 21 | printNodes(root.left, k - 1); 22 | printNodes(root.right, k - 1); 23 | 24 | } 25 | 26 | 27 | } -------------------------------------------------------------------------------- /src/trees/tree/LeftView.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class LeftView { 4 | 5 | private static int max = 0; 6 | 7 | public static void main(String[] args) { 8 | 9 | Node root = Input.treeInput(); 10 | printLV(root, 1); 11 | 12 | } 13 | 14 | private static void printLV(Node root, int level) { 15 | 16 | if (root == null) { 17 | return; 18 | } 19 | 20 | if (level > max) { 21 | System.out.print(root.info + " "); 22 | max = level; 23 | } 24 | 25 | //Just changing the order of below statements changes left to right view 26 | 27 | printLV(root.left, level + 1); 28 | printLV(root.right, level + 1); 29 | 30 | } 31 | 32 | 33 | } 34 | 35 | /* 36 | 37 | The problem can also be solved using simple recursive traversal. 38 | We can keep track of level of a node by passing a parameter to all recursive calls. 39 | The idea is to keep track of maximum level also. Whenever we see a node whose level 40 | is more than maximum level so far, we print the node because this is the first node in its level 41 | 42 | */ -------------------------------------------------------------------------------- /src/trees/tree/LevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class LevelOrderTraversal { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | int height = treeHeight(root); 9 | System.out.println("height of tree - " + height); 10 | for (int d = 1; d <= height; d++) { 11 | traversal(root, d); 12 | System.out.println(); 13 | } 14 | 15 | } 16 | 17 | private static void traversal(Node root, int level) { 18 | 19 | if (root != null) { 20 | if (level == 1) { 21 | System.out.print(root.info + " "); 22 | } else { 23 | traversal(root.left, level - 1); 24 | traversal(root.right, level - 1); 25 | } 26 | } 27 | 28 | } 29 | 30 | private static int treeHeight(Node root) { 31 | 32 | if (root == null) { 33 | return 0; 34 | } 35 | if (root.left == null && root.right == null) { 36 | return 1; 37 | } else { 38 | return maxTwoNo(treeHeight(root.left), treeHeight(root.right)) + 1; 39 | } 40 | 41 | } 42 | 43 | private static int maxTwoNo(int a, int b) { 44 | 45 | return a > b ? a : b; 46 | 47 | } 48 | 49 | } 50 | 51 | /* 52 | 53 | Time Complexity: O(n^2) in worst case. 54 | For a skewed tree, printGivenLevel() takes O(n) time where n is the number of nodes 55 | in the skewed tree. So time complexity of printLevelOrder() is O(n) + O(n-1) + O(n-2) + .. + O(1) which is O(n^2). 56 | 57 | */ -------------------------------------------------------------------------------- /src/trees/tree/LowestCommonAncestor1.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | /** 4 | * Created by poorvank on 3/25/15. 5 | */ 6 | public class LowestCommonAncestor1 { 7 | 8 | public static void main(String[] args) { 9 | 10 | Node root = Input.treeInput(); 11 | System.out.println("lca of 6 and 11 is - " + LCA1(root, 6, 11).info); 12 | 13 | } 14 | 15 | private static Node LCA1(Node root, int k1, int k2) { 16 | 17 | if (root == null) { 18 | return null; 19 | } 20 | 21 | if (root.info == k1 || root.info == k2) { 22 | return root; 23 | } 24 | 25 | root.left = LCA1(root.left, k1, k2); 26 | root.right = LCA1(root.right, k1, k2); 27 | 28 | if (root.right != null && root.left != null) { 29 | return root; 30 | } 31 | 32 | return root.left != null ? root.left : root.right; 33 | 34 | } 35 | 36 | 37 | } 38 | 39 | 40 | /* 41 | 42 | If we assume that the keys n1 and n2 are present in Binary Tree, we can find LCA using single traversal 43 | of Binary Tree and without extra storage for path arrays. 44 | The idea is to traverse the tree starting from root. If any of the given keys (n1 and n2) matches with 45 | root, then root is LCA (assuming that both keys are present). If root doesn’t match with any of the keys, 46 | we recur for left and right subtree. The node which has one key present in its left subtree and the 47 | other key present in right subtree is the LCA. If both keys lie in left subtree, then left subtree has LCA also, 48 | otherwise LCA lies in right subtree. 49 | 50 | */ -------------------------------------------------------------------------------- /src/trees/tree/MaxSumPath.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class MaxSumPath { 4 | 5 | private static Node maxLeaf = null; 6 | private static int cSum = Integer.MIN_VALUE; 7 | 8 | public static void main(String[] args) { 9 | 10 | Node root = Input.treeInput(); 11 | printPath(root, leaf(root, 0)); 12 | 13 | } 14 | 15 | private static Node leaf(Node root, int rSum) { 16 | 17 | if (root == null) { 18 | return root; 19 | } 20 | 21 | int current_sum = rSum + root.info; 22 | 23 | if (root.right == null && root.left == null) { 24 | 25 | if (current_sum > cSum) { 26 | cSum = current_sum; 27 | maxLeaf = root; 28 | } 29 | 30 | 31 | } 32 | 33 | leaf(root.left, current_sum); 34 | leaf(root.right, current_sum); 35 | 36 | return maxLeaf; 37 | 38 | } 39 | 40 | private static void printPath(Node root, Node leaf) { 41 | 42 | if (root == leaf) { 43 | System.out.print(root.info + " "); 44 | } else if (root.info < leaf.info) { 45 | System.out.print(root.info + " "); 46 | printPath(root.right, leaf); 47 | } else if (root.info > leaf.info) { 48 | System.out.print(root.info + " "); 49 | printPath(root.left, leaf); 50 | } 51 | 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /src/trees/tree/MaximumLeavesSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Find the maximum path sum between two leaves of a binary tree 4 | Given a binary tree in which each node element contains a number. 5 | Find the maximum possible sum from one leaf node to another. 6 | 7 | */ 8 | 9 | package trees.tree; 10 | 11 | /** 12 | * Created by poorvank on 6/12/15. 13 | */ 14 | public class MaximumLeavesSum { 15 | 16 | private static int result = 0; 17 | 18 | public static void main(String[] args) { 19 | 20 | Node root = new Node(12); 21 | root.left = new Node(5); 22 | root.left.left = new Node(3); 23 | root.right = new Node(45); 24 | root.right.right = new Node(46); 25 | 26 | maxSum(root); 27 | 28 | System.out.println(result); 29 | 30 | } 31 | 32 | private static int maxSum(Node root) { 33 | 34 | if (root == null) { 35 | return 0; 36 | } 37 | 38 | int left = maxSum(root.left); 39 | int right = maxSum(root.right); 40 | 41 | int currentSum = left + right + root.info; 42 | 43 | if (result < currentSum) { 44 | result = currentSum; 45 | } 46 | 47 | return Math.max(left, right) + root.info; 48 | 49 | } 50 | 51 | } 52 | 53 | 54 | /* 55 | 56 | We can find the maximum sum using single traversal of binary tree. 57 | The idea is to maintain two values in recursive calls 58 | 1) Maximum root to leaf path sum for the subtree rooted under current node. 59 | 2) The maximum path sum between leaves (desired output). 60 | 61 | For every visited node X, we find the maximum root to leaf sum in left and right 62 | subtrees of X. We add the two values with X->data, and compare the sum with maximum path sum found so far. 63 | 64 | */ -------------------------------------------------------------------------------- /src/trees/tree/MinimumElementAtADepth.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree. Find the minimum element at a given depth 3 | */ 4 | 5 | package trees.tree; 6 | 7 | /** 8 | * Created by poorvank on 8/4/15. 9 | */ 10 | public class MinimumElementAtADepth { 11 | 12 | public static void main(String[] args) { 13 | 14 | Node root = new Node(12); 15 | root.left = new Node(5); 16 | root.left.left = new Node(3); 17 | root.left.right = new Node(10); 18 | root.right = new Node(45); 19 | root.right.right = new Node(46); 20 | root.right.left = new Node(34); 21 | 22 | System.out.println(minimum(root, 1)); 23 | 24 | } 25 | 26 | private static int minimum(Node node, int depth) { 27 | 28 | if (node == null) { 29 | return Integer.MAX_VALUE; 30 | } 31 | 32 | if (depth == 0) { 33 | return node.info; 34 | } 35 | 36 | int left = minimum(node.left, depth - 1); 37 | int right = minimum(node.right, depth - 1); 38 | 39 | return Math.min(left, right); 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/trees/tree/MirrorTree.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class MirrorTree { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | System.out.println("Inorder traversal before "); 9 | Traversal.in_Order(root); 10 | System.out.println("\nInorder traversal after "); 11 | root = mirror(root); 12 | Traversal.in_Order(root); 13 | 14 | } 15 | 16 | private static Node mirror(Node root) { 17 | 18 | if (root != null) { 19 | 20 | root.left = mirror(root.left); 21 | root.right = mirror(root.right); 22 | 23 | Node tmp = root.left; 24 | root.left = root.right; 25 | root.right = tmp; 26 | return root; 27 | } 28 | return null; 29 | 30 | } 31 | 32 | } 33 | 34 | //Inorder traversal of mirror tree would be reverse -------------------------------------------------------------------------------- /src/trees/tree/NextRightNode.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | /** 7 | * Created by poorvank on 3/23/15. 8 | */ 9 | public class NextRightNode { 10 | 11 | public static void main(String[] args) { 12 | 13 | Node root = Input.treeInput(); 14 | if (nextRight(root, 25) != null) { 15 | System.out.println("Next root is - " + nextRight(root, 25).info); 16 | } else { 17 | System.out.println("null"); 18 | } 19 | 20 | } 21 | 22 | private static Node nextRight(Node root, int key) { 23 | 24 | Queue nodeQueue = new LinkedList(); 25 | Queue levelQueue = new LinkedList(); 26 | 27 | nodeQueue.add(root); 28 | levelQueue.add(0); 29 | 30 | while (nodeQueue.size() != 0) { 31 | 32 | 33 | Node current = nodeQueue.remove(); 34 | int level = levelQueue.remove(); 35 | 36 | 37 | if (current.info == key) { 38 | 39 | if (nodeQueue.size() == 0 || levelQueue.peek() != level) { 40 | return null; 41 | } else { 42 | return nodeQueue.peek(); 43 | } 44 | 45 | } 46 | if (current.left != null) { 47 | nodeQueue.add(current.left); 48 | levelQueue.add(level + 1); 49 | } 50 | if (current.right != null) { 51 | nodeQueue.add(current.right); 52 | levelQueue.add(level + 1); 53 | } 54 | 55 | //break; 56 | } 57 | 58 | return null; 59 | 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/trees/tree/NoSibling.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a Binary Tree, print all nodes that don’t have a sibling (a sibling is a node that has same parent. 4 | In a Binary Tree, there can be at most one sibling). Root should not be printed as root cannot have a sibling. 5 | 6 | */ 7 | 8 | package trees.tree; 9 | 10 | /** 11 | * Created by poorvank on 6/16/15. 12 | */ 13 | public class NoSibling { 14 | 15 | public static void main(String[] args) { 16 | 17 | Node root = new Node(1); 18 | root.left = new Node(5); 19 | root.left.left = new Node(3); 20 | root.right = new Node(4); 21 | root.right.right = new Node(6); 22 | 23 | 24 | printNodes(root); 25 | 26 | } 27 | 28 | private static void printNodes(Node root) { 29 | 30 | if (root == null) { 31 | return; 32 | } 33 | 34 | if (root.left != null && root.right != null) { 35 | printNodes(root.right); 36 | printNodes(root.left); 37 | } else if (root.right != null) { 38 | System.out.println(root.right.info); 39 | printNodes(root.right); 40 | } else if (root.left != null) { 41 | System.out.println(root.left.info); 42 | printNodes(root.left); 43 | } 44 | 45 | } 46 | 47 | } 48 | 49 | 50 | /* 51 | 52 | This is a typical tree traversal question. We start from root and check if 53 | the node has one child, if yes then print the only child of that node. 54 | If node has both children, then recur for both the children. 55 | 56 | */ -------------------------------------------------------------------------------- /src/trees/tree/Node.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | /** 4 | * Created by poorvank on 7/12/15. 5 | */ 6 | public class Node { 7 | 8 | public int info; 9 | public Node left; 10 | public Node right; 11 | 12 | public Node(int info) { 13 | this(info, null, null); 14 | } 15 | 16 | public Node(int info, Node left, Node right) { 17 | this.info = info; 18 | this.left = left; 19 | this.right = right; 20 | } 21 | 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/trees/tree/OnlyLeftLeaves.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Number of Nodes in binary tree having only left child 4 | 5 | */ 6 | 7 | package trees.tree; 8 | 9 | /** 10 | * Created by poorvank on 12/27/15. 11 | */ 12 | public class OnlyLeftLeaves { 13 | 14 | public static void main(String[] args) { 15 | 16 | Node root = new Node(10); 17 | root.left = new Node(8); 18 | root.left.left = new Node(3); 19 | //root.left.right = new Node(5); 20 | root.right = new Node(2); 21 | root.right.left = new Node(2); 22 | 23 | System.out.println(leftCount(root)); 24 | 25 | } 26 | 27 | private static int leftCount(Node root) { 28 | 29 | if (root == null || (root.left == null && root.right == null)) { 30 | return 0; 31 | } else if (root.left != null && root.right == null) { 32 | return 1 + leftCount(root.left); 33 | } else { 34 | return leftCount(root.left) + leftCount(root.right); 35 | } 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/trees/tree/PathSum.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | public class PathSum { 7 | 8 | public static void main(String[] args) { 9 | 10 | Node root = Input.treeInput(); 11 | Scanner sc = new Scanner(System.in); 12 | System.out.println("Enter the number to check - "); 13 | int a = sc.nextInt(); 14 | sum(root, new ArrayList(), a, 0); 15 | 16 | 17 | } 18 | 19 | private static void sum(Node root, ArrayList list, int check, int currentSum) { 20 | 21 | 22 | if (root == null) { 23 | return; 24 | } 25 | 26 | currentSum += root.info; 27 | 28 | list.add(root.info); 29 | 30 | 31 | if (root.left == null && root.right == null) { 32 | if (currentSum == check) { 33 | System.out.println("Sum found - " + list.toString()); 34 | } 35 | return; 36 | } 37 | 38 | 39 | if (root.left != null) { 40 | sum(root.left, new ArrayList(list), check, currentSum); 41 | } 42 | if (root.right != null) { 43 | sum(root.right, new ArrayList(list), check, currentSum); 44 | } 45 | 46 | 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /src/trees/tree/PreOrderSuccessor.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | /** 4 | * Created by poorvank on 8/18/15. 5 | */ 6 | public class PreOrderSuccessor { 7 | 8 | private static boolean find = false; 9 | 10 | public static void main(String[] args) { 11 | 12 | Node root = new Node(12); 13 | root.left = new Node(5); 14 | root.left.left = new Node(3); 15 | root.right = new Node(45); 16 | root.right.right = new Node(46); 17 | 18 | Node x; 19 | if ((x = findSuccessorPreOrder(3, root)) != null) { 20 | System.out.println(x.info); 21 | } 22 | 23 | } 24 | 25 | private static Node findSuccessorPreOrder(int key, Node root) { 26 | 27 | if (root == null) { 28 | return null; 29 | } 30 | 31 | if (root.info == key) { 32 | 33 | find = true; 34 | 35 | if (root.left != null) { 36 | return root.left; 37 | } else if (root.right != null) { 38 | return root.right; 39 | } 40 | return null; 41 | 42 | } else { 43 | 44 | Node successor; 45 | 46 | successor = findSuccessorPreOrder(key, root.left); 47 | 48 | if (successor != null) { 49 | return successor; 50 | } 51 | 52 | if (find) { 53 | return root.right; 54 | } else if (!find) { 55 | return findSuccessorPreOrder(key, root.right); 56 | } else { 57 | return null; 58 | } 59 | 60 | 61 | } 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/trees/tree/PreorderBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given preorder traversal of a binary search tree, construct the BST. 4 | 5 | */ 6 | 7 | package trees.tree; 8 | 9 | public class PreorderBST { 10 | 11 | private static int min = Integer.MIN_VALUE; 12 | private static int max = Integer.MAX_VALUE; 13 | private static int index = 0; 14 | 15 | public static void main(String[] args) { 16 | 17 | int[] preOrder = new int[]{10, 5, 1, 7, 40, 50}; 18 | Traversal.in_Order(constructTree(preOrder, preOrder.length, preOrder[0], min, max)); 19 | 20 | 21 | } 22 | 23 | private static Node constructTree(int[] preOrder, int size, int key, int min, int max) { 24 | 25 | if (index >= size) { 26 | return null; 27 | } 28 | 29 | Node root = null; 30 | 31 | if (key > min && key < max) { 32 | 33 | root = new Node(key); 34 | index++; 35 | 36 | if (index < size) { 37 | root.left = constructTree(preOrder, size, preOrder[index], min, root.info); 38 | root.right = constructTree(preOrder, size, preOrder[index], root.info, max); 39 | } 40 | 41 | } 42 | 43 | 44 | return root; 45 | 46 | } 47 | 48 | } 49 | 50 | /* 51 | 52 | The trick is to set a range {min .. max} for every node. 53 | Initialize the range as {INT_MIN .. INT_MAX}. 54 | The first node will definitely be in range, so create root node. 55 | To construct the left subtree, set the range as {INT_MIN …root->data}. 56 | If a values is in the range {INT_MIN .. root->data}, the values is part part of left subtree. 57 | To construct the right subtree, set the range as {root->data..max .. INT_MAX}. 58 | 59 | */ -------------------------------------------------------------------------------- /src/trees/tree/PreorderSpecialTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given an array ‘pre[]’ that represents Preorder traversal of a spacial binary tree where every node has either 0 or 2 children. 4 | One more array ‘preLN[]’ is given which has only two possible values ‘L’ and ‘N’. 5 | The value ‘L’ in ‘preLN[]’ indicates that the corresponding node in Binary Tree is a 6 | leaf node and value ‘N’ indicates that the corresponding node is non-leaf node. 7 | Write a function to construct the tree from the given two arrays. 8 | 9 | */ 10 | 11 | package trees.tree; 12 | 13 | public class PreorderSpecialTree { 14 | 15 | private static int index = 0; 16 | 17 | public static void main(String[] args) { 18 | 19 | int[] pre = new int[]{10, 30, 20, 5, 15}; 20 | char[] preLN = new char[]{'N', 'N', 'L', 'L', 'L'}; 21 | Node root = constructTree(new Node(0), pre, preLN); 22 | Traversal.in_Order(root); 23 | 24 | } 25 | 26 | private static Node constructTree(Node root, int[] pre, char[] preLN) { 27 | 28 | root = new Node(pre[index]); 29 | index++; 30 | 31 | 32 | if (preLN[index - 1] == 'N') { 33 | 34 | //System.out.println(root.info); 35 | root.left = constructTree(root.left, pre, preLN); 36 | root.right = constructTree(root.right, pre, preLN); 37 | 38 | } 39 | 40 | return root; 41 | 42 | 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/trees/tree/PrintAncestors.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Print Ancestors of a given node in Binary Tree 4 | Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree. 5 | 6 | For example, if the given tree is following Binary Tree and key is 7, then your function should print 4, 2 and 1. 7 | 8 | 9 | 1 10 | / \ 11 | 2 3 12 | / \ 13 | 4 5 14 | / 15 | 7 16 | 17 | */ 18 | 19 | package trees.tree; 20 | 21 | public class PrintAncestors { 22 | 23 | private static int immediateAncestor = -1; 24 | 25 | public static void main(String[] args) { 26 | 27 | Node root = Input.treeInput(); 28 | if (!ancestor(root, 9)) { 29 | System.out.println("No ancestor"); 30 | } 31 | 32 | 33 | System.out.println("\nimmediate ancestor - " + immediateAncestor); 34 | 35 | } 36 | 37 | private static boolean ancestor(Node root, int target) { 38 | 39 | if (root == null) { 40 | return false; 41 | } 42 | 43 | if (root.info == target) { 44 | return true; 45 | } 46 | 47 | if (ancestor(root.left, target) || ancestor(root.right, target)) { 48 | if (immediateAncestor == -1) { 49 | immediateAncestor = root.info; 50 | } 51 | System.out.print(root.info + " "); 52 | return true; 53 | } 54 | 55 | return false; 56 | 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /src/trees/tree/PrintRangeKeys.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class PrintRangeKeys { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | System.out.println("Range keys are - "); 9 | printKeys(10, 22, root); 10 | 11 | } 12 | 13 | private static void printKeys(int k1, int k2, Node root) { 14 | 15 | if (root == null) { 16 | return; 17 | } 18 | 19 | if (root.info > k1) { 20 | printKeys(k1, k2, root.left); 21 | } 22 | 23 | if (root.info >= k1 && root.info <= k2) { 24 | System.out.println(root.info); 25 | } 26 | 27 | if (root.info < k2) { 28 | printKeys(k1, k2, root.right); 29 | } 30 | 31 | } 32 | 33 | } 34 | 35 | 36 | /* 37 | 38 | Algo used : 39 | 40 | 1) If value of root’s key is greater than k1, then recursively call in left subtree. 41 | 2) If value of root’s key is in range, then print the root’s key. 42 | 3) If value of root’s key is smaller than k2, then recursively call in right subtree. 43 | 44 | */ -------------------------------------------------------------------------------- /src/trees/tree/QueueLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class QueueLevelOrderTraversal { 7 | 8 | public static void main(String[] args) { 9 | 10 | Node root = Input.treeInput(); 11 | Queue nodeQueue = new LinkedList(); 12 | levelTraversal(root, nodeQueue); 13 | 14 | 15 | } 16 | 17 | public static void levelTraversal(Node root, Queue nodeQueue) { 18 | 19 | Node tmp = root; 20 | 21 | while (tmp != null) { 22 | 23 | System.out.print(tmp.info + " "); 24 | 25 | if (tmp.left != null) { 26 | nodeQueue.add(tmp.left); 27 | } 28 | 29 | if (tmp.right != null) { 30 | nodeQueue.add(tmp.right); 31 | } 32 | 33 | tmp = nodeQueue.poll(); 34 | 35 | } 36 | 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /src/trees/tree/RemoveHalfNodes.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given A binary Tree, how do you remove all the half nodes (which has only one child)? 4 | Note leaves should not be touched as they have both children as NULL. 5 | 6 | */ 7 | 8 | package trees.tree; 9 | 10 | /** 11 | * Created by poorvank on 3/24/15. 12 | */ 13 | public class RemoveHalfNodes { 14 | 15 | public static void main(String[] args) { 16 | 17 | Node root = Input.treeInput(); 18 | Traversal.in_Order(root); 19 | System.out.println("\nAfter removal -"); 20 | Traversal.in_Order(fullTree(root)); 21 | 22 | } 23 | 24 | private static Node fullTree(Node root) { 25 | 26 | if (root == null) { 27 | return null; 28 | } 29 | 30 | root.left = fullTree(root.left); 31 | root.right = fullTree(root.right); 32 | 33 | if (root.left == null && root.right == null) { 34 | return root; 35 | } 36 | 37 | if (root.left == null) { 38 | 39 | Node current = root.right; 40 | root = null; 41 | return current; 42 | 43 | } 44 | 45 | if (root.right == null) { 46 | 47 | Node current = root.left; 48 | root = null; 49 | return current; 50 | 51 | } 52 | 53 | return root; 54 | 55 | } 56 | 57 | } 58 | 59 | /* 60 | 61 | The idea is to use post-order traversal to solve this problem efficiently. 62 | We first process the left children, then right children, and finally the node itself. 63 | So we form the new tree bottom up, starting from the leaves towards the root. 64 | By the time we process the current node, both its left and right subtrees were already processed. 65 | O(n) 66 | 67 | */ -------------------------------------------------------------------------------- /src/trees/tree/ReverseLevelOrder.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class ReverseLevelOrder { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | int height = TreeHeight.height(root); 9 | for (int i = height; i >= 1; i--) { 10 | reverse(root, i); 11 | } 12 | 13 | } 14 | 15 | private static void reverse(Node root, int level) { 16 | 17 | if (root == null) { 18 | return; 19 | } 20 | if (level == 1) { 21 | System.out.print(root.info + " "); 22 | } else if (level > 1) { 23 | 24 | reverse(root.left, level - 1); 25 | reverse(root.right, level - 1); 26 | 27 | } 28 | 29 | 30 | } 31 | 32 | } 33 | 34 | 35 | //Can also be done using a queue and a map 36 | 37 | -------------------------------------------------------------------------------- /src/trees/tree/ReverseLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | import utility.Stack; 6 | 7 | /** 8 | * Created by poorvank on 6/22/15. 9 | */ 10 | public class ReverseLevelOrderTraversal { 11 | 12 | public static void main(String[] args) { 13 | 14 | Node root = new Node(12); 15 | root.left = new Node(5); 16 | root.left.left = new Node(3); 17 | root.right = new Node(45); 18 | root.right.right = new Node(46); 19 | 20 | printReverseLevelOrder(root); 21 | 22 | 23 | } 24 | 25 | private static void printReverseLevelOrder(Node root) { 26 | 27 | Stack stack = new Stack<>(); 28 | Queue queue = new LinkedList<>(); 29 | 30 | queue.add(root); 31 | 32 | while (!queue.isEmpty()) { 33 | 34 | Node a = queue.remove(); 35 | stack.push(a); 36 | 37 | if (a.right != null) { 38 | queue.add(a.right); 39 | } 40 | 41 | if (a.left != null) { 42 | queue.add(a.left); 43 | } 44 | 45 | } 46 | 47 | while (!stack.isEmpty()) { 48 | System.out.print(stack.pop().info + " "); 49 | } 50 | 51 | } 52 | 53 | } 54 | 55 | 56 | /* 57 | 58 | The idea is to use a stack to get the reverse level order. 59 | If we do normal level order traversal and instead of printing a node, 60 | push the node to a stack and then print contents of stack, we get “5 4 3 2 1″ 61 | for above example tree, but output should be “4 5 2 3 1″. So to get the correct sequence 62 | (left to right at every level), we process children of a node in reverse order, we first push 63 | the right subtree to stack, then left subtree. 64 | 65 | */ -------------------------------------------------------------------------------- /src/trees/tree/RootToLeaf.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class RootToLeaf { 6 | 7 | private static int maxSum = Integer.MAX_VALUE; 8 | private static ArrayList finalList = new ArrayList<>(); 9 | 10 | public static void main(String[] args) { 11 | 12 | Node root = new Node(8); 13 | root.left = new Node(4); 14 | root.left.left = new Node(3); 15 | root.left.right = new Node(1); 16 | root.right = new Node(5); 17 | root.right.right = new Node(11); 18 | ArrayList list = new ArrayList(); 19 | path(root, list, 0); 20 | System.out.println("Final list is - " + finalList.toString() + " and minimum sum is " + maxSum); 21 | 22 | } 23 | 24 | private static void path(Node root, ArrayList list, int s) { 25 | 26 | if (root == null) { 27 | return; 28 | } else { 29 | list.add(root.info); 30 | s = s + root.info; 31 | } 32 | 33 | if ((root.left == null && root.right == null)) { 34 | System.out.println(list); 35 | if (maxSum > s) { 36 | maxSum = s; 37 | finalList = new ArrayList<>(list); 38 | } 39 | return; 40 | } 41 | 42 | path(root.left, new ArrayList(list), s); 43 | path(root.right, new ArrayList(list), s); 44 | 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /src/trees/tree/SortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Sorted Array to Balanced BST 4 | Given a sorted array. Write a function that creates a Balanced Binary Search Tree using array elements. 5 | 6 | Examples: 7 | 8 | Input: Array {1, 2, 3} 9 | Output: A Balanced BST 10 | 2 11 | / \ 12 | 1 3 13 | 14 | Input: Array {1, 2, 3, 4} 15 | Output: A Balanced BST 16 | 3 17 | / \ 18 | 2 4 19 | / 20 | 1 21 | 22 | */ 23 | 24 | package trees.tree; 25 | 26 | /** 27 | * Created by poorvank on 6/16/15. 28 | */ 29 | public class SortedArrayToBST { 30 | 31 | public static void main(String[] args) { 32 | 33 | int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7}; 34 | Traversal.in_Order(convert(arr, 0, arr.length - 1)); 35 | 36 | } 37 | 38 | private static Node convert(int[] arr, int start, int end) { 39 | 40 | if (start > end) { 41 | return null; 42 | } 43 | 44 | int mid = (start + end) / 2; 45 | 46 | Node root = new Node(arr[mid]); 47 | root.left = convert(arr, start, mid - 1); 48 | root.right = convert(arr, mid + 1, end); 49 | 50 | return root; 51 | 52 | } 53 | 54 | } 55 | 56 | 57 | /* 58 | 59 | Constructing from sorted array in O(n) time is simpler as we can get the middle element 60 | in O(1) time. Following is a simple algorithm where we 61 | first find the middle node of list and make it root of the tree to be constructed. 62 | 63 | 1) Get the Middle of the array and make it root. 64 | 2) Recursively do same for left half and right half. 65 | a) Get the middle of left half and make it left child of the root 66 | created in step 1. 67 | b) Get the middle of right half and make it right child of the 68 | root created in step 1. 69 | 70 | */ -------------------------------------------------------------------------------- /src/trees/tree/SpecialBT1.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given Inorder Traversal of a Special Binary Tree in which key of every node is greater than keys 4 | in left and right children, construct the Binary Tree and return root. 5 | 6 | */ 7 | 8 | package trees.tree; 9 | 10 | public class SpecialBT1 { 11 | 12 | public static void main(String[] args) { 13 | 14 | int[] inOrder = new int[]{5, 10, 40, 30, 28}; 15 | Traversal.pre_Order(constructTree(inOrder, 0, 4)); 16 | 17 | 18 | } 19 | 20 | private static Node constructTree(int[] inOrder, int start, int end) { 21 | 22 | if (start > end) { 23 | return null; 24 | } 25 | 26 | int index = maxIndex(inOrder, start, end); 27 | Node root = new Node(inOrder[index]); 28 | 29 | root.left = constructTree(inOrder, start, index - 1); 30 | root.right = constructTree(inOrder, index + 1, end); 31 | 32 | return root; 33 | 34 | 35 | } 36 | 37 | private static int maxIndex(int[] arr, int start, int end) { 38 | 39 | int max = Integer.MIN_VALUE; 40 | int index = start; 41 | 42 | for (int i = start; i <= end; i++) { 43 | if (arr[i] > max) { 44 | max = arr[i]; 45 | index = i; 46 | } 47 | } 48 | 49 | return index; 50 | 51 | } 52 | 53 | } 54 | 55 | 56 | /* 57 | 1) Find index of the maximum element in array. The maximum element must be root of Binary Tree. 58 | 2) Create a new tree node ‘root’ with the data as the maximum value found in step 1. 59 | 3) Call buildTree for elements before the maximum element and make the built tree as left subtree of ‘root’. 60 | 5) Call buildTree for elements after the maximum element and make the built tree as right subtree of ‘root’. 61 | 6) return ‘root’. 62 | */ -------------------------------------------------------------------------------- /src/trees/tree/SpecifiedSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Root to leaf path sum equal to a given number 4 | Given a binary tree and a number, return true if the tree has a root-to-leaf 5 | path such that adding up all the values along the path equals the given number. 6 | Return false if no such path can be found. 7 | 8 | */ 9 | 10 | package trees.tree; 11 | 12 | import java.util.Scanner; 13 | 14 | /** 15 | * Created by poorvank on 4/28/15. 16 | */ 17 | public class SpecifiedSum { 18 | 19 | public static void main(String[] args) { 20 | 21 | Node root = Input.treeInput(); 22 | Scanner sc = new Scanner(System.in); 23 | int sum = sc.nextInt(); 24 | 25 | System.out.println("Is sum = " + sum + " present " + checkSum(root, sum)); 26 | 27 | } 28 | 29 | private static boolean checkSum(Node root, int sum) { 30 | 31 | if (root == null) { 32 | return (sum == 0); 33 | } else { 34 | 35 | boolean flag = false; 36 | 37 | int subSum = sum - root.info; 38 | if (subSum == 0 && root.left == null && root.right == null) { 39 | return true; 40 | } 41 | 42 | if (root.left != null) { 43 | flag = flag || checkSum(root.left, subSum); 44 | } 45 | if (root.right != null) { 46 | flag = flag || checkSum(root.right, subSum); 47 | } 48 | 49 | return flag; 50 | 51 | } 52 | 53 | } 54 | 55 | } 56 | 57 | 58 | /* 59 | 60 | Algorithm: 61 | Recursively check if left or right child has path sum equal to ( number – value at current node) 62 | 63 | True || false == TRUE 64 | 65 | */ -------------------------------------------------------------------------------- /src/trees/tree/SumDifference.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Difference between sums of odd level and even level nodes of a Binary Tree 4 | 5 | */ 6 | 7 | package trees.tree; 8 | 9 | /** 10 | * Created by poorvank on 6/6/15. 11 | */ 12 | public class SumDifference { 13 | 14 | public static void main(String[] args) { 15 | 16 | Node root = Input.treeInput(); 17 | System.out.println(difference(root)); 18 | 19 | } 20 | 21 | public static int difference(Node root) { 22 | 23 | if (root == null) { 24 | return 0; 25 | } 26 | 27 | return root.info - (difference(root.left) + difference(root.right)); 28 | 29 | } 30 | 31 | } 32 | 33 | 34 | /* 35 | 36 | The problem can also be solved using simple recursive traversal. 37 | We can recursively calculate the required difference as, 38 | value of root’s data subtracted by the difference for subtree under left child and the 39 | difference for subtree under right child. 40 | 41 | */ -------------------------------------------------------------------------------- /src/trees/tree/SumOfLeftLeaves.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class SumOfLeftLeaves { 4 | 5 | private static int sum = 0; 6 | 7 | public static void main(String[] args) { 8 | 9 | Node root = Input.treeInput(); 10 | leftLeafSum(root); 11 | System.out.println("Left leaf sum - " + sum); 12 | 13 | } 14 | 15 | private static void leftLeafSum(Node root) { 16 | 17 | 18 | if (root != null) { 19 | 20 | if (isLeaf(root.left)) { 21 | sum += root.left.info; 22 | } else { 23 | leftLeafSum(root.left); 24 | } 25 | 26 | leftLeafSum(root.right); 27 | 28 | } 29 | 30 | } 31 | 32 | private static boolean isLeaf(Node root) { 33 | 34 | return root!=null && root.left==null && root.right==null; 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /src/trees/tree/TopView.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | 4 | import java.util.HashSet; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | public class TopView { 9 | 10 | public static void main(String[] args) { 11 | 12 | customNode2 root = customInput2.treeInput(); 13 | top(root); 14 | } 15 | 16 | private static void top(customNode2 root) { 17 | 18 | if (root == null) { 19 | return; 20 | } 21 | 22 | HashSet set = new HashSet(); 23 | 24 | Queue queue = new LinkedList(); 25 | 26 | queue.add(root); 27 | 28 | while (!queue.isEmpty()) { 29 | 30 | customNode2 current = queue.remove(); 31 | int hd = current.hd; 32 | 33 | if (!set.contains(hd)) { 34 | System.out.print(current.info + " "); 35 | set.add(hd); 36 | } 37 | 38 | if (current.left != null) { 39 | current.left.hd = hd + 1; 40 | queue.add(current.left); 41 | } 42 | if (current.right != null) { 43 | current.right.hd = hd - 1; 44 | queue.add(current.right); 45 | } 46 | 47 | } 48 | 49 | } 50 | 51 | } 52 | 53 | /* 54 | 55 | We do a level order traversal so that the topmost node at a horizontal node 56 | is visited before any other node of same horizontal distance below it. 57 | Hashing is used to check if a node at given horizontal distance is seen or not. 58 | 59 | */ -------------------------------------------------------------------------------- /src/trees/tree/TreeDiameter.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | 4 | class Height { 5 | 6 | public int value; 7 | 8 | public Height(int value) { 9 | this.value = value; 10 | } 11 | 12 | } 13 | 14 | public class TreeDiameter { 15 | 16 | public static void main(String[] args) { 17 | 18 | Node root = Input.treeInput(); 19 | System.out.print("diameter of tree is - " + diameter(root)); 20 | 21 | } 22 | 23 | private static int diameter(Node root) { 24 | 25 | if (root == null) { 26 | return 0; 27 | } 28 | 29 | int lHeight = TreeHeight.height(root.left); 30 | int rHeight = TreeHeight.height(root.right); 31 | 32 | int lDiameter = diameter(root.left); 33 | int rDiameter = diameter(root.right); 34 | 35 | 36 | /* Return max of following three 37 | 1) Diameter of left subtree 38 | 2) Diameter of right subtree 39 | 3) Height of left subtree + height of right subtree + 1 */ 40 | return Input.maxOfTwoNo((lHeight + rHeight + 1), Input.maxOfTwoNo(lDiameter, rDiameter)); 41 | 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /src/trees/tree/TreeHeight.java: -------------------------------------------------------------------------------- 1 | package trees.tree; 2 | 3 | public class TreeHeight { 4 | 5 | public static void main(String[] args) { 6 | 7 | Node root = Input.treeInput(); 8 | System.out.println("Height of root is - " + height(root)); 9 | 10 | } 11 | 12 | public static int height(Node root) { 13 | 14 | if (root == null) { 15 | return 0; 16 | } else { 17 | return maxOfTwoNo(height(root.left), height(root.right)) + 1; 18 | } 19 | 20 | } 21 | 22 | private static int maxOfTwoNo(int a, int b) { 23 | 24 | return a > b ? a : b; 25 | } 26 | } -------------------------------------------------------------------------------- /src/trees/tries/ForwardDNSLookUp.java: -------------------------------------------------------------------------------- 1 | package trees.tries; 2 | 3 | import utility.Trie; 4 | 5 | public class ForwardDNSLookUp { 6 | 7 | public static void main(String[] args) { 8 | 9 | Trie trie = new Trie<>(); 10 | 11 | trie.put("www.samsung.com", "107.108.11.123"); 12 | trie.put("www.samsung.net", "107.109.123.255"); 13 | trie.put("www.google.com", "74.125.200.106"); 14 | 15 | 16 | System.out.println("domain for google is " + trie.get("www.google.com")); 17 | System.out.println("domain for samsung.com is " + trie.get("www.samsung.com")); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/trees/tries/ReverseDNSLookUp.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Reverse DNS look up is using an internet IP address to find a domain name. For example, 4 | if you type 74.125.200.106 in browser, it automatically redirects to google.in. 5 | 6 | */ 7 | 8 | package trees.tries; 9 | 10 | 11 | import utility.Trie; 12 | 13 | public class ReverseDNSLookUp { 14 | 15 | public static void main(String[] args) { 16 | 17 | 18 | Trie trie = new Trie<>(); 19 | 20 | 21 | trie.put("107.108.11.123", "www.samsung.com"); 22 | trie.put("107.109.123.255", "www.samsung.net"); 23 | trie.put("74.125.200.106", "www.google.in"); 24 | 25 | System.out.println("domain for 107.109.123.255 is " + trie.get("107.109.123.255")); 26 | System.out.println("domain for 107.109.123.245 is " + trie.get("107.109.123.245")); 27 | 28 | } 29 | 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/utility/DLLNode.java: -------------------------------------------------------------------------------- 1 | package utility; 2 | 3 | /** 4 | * Created by poorvank on 11/06/16. 5 | */ 6 | public class DLLNode> implements Comparable> { 7 | 8 | private T info; 9 | private DLLNode next; 10 | private DLLNode previous; 11 | 12 | public DLLNode(T info) { 13 | this(info, null, null); 14 | } 15 | 16 | public DLLNode(T info, DLLNode next, DLLNode previous) { 17 | this.info = info; 18 | this.next = next; 19 | this.previous = previous; 20 | } 21 | 22 | public void setNext(DLLNode next) { 23 | this.next = next; 24 | } 25 | 26 | public T getInfo() { 27 | return info; 28 | } 29 | 30 | public DLLNode getNext() { 31 | return next; 32 | } 33 | 34 | public DLLNode getPrevious() { 35 | return previous; 36 | } 37 | 38 | public void setPrevious(DLLNode previous) { 39 | this.previous = previous; 40 | } 41 | 42 | /** 43 | * Refer to this link : http://stackoverflow.com/questions/21544716/implementing-comparable-with-a-generic-class 44 | */ 45 | @Override 46 | public int compareTo(DLLNode o) { 47 | return this.info.compareTo(o.getInfo()); 48 | } 49 | 50 | public String toString() { 51 | return info.toString(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/utility/GetInputFile.java: -------------------------------------------------------------------------------- 1 | package utility; 2 | 3 | import java.io.File; 4 | 5 | /** 6 | * Created by poorvank on 03/06/16. 7 | */ 8 | public class GetInputFile { 9 | 10 | public static File getFile(String name) { 11 | String absolutePath = new File("").getAbsolutePath(); 12 | return new File(absolutePath + "/src/inputFiles/" + name); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/utility/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | package utility; 2 | 3 | /** 4 | * Created by poorvank on 14/07/16. 5 | */ 6 | public class LongestCommonPrefix { 7 | 8 | public static String value(String s1,String s2) { 9 | int N = Math.min(s1.length(),s2.length()); 10 | for (int i=0;i w, respectively. 16 | */ 17 | 18 | public static boolean less(Comparable a,Comparable b) { 19 | return a.compareTo(b) < 0; 20 | } 21 | 22 | public static boolean less(Object a, Object b, Comparator comparator) { 23 | return comparator.compare(a,b) < 0; 24 | } 25 | 26 | public static void exchange(Comparable[] array,int i,int j) { 27 | Comparable t = array[i]; 28 | array[i] = array[j]; 29 | array[j] = t; 30 | } 31 | 32 | public static void assign(Comparable[] array,int i,Comparable key) { 33 | array[i] = key; 34 | } 35 | 36 | public static void print(Comparable[] array) { 37 | for (Comparable anArray : array) { 38 | System.out.print(anArray.toString() + " "); 39 | } 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/utility/Suffix.java: -------------------------------------------------------------------------------- 1 | //Implementation of all suffixes of a String 2 | 3 | package utility; 4 | 5 | /** 6 | * Created by poorvank on 14/07/16. 7 | */ 8 | public class Suffix implements Comparable { 9 | 10 | private final String text; //The entire text 11 | private final int index; //Index in the unsorted array 12 | 13 | public Suffix(String text, int index) { 14 | this.text = text; 15 | this.index = index; 16 | } 17 | 18 | //Length uniquely determines the starting point 19 | public int getLength() { 20 | return text.length()-index; 21 | } 22 | 23 | public int charAt(int i) { 24 | return text.charAt(index+i); 25 | } 26 | 27 | public int getIndex() { 28 | return index; 29 | } 30 | 31 | @Override 32 | public int compareTo(Suffix that) { 33 | if(this==that) { 34 | return 0; 35 | } 36 | int n = Math.min(that.getLength(),this.getLength()); 37 | for (int i=0;ithat.charAt(i)) { 39 | return 1; 40 | } 41 | if(this.charAt(i) %d (%.5f)" , source,destination,weight); 38 | } 39 | 40 | public static void main(String[] args) { 41 | DirectedEdge e = new DirectedEdge(12, 34, 5.67); 42 | System.out.println(e.toString()); 43 | } 44 | 45 | } 46 | --------------------------------------------------------------------------------