├── .gitattributes ├── .gitignore ├── README.md ├── java ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── groovy │ │ └── com │ │ │ └── lagostout │ │ │ ├── coderust │ │ │ ├── BinarySearch.groovy │ │ │ └── FindMaximumInSlidingWindow.groovy │ │ │ ├── common │ │ │ ├── BinaryTreeNode.groovy │ │ │ ├── FixedCapacityHeap.groovy │ │ │ ├── GraphTrait.groovy │ │ │ ├── Graphs.groovy │ │ │ ├── Heap.groovy │ │ │ ├── Heapable.groovy │ │ │ ├── Heaps.groovy │ │ │ ├── MultilineShortPrefixRecursiveToStringStyle.groovy │ │ │ ├── PriorityQueue.groovy │ │ │ ├── RandomConnectedGraphBuilder.groovy │ │ │ ├── RandomSpanningTreeBuilder.groovy │ │ │ ├── RawBinaryTreeNode.groovy │ │ │ ├── Trie.groovy │ │ │ ├── Util.groovy │ │ │ ├── ZeroBasedHeapIndexHelper.groovy │ │ │ ├── quicksortWithRandomlyPickedPivotScript.groovy │ │ │ └── suffixArrayQuicksortWithSuffixesShuffledBeforeSortScript.groovy │ │ │ ├── elementsofprogramminginterviews │ │ │ ├── binarytrees │ │ │ │ ├── ComputeLCAInBinaryTree.groovy │ │ │ │ ├── FindNonKBalancedNodeThatHasKBalancedDescendants.groovy │ │ │ │ ├── SizeOfLargestCompleteSubtree.groovy │ │ │ │ ├── TestIfABinaryTreeIsHeightBalanced.groovy │ │ │ │ └── TestIfBinaryTreeIsSymmetric.groovy │ │ │ ├── dynamicprogramming │ │ │ │ ├── CountNumberOfPlayPointCombinationsThatResultInAScoreUsingLessSpace.groovy │ │ │ │ ├── CountNumberOfPlayPointCombinationsThatResultInScore.groovy │ │ │ │ └── CountNumberOfUniquePlayPointSequencesThatResultInScore.groovy │ │ │ ├── greedyalgorithmsandinvariants │ │ │ │ └── ComputeAnOptimumAssignmentOfTasks.groovy │ │ │ └── hashtables │ │ │ │ ├── ComputeKMostFrequentQueries.groovy │ │ │ │ ├── ComputeLCA.groovy │ │ │ │ ├── ISBNCache.groovy │ │ │ │ ├── IsAnAnonymousLetterConstructible.groovy │ │ │ │ └── TestForPalindromicPermutations.groovy │ │ │ ├── leetcode │ │ │ └── NestedListWeightSum.groovy │ │ │ └── practicingrecursioninjava │ │ │ ├── ch1_examplesonintegers │ │ │ ├── P10_NSum.groovy │ │ │ ├── P11_SumSquares.groovy │ │ │ ├── P12_InvNSum.groovy │ │ │ ├── P1_PrintHello.groovy │ │ │ ├── P20_PrintReverse.groovy │ │ │ ├── P21_IsPalindrome.groovy │ │ │ ├── P22_Binomial.groovy │ │ │ ├── P23_Convert.groovy │ │ │ ├── P24_ConvertNB.groovy │ │ │ ├── P27_PrintALogNTimes.groovy │ │ │ ├── P28_PrintCommas.groovy │ │ │ ├── P29_PrintAExpTimes.groovy │ │ │ ├── P2_Print1ToN.groovy │ │ │ ├── P33_PrintAFactorialTimes.groovy │ │ │ ├── P3_PrintNDownTo1.groovy │ │ │ ├── P4_Power.groovy │ │ │ ├── P7_NumberOfDigits.groovy │ │ │ ├── P8_NContainsK.groovy │ │ │ └── P9_GCD.groovy │ │ │ └── ch2_examplesonarrays │ │ │ ├── P18_SelectionSort.groovy │ │ │ ├── P19_InsertionSort.groovy │ │ │ ├── P1_PrintArray.groovy │ │ │ ├── P20_BubbleSort.groovy │ │ │ └── P22_BinarySearch.groovy │ ├── java │ │ ├── Main.java │ │ └── com │ │ │ ├── google │ │ │ └── gson │ │ │ │ └── graph │ │ │ │ └── GraphAdapterBuilder.java │ │ │ └── lagostout │ │ │ ├── competitiveprogramming3 │ │ │ ├── datastructuresandlibraries │ │ │ │ └── JollyJumpers.java │ │ │ └── introduction │ │ │ │ ├── CostCutting.java │ │ │ │ ├── DivisionOfNlogonia.java │ │ │ │ ├── EventPlanning.java │ │ │ │ ├── HorrorDash.java │ │ │ │ ├── LoansomeCarBuyer.java │ │ │ │ ├── RelationalOperator.java │ │ │ │ ├── RequestForProposal.java │ │ │ │ └── TheSnail.java │ │ │ ├── geeksforgeeks │ │ │ └── HamiltonianPathFinder.java │ │ │ ├── interviewbit │ │ │ └── dynamicprogramming │ │ │ │ └── simplearraydp │ │ │ │ └── LengthOfLongestSubsequence.java │ │ │ └── leetcode │ │ │ ├── FizzBuzz.java │ │ │ ├── IslandPerimeter.java │ │ │ ├── Logger.java │ │ │ ├── MovingAverage.java │ │ │ ├── QueueReconstruction.java │ │ │ └── ReverseString.java │ ├── kotlin │ │ └── com │ │ │ └── lagostout │ │ │ ├── bytebybyte │ │ │ ├── dynamicprogramming │ │ │ │ ├── EditDistance.kt │ │ │ │ ├── EggDrop.kt │ │ │ │ ├── FindLargestSquareSubmatrix.kt │ │ │ │ ├── FloorTiling.kt │ │ │ │ ├── KnightProbability.kt │ │ │ │ ├── LongestIncreasingSubsequence.kt │ │ │ │ ├── MakingChange.kt │ │ │ │ ├── MatrixPath.kt │ │ │ │ ├── RodCutting.kt │ │ │ │ ├── TargetSum.kt │ │ │ │ └── ZeroOneKnapsack.kt │ │ │ └── recursion │ │ │ │ ├── FindAllPossibleArraysThatCouldResultInBinaryTree.kt │ │ │ │ ├── FindAllSubstringsOfString.kt │ │ │ │ ├── GreatestProductPath.kt │ │ │ │ ├── KnapsackProblemUsingDFS.kt │ │ │ │ ├── LowestCommonAncestor.kt │ │ │ │ ├── Permutations.kt │ │ │ │ └── PrintOddIndicesOfIntegerArray.kt │ │ │ ├── common │ │ │ ├── Common.kt │ │ │ └── Extensions.kt │ │ │ ├── dailycodingproblem │ │ │ └── InterleaveFirstHalfOfStackWithSecondHalfReversed.kt │ │ │ ├── datastructures │ │ │ ├── BinarySearchTree.kt │ │ │ ├── BinaryTreeNode.kt │ │ │ └── RawBinaryTreeNode.kt │ │ │ ├── elementsofprogramminginterviews │ │ │ ├── arrays │ │ │ │ ├── AdvancingThroughArray.kt │ │ │ │ ├── AdvancingThroughArrayWithMinimumSteps.kt │ │ │ │ ├── BuyAndSellStockOnce.kt │ │ │ │ ├── BuyAndSellStockTwice.kt │ │ │ │ ├── DeleteDuplicatesFromArray.kt │ │ │ │ ├── DeleteOccurrencesOfKey.kt │ │ │ │ ├── DutchNationalFlag.kt │ │ │ │ ├── DutchNationalFlagPreservingRelativeOrdering.kt │ │ │ │ ├── DutchNationalFlagWith3KeyValues.kt │ │ │ │ ├── DutchNationalFlagWith4KeyValues.kt │ │ │ │ ├── DutchNationalFlagWithBooleanValues.kt │ │ │ │ ├── IncrementArbitraryPrecisionInteger.kt │ │ │ │ ├── InversePermutation.kt │ │ │ │ ├── LengthOfLongestSubarrayOfEqualEntries.kt │ │ │ │ ├── LimitDuplicatesInSortedArray.kt │ │ │ │ ├── MultiplyTwoArbitraryPrecisionIntegers.kt │ │ │ │ ├── NextPermutation.kt │ │ │ │ ├── PermuteElementsOfArray.kt │ │ │ │ ├── PrimesToN.kt │ │ │ │ ├── SampleOfflineData.kt │ │ │ │ ├── SpiralOrderingOf2DArray.kt │ │ │ │ ├── SudokuChecker.kt │ │ │ │ └── SumOfIntegersEncodedAsBinaryNumbers.kt │ │ │ ├── binarysearchtrees │ │ │ │ ├── BSTInsertionAndDeletion.kt │ │ │ │ ├── BSTInsertionAndDeletionWhenOnlyLinksCanChange.kt │ │ │ │ ├── BuildMinimumHeightBST.kt │ │ │ │ ├── ComputeLCAInBST.kt │ │ │ │ ├── EnumerateNumbers.kt │ │ │ │ ├── FIndFirstKeyGreaterThanValueInBst.kt │ │ │ │ ├── FindClosestEntries.kt │ │ │ │ ├── FindFirstInorderOccurrenceInBST.kt │ │ │ │ ├── FindKLargestElementsInBST.kt │ │ │ │ ├── ReconstructBSTFromTraversalData.kt │ │ │ │ ├── TestIfBinaryTreeSatisfiesBstProperty.kt │ │ │ │ └── TestIfThreeBSTNodesAreTotallyOrdered.kt │ │ │ ├── binarytrees │ │ │ │ ├── BuildMaxTree.kt │ │ │ │ ├── ComputeExteriorOfBinaryTree.kt │ │ │ │ ├── ComputeRightSiblingTree.kt │ │ │ │ ├── ComputeRightSiblingTreeUsingRightChildField.kt │ │ │ │ ├── ComputeTheLCAWhenNodesHaveParentPointers.kt │ │ │ │ ├── ComputeTheSuccessor.kt │ │ │ │ ├── FindRootToLeafPathWithSpecifiedSum.kt │ │ │ │ ├── InOrderTraversalWithConstantSpace.kt │ │ │ │ ├── InOrderTraversalWithoutRecursion.kt │ │ │ │ ├── IterativePreAndPostOrderTraversalWithLinearSpace.kt │ │ │ │ ├── KthNodeInInOrderTraversal.kt │ │ │ │ ├── LinkedListFromBinaryTreeLeaves.kt │ │ │ │ ├── PreOrderTraversalWithoutRecursion.kt │ │ │ │ ├── ReconstructBinaryTreeFromPostorderTraversal.kt │ │ │ │ ├── ReconstructBinaryTreeFromPostorderWithMarkers.kt │ │ │ │ ├── ReconstructBinaryTreeFromPreorderTraversal.kt │ │ │ │ ├── ReconstructBinaryTreeFromPreorderWithMarkers.kt │ │ │ │ ├── SumOfRootToLeafPathsInABinaryTree.kt │ │ │ │ └── namespace.kt │ │ │ ├── dynamicprogramming │ │ │ │ ├── BinomialCoefficient.kt │ │ │ │ ├── ComputeLevenshteinDistance.kt │ │ │ │ ├── ComputeLevenshteinDistanceInWorstCaseSpaceOfShorterStringLength.kt │ │ │ │ ├── ComputeMinimumCharsToDeleteToMakePalindrome.kt │ │ │ │ ├── CountNumberOfDistinctSequencesOfPlayPointsOfScoreOfGameWithTwoTeams.kt │ │ │ │ ├── DetermineIfStringIsAnInterleaving.kt │ │ │ │ ├── DivideSpoilsFairly.kt │ │ │ │ ├── DivideSpoilsFairlyWithSameNumberOfItemsForEachThief.kt │ │ │ │ ├── DynamicProgramming.kt │ │ │ │ ├── ElectoralCollegeTie.kt │ │ │ │ ├── EnumerateOccurrencesOfSequenceIn2DArrayWithSingleVisitPerPositionLimit.kt │ │ │ │ ├── FractionalKnapsackProblem.kt │ │ │ │ ├── KnapsackProblem.kt │ │ │ │ ├── KnapsackProblemWithAchievableWeightSpaceComplexity.kt │ │ │ │ ├── KnapsackProblemWithWeightSpaceComplexity.kt │ │ │ │ ├── LevenshteinDistanceOfBestRegexMatch.kt │ │ │ │ ├── LongestNondecreasingSubsequenceInNLogNTime.kt │ │ │ │ ├── LongestSequenceOfCharactersThatIsASubsequenceOf2Strings.kt │ │ │ │ ├── MaximumAscendingSubsetOfPointsInAPlane.kt │ │ │ │ ├── MaximumNumberOfFishThatCanBeCaughtStartingAndEndingAtAnyPoint.kt │ │ │ │ ├── MaximumNumberOfTeamLeadChanges.kt │ │ │ │ ├── MaximumValueOfFishThatCanBeCaught.kt │ │ │ │ ├── MinimizeMessinessInLinearTimeConstantSpace.kt │ │ │ │ ├── NumberOfMonotoneDecimalNumbersOfLengthK.kt │ │ │ │ ├── NumberOfStrictlyMonotoneDecimalNumbersOfLengthK.kt │ │ │ │ ├── NumberOfWaysToTraverse2DArray.kt │ │ │ │ ├── NumberOfWaysToTraverse2DArrayWithLessSpace.kt │ │ │ │ ├── NumberOfWaysToTraverse2DArrayWithObstacles.kt │ │ │ │ ├── RegexMatchWithMinimumLevenshteinDistance.kt │ │ │ │ ├── SearchForSequenceIn2DArray.kt │ │ │ │ ├── SearchForSequenceIn2DArrayWithSingleVisitPerPositionLimit.kt │ │ │ │ └── WaysToClimbStairs.kt │ │ │ ├── graphs │ │ │ │ ├── CloneAGraph.kt │ │ │ │ ├── ComputeBlackRegionContainingMostPoints.kt │ │ │ │ ├── ComputeEnclosedRegions.kt │ │ │ │ ├── DeadlockDetection.kt │ │ │ │ ├── DeadlockDetectionInUndirectedGraph.kt │ │ │ │ ├── GraphRemainsConnectedAfterRemovingAnyEdge.kt │ │ │ │ ├── PaintBooleanMatrix.kt │ │ │ │ ├── Point.kt │ │ │ │ ├── SearchAMaze.kt │ │ │ │ ├── SetPointToBlackAndGetLargestBlackRegionSize.kt │ │ │ │ ├── ShortestAdditionChainExponentiation.kt │ │ │ │ ├── TransformOneStringToAnother.kt │ │ │ │ ├── WiredConnections.kt │ │ │ │ └── namespace.kt │ │ │ ├── greedyalgorithmsandinvariants │ │ │ │ ├── FindMajorityElement.kt │ │ │ │ ├── GasupProblem.kt │ │ │ │ ├── GasupProblemWhenAmpleCityMayNotExist.kt │ │ │ │ ├── KSumWithRepetitionAllowed.kt │ │ │ │ ├── MaximizeNumberOfVisiblePointsInFieldOfView.kt │ │ │ │ ├── MinimizeCamerasToMonitorRobotsAroundCastle.kt │ │ │ │ ├── ScheduleToMinimizeWaitingTime.kt │ │ │ │ ├── TheIntervalCoveringProblem.kt │ │ │ │ ├── ThreeSumProblemWithNoRepetition.kt │ │ │ │ └── ThreeSumProblemWithRepetitionAllowed.kt │ │ │ ├── hashtables │ │ │ │ ├── AverageOfTop3Scores.kt │ │ │ │ ├── ComputeAllStringDecompositions.kt │ │ │ │ ├── FindLongestSubarrayWithDistinctElements.kt │ │ │ │ ├── FindSmallestSubarrayCoveringAllValues.kt │ │ │ │ ├── FindSmallestSubarraySequentiallyCoveringAllValues.kt │ │ │ │ ├── FindTheNearestRepeatedEntriesInAnArray.kt │ │ │ │ ├── ImplementHashFunctionForChess.kt │ │ │ │ ├── LengthOfLongestContainedInterval.kt │ │ │ │ ├── RearrangeArrayToMaximizeLengthOfShortestSubarrayContainingAllDistinctValues.kt │ │ │ │ ├── RearrarangeArraySoNoEqualElementsAreKOrLessApart.kt │ │ │ │ ├── ShortestSubarrayOfDistinctValues.kt │ │ │ │ └── TestCollatzConjecture.kt │ │ │ ├── heaps │ │ │ │ ├── ComputeKClosestStars.kt │ │ │ │ ├── ComputeKLargestElementsInMaxHeap.kt │ │ │ │ ├── ImplementQueueUsingHeap.kt │ │ │ │ ├── ImplementStackUsingHeap.kt │ │ │ │ ├── MedianOfOnlineData.kt │ │ │ │ ├── MergeSortedFiles.kt │ │ │ │ ├── SortAnAlmostSortedArray.kt │ │ │ │ └── SortIncreasingDecreasingArray.kt │ │ │ ├── honors │ │ │ │ ├── BuyAndSellStockKTimes.kt │ │ │ │ ├── ComputeGCD.kt │ │ │ │ ├── FairBonuses.kt │ │ │ │ ├── FindFirstMissingPositiveEntry.kt │ │ │ │ ├── IdentifyPositionsAttackedByRooks.kt │ │ │ │ ├── JustifyText.kt │ │ │ │ ├── LongestContiguousIncreasingSubarray.kt │ │ │ │ ├── MaxProductOfTriples.kt │ │ │ │ ├── MaximumProductOfAllEntriesButOne.kt │ │ │ │ ├── ProductsOfAllEntriesButOne.kt │ │ │ │ └── RotateArray.kt │ │ │ ├── linkedlists │ │ │ │ ├── CyclicRightShiftForSinglyLinkedLists.kt │ │ │ │ ├── EvenOddMerge.kt │ │ │ │ ├── LinkedListNode.kt │ │ │ │ ├── ListPivoting.kt │ │ │ │ ├── MergeTwoSortedLists.kt │ │ │ │ ├── RemoveDuplicatesFromSortedList.kt │ │ │ │ ├── RemoveEntriesFromListWhenMoreThanMDuplicates.kt │ │ │ │ ├── RemoveKthLastElement.kt │ │ │ │ ├── ReverseList.kt │ │ │ │ ├── ReverseSingleSublist.kt │ │ │ │ ├── ReverseSingleSublistKNodesAtATime.kt │ │ │ │ ├── TestForCyclicity.kt │ │ │ │ ├── TestForOverlappingLists.kt │ │ │ │ ├── TestForOverlappingListsWithCyclesPossible.kt │ │ │ │ ├── TestIfDoublyLinkedListIsPalindrome.kt │ │ │ │ └── TestIfListIsPalindromic.kt │ │ │ ├── primitivetypes │ │ │ │ ├── ClosestIntegerWithSameWeight.kt │ │ │ │ ├── ClosestIntegerWithSameWeightInConstantSpaceTime.kt │ │ │ │ ├── ComputeProductWithoutArithmeticOperators.kt │ │ │ │ ├── ComputeXToPowerY.kt │ │ │ │ ├── Divide.kt │ │ │ │ ├── ParityOfAWord.kt │ │ │ │ ├── ReverseBits.kt │ │ │ │ ├── ReverseDigits.kt │ │ │ │ └── SwapBits.kt │ │ │ ├── recursion │ │ │ │ ├── GenerateAllNonAttackingPlacementsOfNQueens.kt │ │ │ │ ├── GenerateNumberOfNonAttackingPlacementsOfNQueens.kt │ │ │ │ ├── GeneratePermutationsWhenDuplicatesMayBePresent.kt │ │ │ │ ├── MaximumWaterTrappedByVerticalLines.kt │ │ │ │ ├── SmallestNumberOfQueensToAttackUncoveredSquares.kt │ │ │ │ └── towersofhanoi │ │ │ │ │ ├── TowersOfHanoi.kt │ │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithForbiddenMove.kt │ │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithFourPegs.kt │ │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithOneOfThreeMovesRequired.kt │ │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithOnePegAlwaysInvolved.kt │ │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithRelaxedConstraint.kt │ │ │ │ │ ├── TowersOfHanoiWithColoredDisks.kt │ │ │ │ │ ├── TowersOfHanoiWithPairsOfRingsOfEqualSize.kt │ │ │ │ │ └── TowersOfHanoiWithoutRecursion.kt │ │ │ ├── searching │ │ │ │ ├── ComputeIntegerSquareRoot.kt │ │ │ │ ├── ComputeRealSquareRoot.kt │ │ │ │ ├── DivideWithoutUsingDivisionOperator.kt │ │ │ │ ├── FindArrayEntryEqualToItsIndex.kt │ │ │ │ ├── FindArrayEntryEqualToItsIndexWhenThereMayBeDuplicates.kt │ │ │ │ ├── FindElementInCyclicallySortedArray.kt │ │ │ │ ├── FindFirstIndexOfElementGreaterThanKey.kt │ │ │ │ ├── FindIntervalEnclosingInteger.kt │ │ │ │ ├── FindKthLargestElement.kt │ │ │ │ ├── FindKthLargestElementWhenDuplicatesPresent.kt │ │ │ │ ├── FindLocalMinimum.kt │ │ │ │ ├── FindMaxInAscendingDescendingSequences.kt │ │ │ │ ├── FindMedian.kt │ │ │ │ ├── FindMinMaxSimultaneously.kt │ │ │ │ ├── FindStringWithPrefixInArrayOfSortedStrings.kt │ │ │ │ ├── Search2DSortedArray.kt │ │ │ │ ├── SearchCyclicallySortedArray.kt │ │ │ │ └── SearchSortedArrayForFirstOccurrence.kt │ │ │ ├── sorting │ │ │ │ ├── FastSortingAlgorithmForLists.kt │ │ │ │ ├── IntersectionOfTwoSortedArrays.kt │ │ │ │ ├── MergeSortedArrays.kt │ │ │ │ ├── MergingIntervals.kt │ │ │ │ ├── PartitionAndSortArrayWithManyRepeatedEntries.kt │ │ │ │ ├── PeakBandwidthUsage.kt │ │ │ │ ├── RemoveFirstNameDuplicates.kt │ │ │ │ ├── RenderACalendar.kt │ │ │ │ ├── TeamPhotoDay.kt │ │ │ │ └── UnionOfIntervals.kt │ │ │ ├── stacksandqueues │ │ │ │ ├── ComputeBinaryTreeLevelAverages.kt │ │ │ │ ├── ComputeBinaryTreeNodesInBottomUpLeftToRightOrder.kt │ │ │ │ ├── ComputeBinaryTreeNodesInOrderOfIncreasingDepth.kt │ │ │ │ ├── ComputeBinaryTreeNodesInTopDownAlternatingLeftToRightOrder.kt │ │ │ │ ├── ComputeBuildingsWithSunsetViewWhenBuildingsPresentedEastToWest.kt │ │ │ │ ├── ComputeBuildingsWithSunsetViewWhenBuildingsPresentedWestToEast.kt │ │ │ │ ├── EvaluateRpnExpression.kt │ │ │ │ ├── EvaluateRpnExpressionWhenOperatorPrecedesOperands.kt │ │ │ │ ├── ImplementCircularQueue.kt │ │ │ │ ├── ImplementQueueUsingStacks.kt │ │ │ │ ├── ImplementQueueWithMaxAPI.kt │ │ │ │ ├── NormalizePathnames.kt │ │ │ │ ├── SearchPostingsList.kt │ │ │ │ └── StackWithMaxAPI.kt │ │ │ └── strings │ │ │ │ ├── BaseConversion.kt │ │ │ │ ├── ComputeMnemonicsForPhoneNumber.kt │ │ │ │ ├── ComputeSpreadsheetColumnEncoding.kt │ │ │ │ ├── ComputeSpreadsheetColumnEncodingWhereAIsZero.kt │ │ │ │ ├── ComputeValidIPAddresses.kt │ │ │ │ ├── ComputeValidIPAddressesWhenNumberOfPeriodsVariableAndStringLengthUnbounded.kt │ │ │ │ ├── ConvertFromRomanToDecimal.kt │ │ │ │ ├── InterconvertStringsAndIntegers.kt │ │ │ │ ├── LookAndSayProblem.kt │ │ │ │ ├── ReplaceAndRemove.kt │ │ │ │ ├── ReverseWordsInSentence.kt │ │ │ │ ├── ShortestValidRomanNumber.kt │ │ │ │ ├── TelexEncoding.kt │ │ │ │ ├── TestPalindromicity.kt │ │ │ │ ├── TestStringForWellFormedness.kt │ │ │ │ ├── VerifyRomanNumberIsValid.kt │ │ │ │ └── WriteStringSinusoidally.kt │ │ │ └── scratch │ │ │ └── .gitignore │ └── sh │ │ └── move-and-rename-file-for-submission.sh │ └── test │ ├── groovy │ └── com │ │ └── lagostout │ │ ├── coderust │ │ ├── BinarySearchSpec.groovy │ │ └── FindMaximumInSlidingWindowSpec.groovy │ │ ├── common │ │ ├── FixedCapacityHeapSpec.groovy │ │ ├── GraphsSpec.groovy │ │ ├── HeapSpec.groovy │ │ ├── HeapsSpec.groovy │ │ ├── PriorityQueueSpec.groovy │ │ ├── RandomConnectedGraphBuilderSpec.groovy │ │ ├── RandomSpanningTreeBuilderSpec.groovy │ │ └── TrieSpec.groovy │ │ ├── competitiveprogramming3 │ │ └── introduction │ │ │ └── DivisionOfNlogoniaSpec.groovy │ │ ├── elementsofprogramminginterviews │ │ ├── binarytrees │ │ │ ├── ComputeLCAInBinaryTreeSpec.groovy │ │ │ ├── FindNonKBalancedNodeThatHasKBalancedDescendantsSpec.groovy │ │ │ ├── SizeOfLargestCompleteSubtreeSpec.groovy │ │ │ ├── TestIfABinaryTreeIsHeightBalancedSpec.groovy │ │ │ └── TestIfBinaryTreeIsSymmetricSpec.groovy │ │ ├── dynamicprogramming │ │ │ ├── CountNumberOfPlayPointCombinationsThatResultInAScoreUsingLessSpaceSpec.groovy │ │ │ ├── CountNumberOfPlayPointCombinationsThatResultInScoreSpec.groovy │ │ │ └── CountNumberOfUniquePlayPointSequencesThatResultInScoreSpec.groovy │ │ ├── greedyalgorithmsandinvariants │ │ │ └── ComputeAnOptimumAssignmentOfTasksSpec.groovy │ │ └── hashtables │ │ │ ├── ComputeKMostFrequentQueriesSpec.groovy │ │ │ ├── ComputeLCASpec.groovy │ │ │ ├── ISBNCacheSpec.groovy │ │ │ ├── IsAnAnonymousLetterConstructibleSpec.groovy │ │ │ └── TestForPalindromicPermutationsSpec.groovy │ │ ├── geeksforgeeks │ │ └── HamiltonianPathSpec.groovy │ │ ├── interviewbit │ │ └── dynamicprograming │ │ │ └── simplearraydp │ │ │ └── LengthOfLongestSubsequenceSpec.groovy │ │ ├── leetcode │ │ ├── FizzBuzzSpec.groovy │ │ ├── IslandPerimeterSpec.groovy │ │ ├── LoggerSpec.groovy │ │ ├── MovingAverageSpec.groovy │ │ ├── NestedListWeightSumSpec.groovy │ │ ├── QueueReconstructionSpec.groovy │ │ └── ReverseStringSpec.groovy │ │ ├── practicingrecursioninjava │ │ ├── ch1_examplesonintegers │ │ │ ├── BinomialSpec.groovy │ │ │ ├── ConvertNBSpec.groovy │ │ │ ├── ConvertSpec.groovy │ │ │ ├── GCDSpec.groovy │ │ │ ├── InvNSumSpec.groovy │ │ │ ├── IsPalindromeSpec.groovy │ │ │ ├── NContainsKSpec.groovy │ │ │ ├── NSumSpec.groovy │ │ │ ├── NumberOfDigitsSpec.groovy │ │ │ ├── PowerSpec.groovy │ │ │ ├── Print1ToNSpec.groovy │ │ │ ├── PrintAExpTimesSpec.groovy │ │ │ ├── PrintAFactorialTimesSpec.groovy │ │ │ ├── PrintALogNTimesSpec.groovy │ │ │ ├── PrintCommasSpec.groovy │ │ │ ├── PrintHelloSpec.groovy │ │ │ ├── PrintNDownTo1Spec.groovy │ │ │ ├── PrintReverseSpec.groovy │ │ │ └── SumSquaresSpec.groovy │ │ └── ch2_examplesonarrays │ │ │ ├── BinarySearchSpec.groovy │ │ │ ├── BubbleSortSpec.groovy │ │ │ ├── InsertionSortSpec.groovy │ │ │ ├── PrintArraySpec.groovy │ │ │ └── SelectionSortSpec.groovy │ │ └── scratch │ │ └── .gitignore │ ├── kotlin │ └── com │ │ └── lagostout │ │ ├── bytebybyte │ │ ├── dynamicprogramming │ │ │ ├── EditDistanceSpek.kt │ │ │ ├── EggDropSpek.kt │ │ │ ├── FindLargestSquareSubmatrixSpek.kt │ │ │ ├── FloorTilingSpek.kt │ │ │ ├── KnightProbabilitySpek.kt │ │ │ ├── LongestIncreasingSubsequenceSpek.kt │ │ │ ├── MakingChangeSpek.kt │ │ │ ├── MatrixPathSpek.kt │ │ │ ├── RodCuttingSpek.kt │ │ │ ├── TargetSumSpek.kt │ │ │ └── ZeroOneKnapsackSpek.kt │ │ └── recursion │ │ │ ├── FindAllPossibleArraysThatCouldResultInBinaryTreeSpek.kt │ │ │ ├── FindAllSubstringsOfStringSpek.kt │ │ │ ├── GreatestProductPathSpek.kt │ │ │ ├── KnapsackProblemUsingDFSSpek.kt │ │ │ ├── LowestCommonAncestorSpek.kt │ │ │ ├── PermutationsSpek.kt │ │ │ └── PrintOddIndicesOfIntegerArraySpek.kt │ │ ├── dailycodingproblem │ │ └── InterleaveFirstHalfOfStackWithSecondHalfReversedSpek.kt │ │ ├── datastructures │ │ └── BinarySearchTreeSpek.kt │ │ ├── elementsofprogramminginterviews │ │ ├── arrays │ │ │ ├── AdvancingThroughArraySpek.kt │ │ │ ├── AdvancingThroughArrayWithMinimumStepsSpek.kt │ │ │ ├── BuyAndSellStockOnceSpek.kt │ │ │ ├── BuyAndSellStockTwiceSpek.kt │ │ │ ├── DeleteDuplicatesFromArraySpek.kt │ │ │ ├── DeleteOccurrencesOfKeySpek.kt │ │ │ ├── DutchNationalFlagPreservingRelativeOrderingSpek.kt │ │ │ ├── DutchNationalFlagSpek.kt │ │ │ ├── DutchNationalFlagWith3KeyValuesSpek.kt │ │ │ ├── DutchNationalFlagWith4KeyValuesSpek.kt │ │ │ ├── DutchNationalFlagWithBooleanValuesSpek.kt │ │ │ ├── IncrementArbitraryPrecisionIntegerSpek.kt │ │ │ ├── InversePermutationSpek.kt │ │ │ ├── LengthOfLongestSubarrayOfEqualEntriesSpek.kt │ │ │ ├── LimitDuplicatesInSortedArraySpek.kt │ │ │ ├── MultiplyTwoArbitraryPrecisionIntegersSpek.kt │ │ │ ├── NextPermutationSpek.kt │ │ │ ├── PermuteElementsOfArraySpek.kt │ │ │ ├── PrimesToNSpek.kt │ │ │ ├── SampleOfflineDataSpek.kt │ │ │ ├── SpiralOrderingOf2DArraySpek.kt │ │ │ ├── SudokuCheckerSpek.kt │ │ │ └── SumOfIntegersEncodedAsBinaryNumbersSpek.kt │ │ ├── binarysearchtrees │ │ │ ├── BSTInsertionAndDeletionSpek.kt │ │ │ ├── BSTInsertionAndDeletionWhenOnlyLinksCanChangeSpek.kt │ │ │ ├── BuildMinimumHeightBSTSpek.kt │ │ │ ├── ComputeLCAInBSTSpek.kt │ │ │ ├── EnumerateNumbersSpek.kt │ │ │ ├── FIndFirstKeyGreaterThanValueInBstSpek.kt │ │ │ ├── FindClosestEntriesSpek.kt │ │ │ ├── FindFirstInorderOccurrenceInBSTSpek.kt │ │ │ ├── FindKLargestElementsInBSTSpek.kt │ │ │ ├── ReconstructBSTFromTraversalDataSpek.kt │ │ │ ├── TestIfBinaryTreeSatisfiesBstPropertySpek.kt │ │ │ └── TestIfThreeBSTNodesAreTotallyOrderedSpek.kt │ │ ├── binarytrees │ │ │ ├── BuildMaxTreeSpek.kt │ │ │ ├── ComputeExteriorOfBinaryTreeSpek.kt │ │ │ ├── ComputeRightSiblingTreeSpek.kt │ │ │ ├── ComputeRightSiblingTreeUsingRightChildFieldSpek.kt │ │ │ ├── ComputeTheLCAWhenNodesHaveParentPointersSpek.kt │ │ │ ├── ComputeTheSuccessorSpek.kt │ │ │ ├── FindRootToLeafPathWithSpecifiedSumSpek.kt │ │ │ ├── InOrderTraversalWithoutRecursionSpek.kt │ │ │ ├── InorderTraversalWithConstantSpaceSpek.kt │ │ │ ├── IterativePreAndPostOrderTraversalWithLinearSpaceSpek.kt │ │ │ ├── KthNodeInInOrderTraversalSpek.kt │ │ │ ├── LinkedListFromBinaryTreeLeavesSpek.kt │ │ │ ├── PreOrderTraversalWithoutRecursionSpek.kt │ │ │ ├── ReconstructBinaryTreeFromPostorderTraversalSpek.kt │ │ │ ├── ReconstructBinaryTreeFromPostorderWithMarkersSpek.kt │ │ │ ├── ReconstructBinaryTreeFromPreorderTraversalSpek.kt │ │ │ ├── ReconstructBinaryTreeFromPreorderWithMarkers.kt │ │ │ ├── SumOfRootToLeafPathsInABinaryTreeSpek.kt │ │ │ └── testnamespace.kt │ │ ├── dynamicprogramming │ │ │ ├── BinomialCoefficientSpek.kt │ │ │ ├── ComputeLevenshteinDistanceInWorstCaseSpaceOfShorterStringLengthSpek.kt │ │ │ ├── ComputeLevenshteinDistanceSpek.kt │ │ │ ├── ComputeMinimumCharsToDeleteToMakePalindromeSpek.kt │ │ │ ├── CountNumberOfDistinctSequencesOfPlayPointsOfScoreOfGameWithTwoTeamsSpek.kt │ │ │ ├── DetermineIfStringIsAnInterleavingSpek.kt │ │ │ ├── DivideSpoilsFairlySpek.kt │ │ │ ├── DivideSpoilsFairlyWithSameNumberOfItemsForEachThiefSpek.kt │ │ │ ├── DynamicProgrammingUtils.kt │ │ │ ├── ElectoralCollegeTieSpek.kt │ │ │ ├── EnumerateOccurrencesOfSequenceIn2DArrayWithSingleVisitPerPositionLimitSpek.kt │ │ │ ├── FractionalKnapsackProblemSpek.kt │ │ │ ├── KnapsackProblemSpek.kt │ │ │ ├── KnapsackProblemWithAchievableWeightSpaceComplexitySpek.kt │ │ │ ├── KnapsackProblemWithWeightSpaceComplexitySpek.kt │ │ │ ├── LevenshteinDistanceOfBestRegexMatchSpek.kt │ │ │ ├── LongestNondecreasingSubsequenceInNLogNTimeSpek.kt │ │ │ ├── LongestSequenceOfCharactersThatIsASubsequenceOf2StringsSpek.kt │ │ │ ├── MaximumAscendingSubsetOfPointsInAPlaneSpek.kt │ │ │ ├── MaximumNumberOfFishThatCanBeCaughtStartingAndEndingAtAnyPointSpek.kt │ │ │ ├── MaximumNumberOfTeamLeadChangesSpek.kt │ │ │ ├── MaximumValueOfFishThatCanBeCaughtSpek.kt │ │ │ ├── MinimizeMessinessInLinearTimeConstantSpaceSpek.kt │ │ │ ├── NumberOfMonotoneDecimalNumbersOfLengthKSpek.kt │ │ │ ├── NumberOfStrictlyMonotoneDecimalNumbersOfLengthKSpek.kt │ │ │ ├── NumberOfWaysToTraverse2DArraySpek.kt │ │ │ ├── NumberOfWaysToTraverse2DArrayWithLessSpaceSpek.kt │ │ │ ├── NumberOfWaysToTraverse2DArrayWithObstaclesSpek.kt │ │ │ ├── RegexMatchWithMinimumLevenshteinDistanceSpek.kt │ │ │ ├── SearchForSequenceIn2DArraySpek.kt │ │ │ ├── SearchForSequenceIn2DArrayWithSingleVisitPerPositionLimitSpek.kt │ │ │ └── WaysToClimbStairsSpek.kt │ │ ├── graphs │ │ │ ├── CloneAGraphSpek.kt │ │ │ ├── ComputeBlackRegionContainingMostPointsSpek.kt │ │ │ ├── ComputeEnclosedRegionsSpek.kt │ │ │ ├── DeadlockDetectionInUndirectedGraphSpek.kt │ │ │ ├── DeadlockDetectionSpek.kt │ │ │ ├── GraphRemainsConnectedAfterRemovingAnyEdgeSpek.kt │ │ │ ├── PaintBooleanMatrixSpek.kt │ │ │ ├── SearchAMazeSpek.kt │ │ │ ├── SetPointToBlackAndGetLargestBlackRegionSizeSpek.kt │ │ │ ├── ShortestAdditionChainExponentiationSpek.kt │ │ │ ├── TransformOneStringToAnotherSpek.kt │ │ │ └── WiredConnectionsSpek.kt │ │ ├── greedyalgorithmsandinvariants │ │ │ ├── FindMajorityElementSpek.kt │ │ │ ├── GasupProblemSpek.kt │ │ │ ├── GasupProblemWhenAmpleCityMayNotExistSpek.kt │ │ │ ├── KSumWithRepetitionAllowedSpek.kt │ │ │ ├── MaximizeNumberOfVisiblePointsInFieldOfViewSpek.kt │ │ │ ├── MinimizeCamerasToMonitorRobotsPatrollingACastleSpek.kt │ │ │ ├── ScheduleToMinimizeWaitTimeSpek.kt │ │ │ ├── TheIntervalCoveringProblemSpek.kt │ │ │ ├── ThreeSumProblemWithNoRepetitionSpek.kt │ │ │ └── ThreeSumProblemWithRepetitionAllowedSpek.kt │ │ ├── hashtables │ │ │ ├── AverageOfTop3ScoresSpek.kt │ │ │ ├── ComputeAllStringDecompositionsSpek.kt │ │ │ ├── FindLongestSubarrayWithDistinctElementsSpek.kt │ │ │ ├── FindSmallestSubarrayCoveringAllValuesSpek.kt │ │ │ ├── FindSmallestSubarraySequentiallyCoveringAllValuesSpek.kt │ │ │ ├── FindTheNearestRepeatedEntriesInAnArraySpek.kt │ │ │ ├── ImplementHashFunctionForChessSpek.kt │ │ │ ├── LengthOfLongestContainedIntervalSpek.kt │ │ │ ├── RearrangeArraySoNoEqualElementsAreKOrLessApartSpek.kt │ │ │ ├── RearrangeArrayToMaximizeLengthOfShortestSubarrayContainingAllDistinctValuesSpek.kt │ │ │ ├── ShortestSubarrayOfDistinctValuesSpek.kt │ │ │ └── TestCollatzConjectureSpek.kt │ │ ├── heaps │ │ │ ├── ComputeKClosestStarsSpek.kt │ │ │ ├── ComputeKLargestElementsInMaxHeapSpek.kt │ │ │ ├── ImplementQueueUsingHeapSpek.kt │ │ │ ├── ImplementStackUsingHeapSpek.kt │ │ │ ├── MedianOfOnlineDataSpek.kt │ │ │ ├── MergeSortedFilesSpek.kt │ │ │ ├── SortAnAlmostSortedArraySpek.kt │ │ │ └── SortIncreasingDecreasingArraysSpek.kt │ │ ├── honors │ │ │ ├── BuyAndSellStockKTimesSpek.kt │ │ │ ├── ComputeGCDSpek.kt │ │ │ ├── FairBonusesSpek.kt │ │ │ ├── FindFirstMissingPositiveEntrySpek.kt │ │ │ ├── IdentifyPositionsAttackedByRooksSpek.kt │ │ │ ├── JustifyTextSpek.kt │ │ │ ├── LongestContiguousIncreasingSubarraySpek.kt │ │ │ ├── MaxProductOfTriplesSpek.kt │ │ │ ├── MaximumProductOfAllEntriesButOneSpek.kt │ │ │ ├── ProductsOfAllEntriesButOneSpek.kt │ │ │ └── RotateArraySpek.kt │ │ ├── linkedlists │ │ │ ├── CyclicRightShiftForSinglyLinkedListsSpek.kt │ │ │ ├── EvenOddMergeSpek.kt │ │ │ ├── ListPivotingSpek.kt │ │ │ ├── MergeTwoSortedListsSpek.kt │ │ │ ├── RemoveDuplicatesFromSortedListSpek.kt │ │ │ ├── RemoveEntriesFromListWhenThereAreMoreThanMDuplicatesSpek.kt │ │ │ ├── RemoveKthLastElementSpek.kt │ │ │ ├── ReverseListSpek.kt │ │ │ ├── ReverseSingleSublistKNodesAtATimeSpek.kt │ │ │ ├── ReverseSingleSublistSpek.kt │ │ │ ├── TestForCyclicitySpek.kt │ │ │ ├── TestForOverlappingListsSpek.kt │ │ │ ├── TestForOverlappingListsWithCyclesPossibleSpek.kt │ │ │ ├── TestIfDoublyLinkedListIsPalindromeSpek.kt │ │ │ ├── TestIfListIsPalindromicSpek.kt │ │ │ └── testnamespace.kt │ │ ├── primitivetypes │ │ │ ├── ClosestIntegerWithSameWeightSpek.kt │ │ │ ├── ComputeProductWithoutArithmeticOperatorsSpek.kt │ │ │ ├── ComputeXToPowerYSpek.kt │ │ │ ├── DivideSpek.kt │ │ │ ├── ParityOfAWordSpek.kt │ │ │ ├── ReverseBitsSpek.kt │ │ │ ├── ReverseDigitsSpek.kt │ │ │ └── SwapBitsSpek.kt │ │ ├── recursion │ │ │ ├── GenerateAllNonAttackingPlacementsOfNQueensSpek.kt │ │ │ ├── GenerateNumberOfNonAttackingPlacementsOfNQueensSpek.kt │ │ │ ├── GeneratePermutationsWhenDuplicatesMayBePresentSpek.kt │ │ │ ├── MaximumWaterTrappedByVerticalLinesSpek.kt │ │ │ ├── SmallestNumberOfQueensToAttackUncoveredSquaresSpek.kt │ │ │ └── towersofhanoi │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithForbiddenMoveSpek.kt │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithFourPegsSpek.kt │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithOneOfThreeMovesRequiredSpek.kt │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithOnePegAlwaysInvolvedSpek.kt │ │ │ │ ├── TowersOfHanoiMinimumOperationsWithRelaxedConstraintSpek.kt │ │ │ │ ├── TowersOfHanoiSpek.kt │ │ │ │ ├── TowersOfHanoiWithPairsOfRingsOfEqualSizeSpek.kt │ │ │ │ ├── TowersOfHanoiWithoutRecursionSpek.kt │ │ │ │ └── testnamespace.kt │ │ ├── searching │ │ │ ├── ComputeIntegerSquareRootSpek.kt │ │ │ ├── ComputeRealSquareRootSpek.kt │ │ │ ├── DivideWithoutUsingDivisionOperatorSpek.kt │ │ │ ├── FindArrayEntryEqualToItsIndexSpek.kt │ │ │ ├── FindArrayEntryEqualToItsIndexWhenThereMayBeDuplicatesSpek.kt │ │ │ ├── FindElementInCyclicallySortedArraySpek.kt │ │ │ ├── FindFirstIndexOfElementGreaterThanKeySpek.kt │ │ │ ├── FindIntervalEnclosingIntegerSpek.kt │ │ │ ├── FindKthLargestElementSpek.kt │ │ │ ├── FindKthLargestElementWhenDuplicatesPresentSpek.kt │ │ │ ├── FindLocalMinimumSpek.kt │ │ │ ├── FindMaxInAscendingDescendingSequencesSpek.kt │ │ │ ├── FindMedianSpek.kt │ │ │ ├── FindMinMaxSimultaneouslySpek.kt │ │ │ ├── FindStringWithPrefixInArrayOfSortedStringsSpek.kt │ │ │ ├── Search2DSortedArraySpek.kt │ │ │ ├── SearchCyclicallySortedArraySpek.kt │ │ │ └── SearchSortedArrayForFirstOccurrenceSpek.kt │ │ ├── sorting │ │ │ ├── FastSortingAlgorithmForListsSpek.kt │ │ │ ├── IntersectionOfTwoSortedArraysSpek.kt │ │ │ ├── MergeSortedArraysSpek.kt │ │ │ ├── MergingIntervalsSpek.kt │ │ │ ├── PartitionAndSortArrayWithManyRepeatedEntriesSpek.kt │ │ │ ├── PeakBandwidthUsageSpek.kt │ │ │ ├── RemoveFirstNameDuplicatesSpek.kt │ │ │ ├── RenderACalendarSpek.kt │ │ │ ├── TeamPhotoDaySpek.kt │ │ │ └── UnionOfIntervalsSpek.kt │ │ ├── stacksandqueues │ │ │ ├── ComputeBinaryTreeLevelAveragesSpek.kt │ │ │ ├── ComputeBinaryTreeNodesInBottomUpLeftToRightOrderSpek.kt │ │ │ ├── ComputeBinaryTreeNodesInOrderOfIncreasingDepthSpek.kt │ │ │ ├── ComputeBinaryTreeNodesInTopDownAlternatingLeftToRightOrderSpek.kt │ │ │ ├── ComputeBuildingsWithSunsetViewWhenBuildingsPresentedEastToWestSpek.kt │ │ │ ├── ComputeBuildingsWithSunsetViewWhenBuildingsPresentedWestToEastSpek.kt │ │ │ ├── EvaluateRpnExpressionSpek.kt │ │ │ ├── EvaluateRpnExpressionWhenOperatorPrecedesOperandsSpek.kt │ │ │ ├── ImplementCircularQueueSpek.kt │ │ │ ├── ImplementQueueUsingStacksSpek.kt │ │ │ ├── ImplementQueueWithMaxAPISpek.kt │ │ │ ├── NormalizePathnamesSpek.kt │ │ │ ├── SearchPostingsListSpek.kt │ │ │ ├── StackWithMaxAPISpek.kt │ │ │ └── testnamespace.kt │ │ └── strings │ │ │ ├── BaseConversionSpek.kt │ │ │ ├── ComputeMnemonicsForPhoneNumberSpek.kt │ │ │ ├── ComputeSpreadsheetColumnEncodingSpek.kt │ │ │ ├── ComputeSpreadsheetColumnEncodingWhereAIsZeroSpek.kt │ │ │ ├── ComputeValidIPAddressesSpek.kt │ │ │ ├── ComputeValidIPAddressesWhenNumberOfPeriodsVariableAndStringLengthUnboundedSpek.kt │ │ │ ├── ConvertFromRomanToDecimalSpek.kt │ │ │ ├── InterconvertStringsAndIntegersSpek.kt │ │ │ ├── LookAndSayProblemSpek.kt │ │ │ ├── ReplaceAndRemoveSpek.kt │ │ │ ├── ReverseWordsInSentenceSpek.kt │ │ │ ├── ShortestValidRomanNumberSpek.kt │ │ │ ├── TelexEncodingSpek.kt │ │ │ ├── TestPalindromicitySpek.kt │ │ │ ├── TestStringForWellFormednessSpek.kt │ │ │ ├── VerifyRomanNumberIsValidSpek.kt │ │ │ └── WriteStringSinusoidallySpek.kt │ │ ├── kotlin │ │ └── common │ │ │ └── namespace.kt │ │ └── scratch │ │ └── .gitignore │ └── resources │ ├── expectedresults │ ├── CostCutting.txt │ └── DivisionOfNlogonia.txt │ └── tests │ ├── CostCutting.txt │ └── DivisionOfNLogonia.txt └── swift └── CodingPractice ├── CodingPractice.xcodeproj ├── project.pbxproj └── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── CodingPractice.xcworkspace ├── contents.xcworkspacedata └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── CodingPractice ├── AddDigits.swift ├── CodingPractice.h ├── ConstructTheRectangle.swift ├── EPBedBathAndBeyondProblem.swift ├── EPLengthOfLongestNondecreasingSubsequence.swift ├── EPLongestAlternatingSubsequence.swift ├── EPLongestBitonicSubsequence.swift ├── EPLongestConvexSubsequence.swift ├── EPLongestNondecreasingSubsequence.swift ├── EPLongestWeaklyAlternatingSubsequence.swift ├── EPMinimumPalindromicDecomposition.swift ├── EPMinimumWeightPathInTriangle.swift ├── EPNumberOfWaysToClimbStairs.swift ├── EPPickUpCoinsForMaximumGain.swift ├── EPPrettyPrinting.swift ├── EPPrettyPrintingExcludingLastLineMessiness.swift ├── Extensions.swift ├── FindDisappearedNumbers.swift ├── FirstUniqueCharacterInAString.swift ├── FlipGame.swift ├── Functions.swift ├── HammingDistance.swift ├── Info.plist ├── IntersectionOfTwoArrays.swift ├── IslandPerimeter.swift ├── MaxConsecutiveOnes.swift ├── MaxDepthOfBinaryTree.swift ├── MinimumMovesToEqualArrayElements.swift ├── NimGame.swift ├── NumberComplement.swift ├── Operators.swift ├── PaintHouse.swift ├── PalindromePermutation.swift ├── RelativeRanks.swift ├── SingleNumber.swift ├── SumOfTwoIntegers.swift └── Utils.swift ├── CodingPracticeTests ├── AddDigitsSpec.swift ├── ConstructTheRectangleSpec.swift ├── EPBedBathAndBeyondProblemSpec.swift ├── EPLengthOfLongestNondecreasingSubsequenceSpec.swift ├── EPLongestAlternatingSubsequenceSpec.swift ├── EPLongestBitonicSubsequenceSpec.swift ├── EPLongestConvexSubsequenceSpec.swift ├── EPLongestNondecreasingSubsequenceSpec.swift ├── EPLongestWeaklyAlternatingSubsequenceSpec.swift ├── EPMinimumPalindromicDecompositionSpec.swift ├── EPMinimumWeightPathInTriangleSpec.swift ├── EPNumberOfWaysToClimbStairsSpec.swift ├── EPPickUpCoinsForMaximumGainSpec.swift ├── EPPrettyPrintingExcludingLastLineMessinessSpec.swift ├── EPPrettyPrintingSpec.swift ├── FindDisappearedNumbersSpec.swift ├── FirstUniqueCharacterInAStringSpec.swift ├── FlipGameSpec.swift ├── HammingDistanceTests.swift ├── Info.plist ├── IntersectionOfTwoArraysSpec.swift ├── IslandPerimeterSpec.swift ├── MaxConsecutiveOnesSpec.swift ├── MaxDepthOfBinaryTreeSpec.swift ├── MinimumMovesToEqualArrayElementsSpec.swift ├── NimGameSpec.swift ├── NumberComplementSpec.swift ├── PaintHouseSpec.swift ├── PalindromePermutationSpec.swift ├── PickUpCoinsForMaximumGainSpec.swift ├── RelativeRanksSpec.swift ├── RelativeRanks_QuickSort_Spec.swift ├── Scratch.swift ├── SingleNumberSpec.swift ├── SumOfTwoIntegersSpec.swift └── TFunctions.swift └── Podfile /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -crlf -diff -merge -------------------------------------------------------------------------------- /java/.gitignore: -------------------------------------------------------------------------------- 1 | out/ 2 | -------------------------------------------------------------------------------- /java/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Dec 27 14:52:47 PST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip 7 | -------------------------------------------------------------------------------- /java/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'coding-practice' 2 | 3 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/coderust/BinarySearch.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.coderust 2 | 3 | // https://www.educative.io/collection/page/5642554087309312/5679846214598656/240002 4 | 5 | class BinarySearch { 6 | static Optional findIndexOf(List integers, int key) { 7 | int i = 0 8 | int j = integers.size() - 1 9 | while (i <= j) { 10 | int mid = (i + j) / 2 11 | int currentInteger = integers[mid] 12 | if (currentInteger > key) j = mid - 1 13 | else if (currentInteger < key) i = mid + 1 14 | else return Optional.of(mid) 15 | } 16 | return Optional.empty() 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/coderust/FindMaximumInSlidingWindow.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.coderust 2 | 3 | // https://www.educative.io/collection/page/5642554087309312/5679846214598656/210002 4 | 5 | class FindMaximumInSlidingWindow { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/common/GraphTrait.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | trait GraphTrait { 4 | 5 | int randomVertex(int vertexCount) { 6 | randomDataGenerator.nextInt(0, vertexCount - 1) 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/common/Heapable.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | interface Heapable> { 4 | T peek() 5 | T pop() 6 | void add(T comparable) 7 | void addAll(Iterable comparables) 8 | void update(T oldValue, T newValue) 9 | void remove(T value) 10 | int getSize() 11 | List asList() 12 | boolean isEmpty() 13 | } 14 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/common/PriorityQueue.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | import com.google.common.annotations.VisibleForTesting 4 | import com.lagostout.common.Heaps.HeapPropertyTester 5 | 6 | // https://www.hackerearth.com/practice/data-structures/trees/heapspriority-queues/tutorial/ 7 | 8 | class PriorityQueue> { 9 | 10 | Heap heap 11 | 12 | PriorityQueue(List items, 13 | HeapPropertyTester heapPropertyTester) { 14 | heap = new Heap<>(heapPropertyTester, items) 15 | } 16 | 17 | @VisibleForTesting 18 | PriorityQueue(Heap heap) { 19 | this.heap = heap 20 | } 21 | 22 | void insert(T value) { 23 | heap.add(value) 24 | } 25 | 26 | void update(T oldValue, T newValue) { 27 | heap.update(oldValue, newValue) 28 | } 29 | 30 | T peek() { 31 | heap.peek() 32 | } 33 | 34 | T pop() { 35 | heap.pop() 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/common/RawBinaryTreeNode.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | class RawBinaryTreeNode>{ 4 | Integer leftChildIndex = null 5 | Integer rightChildIndex = null 6 | Integer parentIndex = null 7 | T value 8 | 9 | RawBinaryTreeNode(Integer leftChildIndex, 10 | Integer rightChildIndex, 11 | Integer parentIndex, 12 | T value) { 13 | this.leftChildIndex = leftChildIndex 14 | this.rightChildIndex = rightChildIndex 15 | this.parentIndex = parentIndex 16 | this.value = value 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/common/Util.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | class Util { 4 | 5 | static File getFile(String file) { 6 | new File(Util.getClassLoader().getResource(file).getFile()) 7 | } 8 | 9 | static InputStream createStream(String file) { 10 | getFile(file).newInputStream() 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/common/ZeroBasedHeapIndexHelper.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | class ZeroBasedHeapIndexHelper { 4 | 5 | static int getParentIndex(int nodeIndex) { 6 | (nodeIndex - 1) / 2 7 | } 8 | 9 | static int getLeftChildIndex(int nodeIndex) { 10 | (nodeIndex * 2) + 1 11 | } 12 | 13 | static int getRightChildIndex(int nodeIndex) { 14 | getLeftChildIndex(nodeIndex) + 1 15 | } 16 | 17 | static T getRightChild(int parentIndex, List heap) { 18 | heap[getRightChildIndex(parentIndex)] 19 | } 20 | 21 | static T getLeftChild(int parentIndex, List heap) { 22 | heap[getLeftChildIndex(parentIndex)] 23 | } 24 | 25 | static T getParent(int childIndex, List heap) { 26 | heap[getParentIndex(childIndex)] 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/CountNumberOfUniquePlayPointSequencesThatResultInScore.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | /** 4 | * Problem 17.1.3 page 313 5 | */ 6 | class CountNumberOfUniquePlayPointSequencesThatResultInScore { 7 | 8 | static int sequenceCount(int score, List allPlayPoints) { 9 | List cache = [1] 10 | if (score == 0) return cache[0] 11 | 1.upto(score) { currentScore -> 12 | // println "currentScore $currentScore" 13 | int currentScoreSequenceCount = 0 14 | cache[currentScore] = currentScoreSequenceCount 15 | for (int playPoints in allPlayPoints) { 16 | int previousScore = currentScore - playPoints 17 | if (previousScore >= 0) { 18 | currentScoreSequenceCount += cache[previousScore] 19 | } 20 | } 21 | cache[currentScore] = currentScoreSequenceCount 22 | } 23 | cache[score] 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/elementsofprogramminginterviews/hashtables/ComputeLCA.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | import com.lagostout.common.BinaryTreeNode 4 | 5 | /** 6 | * Problem 13.4 p219 7 | */ 8 | class ComputeLCA { 9 | 10 | static BinaryTreeNode findLCA(BinaryTreeNode node1, BinaryTreeNode node2) { 11 | def visitedNodes = [] as Set 12 | def lowestCommonAncestor 13 | while (true) { 14 | if (node1) { 15 | if (visitedNodes.contains(node1)) { 16 | lowestCommonAncestor = node1 17 | break 18 | } 19 | visitedNodes.add(node1) 20 | node1 = node1.parent 21 | } 22 | if (node2) { 23 | if (visitedNodes.contains(node2)) { 24 | lowestCommonAncestor = node2 25 | break 26 | } 27 | visitedNodes.add(node2) 28 | node2 = node2.parent 29 | } 30 | } 31 | lowestCommonAncestor 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/elementsofprogramminginterviews/hashtables/ISBNCache.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | import com.google.common.annotations.VisibleForTesting 4 | 5 | class ISBNCache { 6 | 7 | @VisibleForTesting 8 | LinkedHashMap map 9 | 10 | ISBNCache(final int capacity) { 11 | map = new LinkedHashMap( 12 | capacity, 0.75F, true) { 13 | protected boolean removeEldestEntry(Map.Entry eldest) { 14 | return size() > capacity 15 | } 16 | } 17 | } 18 | 19 | void put(String isbn, int price) { 20 | if (map.get(isbn) == null) 21 | map.put(isbn, price) 22 | } 23 | 24 | void remove(String isbn) { 25 | map.remove(isbn) 26 | } 27 | 28 | Integer get(String isbn) { 29 | return map.get(isbn) 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/elementsofprogramminginterviews/hashtables/IsAnAnonymousLetterConstructible.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | class IsAnAnonymousLetterConstructible { 4 | 5 | static boolean isConstructible(String letter, String magazine) { 6 | def magazineCharToCount = new HashMap() 7 | for (char ch : magazine.chars) { 8 | def count = (magazineCharToCount.containsKey(ch) ? 9 | magazineCharToCount.get(ch) : 0) + 1 10 | magazineCharToCount.put(ch, count) 11 | } 12 | def isConstructible = true 13 | for (char ch : letter.chars) { 14 | if (!magazineCharToCount.containsKey(ch) || 15 | magazineCharToCount.get(ch) == 0) { 16 | isConstructible = false 17 | break 18 | } 19 | def count = magazineCharToCount.get(ch) - 1 20 | magazineCharToCount.put(ch, count) 21 | } 22 | isConstructible 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/elementsofprogramminginterviews/hashtables/TestForPalindromicPermutations.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | class TestForPalindromicPermutations { 4 | 5 | static boolean canBePermutedToFormPalindrome(String str) { 6 | def canBePermuted = true 7 | def charToCharCount = new HashMap() 8 | str.chars.each { char ch -> 9 | def count = charToCharCount.getOrDefault(ch, 0) + 1 10 | charToCharCount.put(ch, count) 11 | } 12 | def numberOfCharWithOddCount = charToCharCount.values() 13 | .count { it % 2 == 1 } 14 | if (numberOfCharWithOddCount > 1) 15 | canBePermuted = false 16 | canBePermuted 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P10_NSum.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P10_NSum { 4 | 5 | static public int nSum(int n) { 6 | if (n == 1) return 1 7 | n + nSum(n-1) 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P11_SumSquares.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P11_SumSquares { 4 | 5 | static public int sumSquares(int n) { 6 | if (n == 1) return 1 7 | n * n + sumSquares(n-1) 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P12_InvNSum.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P12_InvNSum { 4 | static public double invNSum(int n) { 5 | if (n == 1) return 1 6 | 1D / n + invNSum(n-1) 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P1_PrintHello.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P1_PrintHello { 4 | 5 | static String printHello(int n) { 6 | if (n == 1) return "Hello_${n}_" 7 | return printHello(n-1) + "Hello_${n}_" 8 | } 9 | 10 | static String printHello_moreRecursion(int n) { 11 | if (n == 0) return "" 12 | return printHello_moreRecursion(n-1) + "Hello_${n}_" 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P20_PrintReverse.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P20_PrintReverse { 4 | 5 | static public void printReverse(int n) { 6 | if (n < 9) println n 7 | } 8 | 9 | static public void printReverse(int n, int m) { 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P21_IsPalindrome.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P21_IsPalindrome { 4 | 5 | static public boolean isPalindrome(int n, int length) { 6 | println "" 7 | if (length <= 1) return true 8 | int first = n / Math.pow(10, length - 1) 9 | int last = n % 10 10 | int middle = (n % Math.pow(10, length - 1)) / 10 11 | return first == last && isPalindrome(middle, length - 2) 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P22_Binomial.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P22_Binomial { 4 | static public int binomial(int n, int k) { 5 | if (k == 0 || n == k) return 1 6 | return binomial(n - 1, k - 1) + binomial(n - 1, k) 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P23_Convert.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P23_Convert { 4 | static String convert(int n) { 5 | if (n < 2) 6 | n 7 | else 8 | convert(n.intdiv(2) as int) + (n % 2) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P24_ConvertNB.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P24_ConvertNB { 4 | static String convert(int n, int b) { 5 | if (n < b) n 6 | else convert(n.intdiv(b) as int, b) + (n % b) 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P27_PrintALogNTimes.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P27_PrintALogNTimes { 4 | 5 | static String printALogNTimes(int n) { 6 | if (n < 2) return '' 7 | return 'A' + printALogNTimes(n.intdiv(2) as int) 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P28_PrintCommas.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P28_PrintCommas { 4 | static String printCommas(long n) { 5 | if (n < 1000) n 6 | else { 7 | long nextN = n / 1000 as long 8 | String result = printCommas(nextN) + 9 | (nextN > 0 ? ',' : '') 10 | int end = (n % 1000) 11 | if (end < 100) result += '0' 12 | if (end < 10) result += '0' 13 | result + end 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P29_PrintAExpTimes.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P29_PrintAExpTimes { 4 | static String printAExpTimes(int n) { 5 | if (n == 0) return 'A' 6 | return printAExpTimes(n-1) + printAExpTimes(n-1) 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P2_Print1ToN.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P2_Print1ToN { 4 | 5 | static List print1ToN(int n) { 6 | if (n == 1) return [1] 7 | return print1ToN(n-1) + [n] 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P33_PrintAFactorialTimes.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P33_PrintAFactorialTimes { 4 | static String printAFactorialTimes(int n) { 5 | if (n == 1) return 'A' 6 | String result = '' 7 | for (int i = 0; i < n; i++) { 8 | result += printAFactorialTimes(n-1) 9 | } 10 | result 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P3_PrintNDownTo1.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P3_PrintNDownTo1 { 4 | 5 | static List printNDownTo1(int n) { 6 | if (n == 1) return [n] 7 | return [n] + printNDownTo1(n-1) 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P4_Power.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P4_Power { 4 | 5 | static double power1(double base, int exponent) { 6 | if (exponent == 0) return 1 7 | return base * power1(base, exponent - 1) 8 | } 9 | 10 | static double power2(double base, int exponent) { 11 | if (exponent == 0) return 1 12 | else { 13 | double result = power2(base, exponent >> 1) * power2(base, exponent >> 1) 14 | if (exponent & 1) { 15 | return base * result 16 | } else { 17 | return result 18 | } 19 | } 20 | } 21 | 22 | static double power3(double base, int exponent) { 23 | if (exponent == 0) return 1 24 | else { 25 | double result = power2(base, exponent >> 1) 26 | result *= result 27 | if (exponent & 1) { 28 | return base * result 29 | } else { 30 | return result 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P7_NumberOfDigits.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P7_NumberOfDigits { 4 | 5 | static int numberOfDigits(int n) { 6 | if (n <= 9) return 1 7 | numberOfDigits(n.intdiv(10).intValue()) + 1 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P8_NContainsK.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P8_NContainsK { 4 | 5 | static boolean nContainsK(int n, int k) { 6 | if (n < 10) return n == k 7 | return (n % 10) == k || nContainsK(n.intdiv(10).intValue(), k) 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/P9_GCD.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | class P9_GCD { 4 | 5 | static public int gcd(int m, int n) { 6 | if (m % n == 0) return n; 7 | return gcd(n, m % n) 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/P18_SelectionSort.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | class P18_SelectionSort { 4 | 5 | static void selectionSort(int[] a, int n) { 6 | if (n <= 1) return 7 | int maxIndex = n-1 8 | for (int i = 0; i < n-1; i++) { 9 | if (a[i] > a[maxIndex]) maxIndex = i 10 | } 11 | if (maxIndex != n-1) { 12 | int temp = a[n-1] 13 | a[n-1] = a[maxIndex] 14 | a[maxIndex] = temp 15 | } 16 | selectionSort(a, n-1) 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/P19_InsertionSort.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | class P19_InsertionSort { 4 | static void insertionSort(int[] a, int n) { 5 | if (n <= 1) return 6 | insertionSort(a, n-1) 7 | int i = n-1 8 | int temp = a[i] 9 | while (i > 0 && a[i-1] > temp) { 10 | a[i] = a[i-1] 11 | i-- 12 | } 13 | if (i != n-1) 14 | a[i] = temp 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/P1_PrintArray.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | class P1_PrintArray { 4 | static String printArray(int[] a, int n) { 5 | if (n == 1) return a[0] 6 | return printArray(a, n-1) + ' ' + a[n-1] 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/P20_BubbleSort.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | class P20_BubbleSort { 4 | static void bubbleSort(int[] a, int n) { 5 | if (n == 1) return 6 | for (int i = 1; i < n; i++) { 7 | if (a[i] < a[i-1]) { 8 | int temp = a[i] 9 | a[i] = a[i-1] 10 | a[i-1] = temp 11 | } 12 | } 13 | bubbleSort(a, n-1) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/src/main/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/P22_BinarySearch.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | class P22_BinarySearch { 4 | static int _binarySearch(int[] a, int key, int left, int right) { 5 | if (left > right) return right 6 | int mid = (left + right)/2 7 | if (a[mid] == key) return mid 8 | else if (a[mid] < key) return binarySearch(a, key, mid+1, right) 9 | else return binarySearch(a, key, left, mid-1) 10 | } 11 | 12 | static int binarySearch(int[] a, int key, int left, int right) { 13 | if (left > right) return right 14 | int mid = (left + right)/2 15 | if (a[mid] == key) return mid 16 | else if (a[mid] > key) return binarySearch(a, key, left, mid-1) 17 | else return binarySearch(a, key, mid+1, right) 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /java/src/main/java/com/lagostout/competitiveprogramming3/datastructuresandlibraries/JollyJumpers.java: -------------------------------------------------------------------------------- 1 | package com.lagostout.competitiveprogramming3.datastructuresandlibraries; 2 | 3 | public class JollyJumpers { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /java/src/main/java/com/lagostout/competitiveprogramming3/introduction/RelationalOperator.java: -------------------------------------------------------------------------------- 1 | package com.lagostout.competitiveprogramming3.introduction; 2 | 3 | import java.util.Scanner; 4 | 5 | class RelationalOperator { 6 | 7 | public static void main(String[] args) { 8 | RelationalOperator ro = new RelationalOperator(); 9 | ro.run(); 10 | } 11 | 12 | private void run() { 13 | Scanner scanner = new Scanner(System.in); 14 | int inputSetsCount = scanner.nextInt(); 15 | char[] ops = new char[inputSetsCount]; 16 | for (int i = 0; i < inputSetsCount; i++) { 17 | long a = scanner.nextLong(); 18 | long b = scanner.nextLong(); 19 | char op; 20 | if (a == b) op = '='; 21 | else if (a < b) op = '<'; 22 | else op = '>'; 23 | ops[i] = op; 24 | } 25 | for (char op : ops) { 26 | System.out.println(op); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /java/src/main/java/com/lagostout/competitiveprogramming3/introduction/RequestForProposal.java: -------------------------------------------------------------------------------- 1 | package com.lagostout.competitiveprogramming3.introduction; 2 | 3 | public class RequestForProposal { 4 | } 5 | -------------------------------------------------------------------------------- /java/src/main/java/com/lagostout/interviewbit/dynamicprogramming/simplearraydp/LengthOfLongestSubsequence.java: -------------------------------------------------------------------------------- 1 | package com.lagostout.interviewbit.dynamicprogramming.simplearraydp; 2 | 3 | public class LengthOfLongestSubsequence { 4 | 5 | public static int compute(int[] arg) { 6 | // int lengthOfLongestDescendingSubsequence = 7 | return 0; 8 | } 9 | 10 | private static int computeLengthOfLongestDescendingSubsequence(int foo) { 11 | return 0; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /java/src/main/java/com/lagostout/leetcode/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | package com.lagostout.leetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | @SuppressWarnings("Duplicates") 7 | public class FizzBuzz { 8 | 9 | public static List fizzBuzz(int n) { 10 | List result = new ArrayList(); 11 | for (int i = 1; i <= n; i++) { 12 | String s = Integer.toString(i); 13 | if (i % 15 == 0) s = "FizzBuzz"; 14 | else if (i % 3 == 0) s = "Fizz"; 15 | else if (i % 5 == 0) s = "Buzz"; 16 | result.add(s); 17 | } 18 | return result; 19 | } 20 | 21 | public static List fizzBuzzFaster(int n) { 22 | List result = new ArrayList(); 23 | for (int i = 1; i <= n; i++) { 24 | String s; 25 | if (i % 15 == 0) s = "FizzBuzz"; 26 | else if (i % 3 == 0) s = "Fizz"; 27 | else if (i % 5 == 0) s = "Buzz"; 28 | else s = Integer.toString(i); 29 | result.add(s); 30 | } 31 | return result; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /java/src/main/java/com/lagostout/leetcode/MovingAverage.java: -------------------------------------------------------------------------------- 1 | package com.lagostout.leetcode; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | 6 | public class MovingAverage { 7 | 8 | private final int maxWindowSize; 9 | private Deque deque = new ArrayDeque<>(); 10 | private int sum; 11 | 12 | public MovingAverage(int size) { 13 | this.maxWindowSize = size; 14 | } 15 | 16 | public double next(int val) { 17 | int first = 0; 18 | if (deque.size() >= maxWindowSize) { 19 | first = deque.removeFirst(); 20 | } 21 | deque.addLast(val); 22 | sum = (sum - first) + val; 23 | return sum/(double) deque.size(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/bytebybyte/dynamicprogramming/LongestIncreasingSubsequence.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.dynamicprogramming 2 | 3 | object LongestIncreasingSubsequence { 4 | 5 | fun computeWithBruteForceAndRecursion( 6 | integers: List, index: Int = 0, 7 | min: Int? = null): Int { 8 | return if (index > integers.lastIndex) 0 9 | else { 10 | // If we're at index = 0, include the value in the 11 | // subsequence. Otherwise, only include the value 12 | // if it's greater than the min. 13 | mutableListOf().apply { 14 | if (min == null || integers[index] > min) { 15 | add(computeWithBruteForceAndRecursion( 16 | integers, index + 1, integers[index]) + 1) 17 | } 18 | // Maintain the existing min. 19 | add(computeWithBruteForceAndRecursion( 20 | integers, index + 1, min)) 21 | }.max()!! 22 | } 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/bytebybyte/recursion/FindAllPossibleArraysThatCouldResultInBinaryTree.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.recursion 2 | 3 | import com.lagostout.datastructures.BinaryTreeNode 4 | 5 | fun findAllPossibleArraysThatCouldResultInBinaryTree( 6 | root: BinaryTreeNode?): List> { 7 | if (root == null) return listOf(emptyList()) 8 | val possibleArraysOfLeftSubtree = 9 | findAllPossibleArraysThatCouldResultInBinaryTree(root.left) 10 | val possibleArraysOfRightSubtree = 11 | findAllPossibleArraysThatCouldResultInBinaryTree(root.right) 12 | return possibleArraysOfLeftSubtree.flatMap { leftArray -> 13 | possibleArraysOfRightSubtree.flatMap { rightArray -> 14 | listOf(leftArray + rightArray, rightArray + leftArray).toSet().map { 15 | listOf(root.value) + it 16 | } 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/bytebybyte/recursion/FindAllSubstringsOfString.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.recursion 2 | 3 | fun findAllSubstringsOfString(s: String): List { 4 | return findAllSubstringsOfString(s, 0, 1) 5 | } 6 | 7 | private fun findAllSubstringsOfString(s: String, startIndex: Int, endIndex: Int): List { 8 | return when { 9 | startIndex > s.lastIndex -> return emptyList() 10 | endIndex > s.length -> findAllSubstringsOfString(s, startIndex + 1, startIndex + 2) 11 | else -> listOf(s.substring(startIndex, endIndex)) + 12 | findAllSubstringsOfString(s, startIndex, endIndex + 1) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/bytebybyte/recursion/KnapsackProblemUsingDFS.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.recursion 2 | 3 | data class Item(val value: Int, val weight: Int) 4 | 5 | /* We'll assume that no items are duplicates. */ 6 | 7 | fun knapsack(items: List, maxWeight: Int): Int { 8 | data class State(val value: Int, val weight: Int, 9 | val remainingItems: Set) { 10 | fun nextStates(): Set { 11 | return remainingItems.map { 12 | State(value + it.value, weight + it.weight, 13 | remainingItems.minus(it)) 14 | }.toSet() 15 | } 16 | } 17 | fun compute(state: State, maxValue: Int): Int { 18 | if (state.weight > maxWeight) return maxValue 19 | else if (state.weight == maxWeight) 20 | return maxOf(state.value, maxValue) 21 | var result = maxOf(state.value, maxValue) 22 | state.nextStates().forEach { 23 | result = compute(it, result) 24 | } 25 | return result 26 | } 27 | return compute(State(0, 0, items.toSet()), 0) 28 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/bytebybyte/recursion/LowestCommonAncestor.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.recursion 2 | 3 | data class Node(val value: Int, var left: Node? = null, var right: Node? = null) 4 | 5 | /* We'll assume the two descendant nodes are always in the tree. 6 | From that, it follows that there'll always be at least one node in 7 | the tree. We'll allow the possibility that the descendant nodes 8 | may actually be two pointers to the same node instance. */ 9 | 10 | fun lowestCommonAncestor(root: Node, n1: Node, n2: Node): Node { 11 | fun compute(root: Node?, nodesToSearchFor: MutableList): Node? { 12 | if (root == null || nodesToSearchFor.isEmpty()) return null 13 | val countOfNodesToSearchFor = nodesToSearchFor.size 14 | nodesToSearchFor.removeAll(listOf(root)) 15 | val commonAncestorByGoingLeftOrRight = 16 | listOfNotNull(compute(root.left, nodesToSearchFor), 17 | compute(root.right, nodesToSearchFor)).firstOrNull() 18 | return commonAncestorByGoingLeftOrRight ?: (if (countOfNodesToSearchFor == 2 19 | && nodesToSearchFor.isEmpty()) root else null) 20 | } 21 | return compute(root, mutableListOf(n1, n2))!! 22 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/bytebybyte/recursion/Permutations.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.recursion 2 | 3 | fun permutations(numbers: List): List> { 4 | data class State(val value: Int?, val availableNumbers: List) { 5 | fun nextStates(): List { 6 | return availableNumbers.map { 7 | State(it, availableNumbers - it) 8 | } 9 | } 10 | } 11 | fun compute(state: State): List> { 12 | return if (state.nextStates().isEmpty()) 13 | listOf(listOfNotNull(state.value)) 14 | else state.nextStates().flatMap { nextState -> 15 | compute(nextState).map { 16 | listOfNotNull(state.value) + it 17 | } 18 | } 19 | } 20 | return compute(State(null, numbers)) 21 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/bytebybyte/recursion/PrintOddIndicesOfIntegerArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.recursion 2 | 3 | fun printOddIndicesOfIntegerArray(array: Array): List { 4 | return printOddIndicesOfIntegerArray(array, 1) 5 | } 6 | 7 | private fun printOddIndicesOfIntegerArray( 8 | array: Array, index: Int): List { 9 | if (index > array.lastIndex) return emptyList() 10 | println(array[index]) 11 | return listOf(array[index]) + printOddIndicesOfIntegerArray(array, index + 2) 12 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/datastructures/RawBinaryTreeNode.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.datastructures 2 | 3 | // This is only used in Kotlin, and should stay that way. 4 | data class RawBinaryTreeNode>(val leftChildIndex: Int? = null, 5 | val rightChildIndex: Int? = null, 6 | val parentIndex: Int? = null, 7 | val value: T) { 8 | companion object { 9 | fun > rbt(left: Int? = null, right: Int? = null, 10 | parent: Int? = null, value: T): RawBinaryTreeNode = 11 | RawBinaryTreeNode(left, right, parent, value) 12 | 13 | fun > rbt(value: T, left: Int? = null, right: Int? = null, 14 | parent: Int? = null): RawBinaryTreeNode = 15 | RawBinaryTreeNode(left, right, parent, value) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/AdvancingThroughArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /** 4 | * Problem 6.4.1 page 68 5 | */ 6 | fun advancingToEndOfArrayIsPossible(array: List): Boolean { 7 | var destinationIndex = array.lastIndex 8 | var destinationIndexIsReachable = true 9 | var finishedTraversingArray = false 10 | while (!finishedTraversingArray) { 11 | var currentIndex = destinationIndex - 1 12 | while (true) { 13 | if (currentIndex < 0) { 14 | finishedTraversingArray = true 15 | break 16 | } 17 | destinationIndexIsReachable = false 18 | if (currentIndex + 19 | array[currentIndex] >= destinationIndex) { 20 | destinationIndexIsReachable = true 21 | destinationIndex = currentIndex 22 | break 23 | } 24 | --currentIndex 25 | } 26 | } 27 | return destinationIndexIsReachable 28 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/DeleteDuplicatesFromArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /** 4 | * Problem 6.5.1 page 69 5 | */ 6 | fun deleteDuplicatesFromArray(array: IntArray): Int { 7 | if (array.isEmpty()) return 0 8 | var pointer1 = 0 9 | var pointer2: Int = pointer1 10 | var pointer1Number = array[pointer1] 11 | var nextNumber: Int = pointer1Number 12 | while (true) { 13 | // Find next number 14 | while (pointer2 < array.lastIndex) { 15 | nextNumber = array[++pointer2] 16 | array[pointer2] = 0 17 | if (nextNumber != pointer1Number) break 18 | } 19 | // We didn't advance pointer2 20 | if (array[pointer1] == nextNumber) break 21 | // Otherwise, advance pointer1 22 | array[++pointer1] = nextNumber 23 | pointer1Number = nextNumber 24 | } 25 | return pointer1 + 1 26 | } 27 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/DeleteOccurrencesOfKey.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | fun > deleteOccurrencesOfKey(key: T, array: Array): Int { 4 | var writeIndex = 0 5 | var readIndex = writeIndex 6 | while(readIndex <= array.lastIndex) { 7 | if (array[readIndex] != key) { 8 | array[writeIndex++] = array[readIndex] 9 | } 10 | ++readIndex 11 | } 12 | return writeIndex 13 | } 14 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/DutchNationalFlag.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /** 4 | * Problem 6.1.1 page 62 5 | */ 6 | fun arrangeAsDutchNationalFlag(array: MutableList, pivotIndex: Int) { 7 | if (array.isEmpty() || array.size == 1) return 8 | if (pivotIndex > array.lastIndex || pivotIndex < 0) 9 | throw IllegalArgumentException( 10 | "Argument pivotIndex must be > 0 and <= array last index") 11 | fun swap(array: MutableList, index1: Int, index2: Int) { 12 | val temp = array[index1] 13 | array[index1] = array[index2] 14 | array[index2] = temp 15 | } 16 | val pivotValue = array[pivotIndex] 17 | swap(array, 0, pivotIndex) 18 | var boundaryIndex = 0 19 | (1 until array.size).forEach { currentIndex -> 20 | if (array[currentIndex] < pivotValue) { 21 | swap(array, currentIndex, boundaryIndex++) 22 | } 23 | } 24 | (boundaryIndex until array.size).forEach { 25 | currentIndex -> 26 | if (array[currentIndex] == pivotValue) { 27 | swap(array, currentIndex, boundaryIndex++) 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/DutchNationalFlagPreservingRelativeOrdering.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /** 4 | * Problem 6.1.5 page 65 5 | */ 6 | object DutchNationalFlagPreservingRelativeOrdering { 7 | 8 | data class Element(val order: Int, val value: Boolean) 9 | 10 | fun arrangeAsDutchNationalFlag(array: MutableList) { 11 | var lastFalseIndex = array.lastIndex 12 | var lastTrueIndex = array.lastIndex 13 | while (lastTrueIndex >= 0 && lastFalseIndex >= 0) { 14 | if (array[lastFalseIndex].value) 15 | --lastFalseIndex 16 | else if (!array[lastTrueIndex].value || 17 | lastTrueIndex > lastFalseIndex) 18 | --lastTrueIndex 19 | else { 20 | val trueElement = array[lastTrueIndex] 21 | array[lastTrueIndex] = array[lastFalseIndex] 22 | array[lastFalseIndex] = trueElement 23 | } 24 | } 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/DutchNationalFlagWith3KeyValues.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /** 4 | * Problem 6.1.2 page 65 5 | */ 6 | fun arrangeAsDutchNationalFlag(array: MutableList) { 7 | if (array.isEmpty() || array.size == 1) return 8 | var key = array[0] 9 | fun swap(array: MutableList, index1: Int, index2: Int) { 10 | val temp = array[index1] 11 | array[index1] = array[index2] 12 | array[index2] = temp 13 | } 14 | var boundaryIndex = 1 15 | (1 until array.size).forEach { currentIndex -> 16 | if (array[currentIndex] == key) { 17 | swap(array, currentIndex, boundaryIndex++) 18 | } 19 | } 20 | if (boundaryIndex == array.size) return 21 | key = array[boundaryIndex++] 22 | (boundaryIndex until array.size).forEach { 23 | currentIndex -> 24 | if (array[currentIndex] == key) { 25 | swap(array, currentIndex, boundaryIndex++) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/DutchNationalFlagWith4KeyValues.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | object DutchNationalFlagWith4KeyValues { 4 | 5 | fun arrangeAsDutchNationalFlag(array: MutableList) { 6 | if (array.isEmpty() || array.size == 1) return 7 | fun swap(array: MutableList, index1: Int, index2: Int) { 8 | val temp = array[index1] 9 | array[index1] = array[index2] 10 | array[index2] = temp 11 | } 12 | var boundaryIndex = 0 13 | while (boundaryIndex < array.size) { 14 | val key = array[boundaryIndex] 15 | (boundaryIndex..array.lastIndex).forEach { currentIndex -> 16 | if (array[currentIndex] == key) { 17 | swap(array, currentIndex, boundaryIndex++) 18 | } 19 | } 20 | } 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/DutchNationalFlagWithBooleanValues.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /** 4 | * Problem 6.1.4 page 65 5 | */ 6 | @Suppress("NAME_SHADOWING") 7 | fun arrangeAsDutchNationalFlag(array: MutableList) { 8 | var firstTrueIndex = 0 9 | var currentIndex = 0 10 | fun swap (fromIndex: Int, toIndex: Int) { 11 | val temp = array[fromIndex] 12 | array[fromIndex] = array[toIndex] 13 | array[toIndex] = temp 14 | } 15 | while (currentIndex < array.size) { 16 | if (!array[currentIndex]) { 17 | while (!array[firstTrueIndex] && 18 | firstTrueIndex < currentIndex) { 19 | firstTrueIndex++ 20 | } 21 | swap(currentIndex, firstTrueIndex) 22 | } 23 | currentIndex++ 24 | } 25 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/IncrementArbitraryPrecisionInteger.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | fun incrementInteger(list: MutableList) { 4 | var index = list.lastIndex 5 | var done = false 6 | while (index >= 0 && !done) { 7 | val sum = list[index] + 1 8 | list[index] = sum % 10 9 | done = sum == list[index] 10 | --index 11 | } 12 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/LengthOfLongestSubarrayOfEqualEntries.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /* Problem 6.6.2 page 71 */ 4 | 5 | fun lengthOfLongestSubarrayOfEqualEntries(array: List): Int { 6 | if (array.count() <= 1) return array.count() 7 | var longestSubarrayCount = 1 8 | var currentSubarrayCount = 1 9 | (1 until array.count()).forEach { index -> 10 | val currentNumber = array[index] 11 | val previousNumber = array[index - 1] 12 | if (currentNumber == previousNumber) { 13 | currentSubarrayCount += 1 14 | if (currentSubarrayCount > longestSubarrayCount) { 15 | longestSubarrayCount = currentSubarrayCount 16 | } 17 | } else { 18 | currentSubarrayCount = 1 19 | } 20 | } 21 | return longestSubarrayCount 22 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/LimitDuplicatesInSortedArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /* Problem 6.5.3 page 70 */ 4 | 5 | fun limitDuplicatesInSortedArray(array: Array, m: Int) { 6 | var writeIndex: Int? = null 7 | var readIndex = 0 8 | var duplicateCount = 0 9 | var currentReadEntry = array[readIndex] 10 | while (true) { 11 | if (readIndex <= array.lastIndex && 12 | array[readIndex] == currentReadEntry) { 13 | ++duplicateCount 14 | array[readIndex++] = null 15 | } else { 16 | val copyCount = if (duplicateCount == m) 17 | minOf(2, duplicateCount) else duplicateCount 18 | (1..copyCount).forEach { 19 | writeIndex = (writeIndex?.inc() ?: 0).also { 20 | array[it] = currentReadEntry 21 | } 22 | } 23 | if (readIndex >= array.size) break 24 | currentReadEntry = array[readIndex] 25 | duplicateCount = 0 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/PermuteElementsOfArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /* Problem 6.9.1 page 74 */ 4 | 5 | fun permuteElementsOfArray(array: MutableList, permutation: MutableList) { 6 | var safeLastPermutedIndex = 0 7 | var element: T 8 | while (safeLastPermutedIndex < permutation.size) { 9 | while (permutation[safeLastPermutedIndex] != safeLastPermutedIndex) { 10 | val permutedIndex = permutation[safeLastPermutedIndex] 11 | // Swap elements 12 | element = array[safeLastPermutedIndex]!! 13 | val tempElement = array[permutedIndex] 14 | array[permutedIndex] = element 15 | array[safeLastPermutedIndex] = tempElement 16 | // Swap permutations 17 | val tempPermutedIndex = permutation[permutedIndex] 18 | permutation[permutedIndex] = permutedIndex 19 | permutation[safeLastPermutedIndex] = tempPermutedIndex 20 | } 21 | safeLastPermutedIndex += 1 22 | } 23 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/PrimesToN.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /* Problem 6.8 page 72 */ 4 | 5 | fun primesToN(n: Int): List { 6 | val candidates = MutableList(n + 1) { true } 7 | return candidates.run { 8 | indices.drop(2).run { 9 | forEach { 10 | if (candidates[it]) { 11 | var index = it * it 12 | while (index <= n) { 13 | candidates[index] = false 14 | index += it 15 | } 16 | } 17 | } 18 | filter { candidates[it] } 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/SampleOfflineData.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | import com.lagostout.common.swap 4 | import org.apache.commons.math3.random.RandomDataGenerator 5 | 6 | /* Problem 6.11.1 page 78 */ 7 | 8 | fun sampleOfflineData(list: MutableList, n: Int) { 9 | var leftIndex = 0 10 | while (leftIndex < n) { 11 | val selectedIndex = RandomDataGenerator() 12 | .nextInt(leftIndex, list.lastIndex) 13 | list.swap(leftIndex, selectedIndex) 14 | leftIndex += 1 15 | } 16 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/SumOfIntegersEncodedAsBinaryNumbers.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | /** 4 | * Problem 6.2.2 page 66 5 | */ 6 | fun sumOfIntegersEncodedAsBinaryNumbers(firstInt: String, secondInt: String): String { 7 | var indexOffset = 0 8 | var excess = 0 9 | val stringBuilder = StringBuilder() 10 | run { 11 | while (true) { 12 | (listOf(firstInt, secondInt).map { 13 | Pair(it, it.lastIndex - indexOffset) 14 | }.also { 15 | if (it.all { it.second < 0 }) { 16 | if (excess == 1) stringBuilder.append(1) 17 | return@run 18 | } 19 | }.map { (integer, index) -> 20 | if (index < 0 || integer[index] != '1') 0 21 | else 1 22 | }.sum() + excess).let { 23 | excess = if (it > 1) 1 else 0 24 | stringBuilder.append(it % 2) 25 | } 26 | ++indexOffset 27 | } 28 | } 29 | return stringBuilder.reverse().toString() 30 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/binarysearchtrees/FindFirstInorderOccurrenceInBST.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.binarysearchtrees 2 | 3 | import com.lagostout.datastructures.BinaryTreeNode 4 | 5 | /** 6 | * Problem 15.2.2 page 264 7 | */ 8 | fun > findFirstInorderOccurrence( 9 | root: BinaryTreeNode, k: T): BinaryTreeNode? { 10 | var firstOccurrence: BinaryTreeNode? = null 11 | var currentNode: BinaryTreeNode? = root 12 | while (currentNode != null) { 13 | currentNode = currentNode.run { 14 | when { 15 | value >= k -> { 16 | if (value == k) 17 | firstOccurrence = currentNode 18 | left 19 | } 20 | else -> right 21 | } 22 | } 23 | } 24 | return firstOccurrence 25 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/binarytrees/ComputeRightSiblingTree.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.binarytrees 2 | 3 | import com.lagostout.datastructures.BinaryTreeNode 4 | 5 | /* Problem 10.16.1 page 172 */ 6 | 7 | fun computeRightSiblingTree(root: BinaryTreeNode) { 8 | var node = root 9 | var levelNextPreviousNode: BinaryTreeNode? = null 10 | var leftmostNodeOnLevel = node.left 11 | while (true) { 12 | node.left ?: break 13 | levelNextPreviousNode?.let { 14 | it.levelNext = node.left 15 | } 16 | node.left!!.levelNext = node.right 17 | levelNextPreviousNode = node.right 18 | node = node.levelNext ?: leftmostNodeOnLevel?.also { 19 | levelNextPreviousNode = null 20 | leftmostNodeOnLevel = it.left 21 | } ?: break 22 | } 23 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/binarytrees/ComputeRightSiblingTreeUsingRightChildField.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.binarytrees 2 | 3 | import com.lagostout.datastructures.BinaryTreeNode 4 | 5 | /* Problem 10.16.2 page 173 */ 6 | 7 | fun computeRightSiblingTreeUsingRightChildField(root: BinaryTreeNode) { 8 | 9 | fun setLeftChildLevelNext(node: BinaryTreeNode) { 10 | if (node.isALeaf) return 11 | setLeftChildLevelNext(node.left!!) 12 | node.left?.right = node.right 13 | if (node.hasRight) 14 | setLeftChildLevelNext(node.right!!) 15 | node.right = null 16 | } 17 | 18 | fun connectLevels(node: BinaryTreeNode) { 19 | if (!node.hasLeft) return 20 | var levelNode: BinaryTreeNode? = node 21 | while (levelNode != null) { 22 | levelNode.left?.right?.right = levelNode.right?.left 23 | levelNode = levelNode.right 24 | } 25 | connectLevels(node.left!!) 26 | } 27 | 28 | if (root.isALeaf) return 29 | setLeftChildLevelNext(root) 30 | connectLevels(root.left!!) 31 | 32 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/binarytrees/KthNodeInInOrderTraversal.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.binarytrees 2 | 3 | import com.lagostout.datastructures.BinaryTreeNode 4 | 5 | /** 6 | * Problem 10.9 page 163 7 | */ 8 | fun kthNodeInInOrderTraversal( 9 | k: Int, root: BinaryTreeNode?): 10 | BinaryTreeNode? { 11 | var currentNode = root 12 | // So we can compare positions (0-based) and counts (1-based) 13 | var relativeK = k + 1 14 | var currentNodePosition: Int 15 | while (currentNode != null) { 16 | currentNodePosition = (currentNode.left?.value ?: 0) + 1 17 | if (relativeK == currentNodePosition) { 18 | break 19 | } else if (relativeK < currentNodePosition) { 20 | currentNode = currentNode.left 21 | } else if (relativeK > currentNodePosition) { 22 | relativeK -= currentNodePosition 23 | currentNode = currentNode.right 24 | } 25 | } 26 | return currentNode 27 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/ComputeLevenshteinDistance.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | /** 4 | * Problem 17.2 page 315 5 | */ 6 | fun levenshteinDistance(from: String, to: String): Int = 7 | levenshteinDistanceCache(from, to).last().last() 8 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/DetermineIfStringIsAnInterleaving.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | import org.apache.commons.collections4.iterators.PeekingIterator 4 | 5 | /** 6 | * Problem 17.2.6 page 316 7 | */ 8 | fun determineIfStringIsAnInterleavingOfTwoStrings( 9 | string: String, first: String, second: String): Boolean { 10 | val stringIterator = string.reversed().iterator() 11 | val firstIterator = PeekingIterator(first.reversed().iterator()) 12 | val secondIterator = PeekingIterator(second.reversed().iterator()) 13 | var isNotInterleaving = false 14 | while (!isNotInterleaving && stringIterator.hasNext()) { 15 | val stringChar = stringIterator.next() 16 | when (stringChar) { 17 | firstIterator.peek() -> { 18 | firstIterator.next() 19 | } 20 | secondIterator.peek() -> { 21 | secondIterator.next() 22 | } 23 | else -> { 24 | isNotInterleaving = true 25 | } 26 | } 27 | } 28 | return !isNotInterleaving && 29 | !firstIterator.hasNext() && 30 | !secondIterator.hasNext() 31 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/LongestNondecreasingSubsequenceInNLogNTime.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | /* Problem 17.12.8 page 337 */ -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/MinimizeMessinessInLinearTimeConstantSpace.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | /* Problem 17.11.3 page 335 */ 4 | 5 | fun minimizeMessiness(words: List, lineCapacity: Int): Int? { 6 | if (words.isEmpty()) return 0 7 | var messiness: Int? = lineCapacity 8 | var wordsLength = 0 9 | for (word in words) { 10 | val wordLength = word.length 11 | if (wordLength > lineCapacity) { 12 | messiness = null 13 | break 14 | } 15 | val spaceAndWordLength = wordLength + if (wordsLength == 0) 0 else 1 16 | val nextWordsLength = wordsLength + spaceAndWordLength 17 | if (nextWordsLength <= lineCapacity) { 18 | messiness = messiness?.minus(spaceAndWordLength) 19 | wordsLength = nextWordsLength 20 | } else { 21 | messiness = messiness?.plus(lineCapacity - wordLength) 22 | wordsLength = wordLength 23 | } 24 | } 25 | return messiness 26 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/NumberOfWaysToTraverse2DArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | /** 4 | * Problem 17.3.1 page 317 5 | */ 6 | fun numberOfWaysToTraverse2DArray(rowCount: Int, columnCount: Int): Int { 7 | val array = mutableListOf>().apply { 8 | val row = mutableListOf().apply { 9 | (0 until columnCount).forEach { 10 | (if (it == 0) 1 else 0).let { 11 | add(it) 12 | } 13 | } 14 | } 15 | addAll((0 until rowCount).map { row.toMutableList() }) 16 | }.apply { 17 | get(0).apply { (1 until columnCount).forEach { set(it, 1) } } 18 | } 19 | (1 until rowCount).forEach { rowIndex -> 20 | (1 until columnCount).forEach { columnIndex -> 21 | array[rowIndex][columnIndex] = array[rowIndex - 1][columnIndex] + 22 | array[rowIndex][columnIndex - 1] 23 | } 24 | } 25 | return array.last().last() 26 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/NumberOfWaysToTraverse2DArrayWithLessSpace.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | /** 4 | * Problem 17.3.2 page 318 5 | */ 6 | fun numberOfWaysToTraverse2DArrayWithLessSpace( 7 | rowCount: Int, columnCount: Int): Int { 8 | val (shortSide, longSide) = 9 | listOf(rowCount, columnCount).sorted() 10 | return IntArray(shortSide) { 1 } 11 | .apply { 12 | (1 until longSide).forEach { 13 | (1 until shortSide).forEach { 14 | set(it, get(it-1) + get(it)) 15 | } 16 | } 17 | }.last() 18 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/RegexMatchWithMinimumLevenshteinDistance.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/WaysToClimbStairs.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | fun countOfWaysToClimbStairs(stairCount: Int, maxStepsAtATime: Int): Int { 4 | if (stairCount == 0) return 0 5 | val cache = mutableListOf(1) 6 | 1.rangeTo(stairCount).forEach { stair -> 7 | var ways = 0 8 | 1.rangeTo(maxStepsAtATime).forEach { steps -> 9 | val previousStair = stair - steps 10 | ways += if (previousStair >= 0) 11 | cache[previousStair] 12 | else 0 13 | } 14 | cache.add(ways) 15 | } 16 | return cache[stairCount] 17 | } 18 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/graphs/ComputeBlackRegionContainingMostPoints.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.graphs 2 | 3 | /** 4 | * Problem 19.2.2 page 365 5 | */ 6 | fun computeBlackRegionContainingMostPoints( 7 | matrix: List>): Set> { 8 | val graph = toGraph(matrix) // Let's assume true == black 9 | return computeComponents(graph).maxBy { it.size } ?: emptySet() 10 | } 11 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/graphs/DeadlockDetection.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.graphs 2 | 3 | import java.util.* 4 | 5 | fun detectDeadlock(digraph: List>): Boolean { 6 | var deadlockFound = false 7 | val stack = LinkedList>() 8 | val exploredNodes = mutableSetOf>() 9 | val digraphIterator = digraph.iterator() 10 | while (digraphIterator.hasNext()) { 11 | stack.push(digraphIterator.next()) 12 | while (stack.isNotEmpty()) { 13 | val node = stack.pop() 14 | if (exploredNodes.contains(node)) { 15 | deadlockFound = true 16 | break 17 | } 18 | exploredNodes.add(node) 19 | node.adjacentNodes.forEach { stack.push(it) } 20 | } 21 | exploredNodes.clear() 22 | if (deadlockFound) break 23 | } 24 | return deadlockFound 25 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/graphs/GraphRemainsConnectedAfterRemovingAnyEdge.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.graphs 2 | 3 | /** 4 | * Problem 19.4.3 page 369 5 | */ 6 | // Might have been simpler and more appropriate to represent the 7 | // graph with an edge list, instead of an adjacency list. 8 | object GraphRemainsConnectedAfterRemovingAnyEdge { 9 | data class Node(val value: K) 10 | fun graphRemainsConnectedAfterRemovingAnyEdge( 11 | graph: Map, Set>>): Boolean { 12 | val nodeToIncomingEdgeCountMap = mutableMapOf, Int>() 13 | graph.values.forEach { adjacentNodes -> 14 | adjacentNodes.forEach { node -> 15 | nodeToIncomingEdgeCountMap.let { 16 | it.put(node, it.getOrPut(node, { 0 }) + 1) 17 | } 18 | } 19 | } 20 | return nodeToIncomingEdgeCountMap.let { 21 | if (it.any { it.value == 0 }) 22 | throw IllegalArgumentException( 23 | "Graph must be connected, to begin with.") 24 | graph.size == 1 || !it.containsValue(1) 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/graphs/Point.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.graphs 2 | 3 | data class Point (val column: Int, val row: Int, val value: T? = null) 4 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/greedyalgorithmsandinvariants/FindMajorityElement.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.greedyalgorithmsandinvariants 2 | 3 | /** 4 | * Problem 18.5 page 347 5 | */ 6 | 7 | fun findMajorityElement(strings: List): String? { 8 | when (strings.count()) { 9 | 0 -> return null 10 | 1 -> return strings.first() 11 | } 12 | var majorityElement: String? = null 13 | var majorityElementCount = 0 14 | var count = 0 15 | strings.forEach { element -> 16 | majorityElement?.let { 17 | count += 1 18 | val elementIsMajorityElement = it == element 19 | majorityElementCount += if (elementIsMajorityElement) 1 else 0 20 | val halfCount = count / 2 21 | if (majorityElementCount <= halfCount) { 22 | majorityElement = null 23 | majorityElementCount = 0 24 | } 25 | } ?: run { 26 | count = 1 27 | majorityElement = element 28 | majorityElementCount = 1 29 | } 30 | } 31 | return majorityElement 32 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/greedyalgorithmsandinvariants/TheIntervalCoveringProblem.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.greedyalgorithmsandinvariants 2 | 3 | /** 4 | * Problem 18.3.1 p342 5 | */ 6 | 7 | data class Interval(val start:Int, val end:Int) : Comparable { 8 | override fun compareTo(other: Interval): Int { 9 | return start - other.start 10 | } 11 | } 12 | 13 | fun minimumSizedSetOfNumbersThatCoverAllIntervals( 14 | intervals: List): List { 15 | val cover = mutableListOf() 16 | val sortedIntervals = intervals.sorted() 17 | cover.add(sortedIntervals[0]) 18 | sortedIntervals.takeLast(sortedIntervals.size - 1).forEach { 19 | var coverInterval = cover.last().copy() 20 | if (it.start <= coverInterval.end) { 21 | coverInterval = coverInterval.copy( 22 | start = it.start, 23 | end = minOf(coverInterval.end, it.end)) 24 | cover[cover.lastIndex] = coverInterval 25 | } else { 26 | cover.add(it) 27 | } 28 | } 29 | return cover.map { it.start } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/hashtables/ImplementHashFunctionForChess.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/hashtables/RearrangeArrayToMaximizeLengthOfShortestSubarrayContainingAllDistinctValues.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | import java.util.Map.Entry.comparingByValue 4 | import java.util.stream.Collectors.toList 5 | 6 | /** 7 | * Problem 13.7.4 page 225 8 | */ 9 | fun maximumLengthOfShortestSubarrayContainingAllDistinctValues(values: List): Int { 10 | if (values.isEmpty()) return 0 11 | val mapOfValuesToCount = mutableMapOf() 12 | values.forEach { value -> 13 | mapOfValuesToCount[value] = mapOfValuesToCount.getOrDefault(value, 0) + 1 14 | } 15 | val sortedEntries = mapOfValuesToCount.entries.stream() 16 | .sorted(comparingByValue()).collect(toList()) 17 | if (mapOfValuesToCount.size == 1) return 1 18 | val positionOfLastValueOfFirstSubarray = sortedEntries[0].value 19 | val positionOfFirstValueOfLastSubarray = values.size - sortedEntries[1].value + 1 20 | return positionOfFirstValueOfLastSubarray - positionOfLastValueOfFirstSubarray + 1 21 | } 22 | 23 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/hashtables/ShortestSubarrayOfDistinctValues.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | /** 4 | * Problem 13.7.3 page 225 5 | */ 6 | fun rangeOfShortestSubarrayOfDistinctValues(values: List): IntRange? { 7 | if (values.isEmpty()) return null 8 | var shortestRange: IntRange = (0..0) 9 | val valueToPositionMap = LinkedHashMap() 10 | values.forEachIndexed { 11 | index, value -> 12 | val valueIsNew = !valueToPositionMap.containsKey(value) 13 | if (!valueIsNew) { 14 | valueToPositionMap.remove(value) 15 | } 16 | valueToPositionMap.put(value, index) 17 | val positions = valueToPositionMap.values 18 | val newRange = positions.first()..positions.last() 19 | if (valueIsNew || 20 | shortestRange.count() >= newRange.count()) { 21 | shortestRange = newRange 22 | } 23 | } 24 | return shortestRange 25 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/heaps/ImplementQueueUsingHeap.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.heaps 2 | 3 | import java.util.* 4 | 5 | /** 6 | * Problem 11.7.2 page 188 7 | */ 8 | class ImplementQueueUsingHeap { 9 | 10 | class HeapItem>(val data: T, val priority: Int) 11 | 12 | class QueueUsingHeap> { 13 | var count: Int = 0 14 | 15 | val heap = PriorityQueue>( 16 | { i, j -> i.priority.compareTo(j.priority) }) 17 | 18 | fun add(data: T) { 19 | heap.add(HeapItem(data, count++)) 20 | } 21 | 22 | fun remove(): T { 23 | return heap.remove().data 24 | } 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/heaps/ImplementStackUsingHeap.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.heaps 2 | 3 | import java.util.* 4 | 5 | /** 6 | * Problem 11.7.1 page 187 7 | */ 8 | class StackUsingHeap { 9 | data class PriorityQueueItem(val value: T, val priority: Int) 10 | 11 | val heap = PriorityQueue>( 12 | Comparator> { item1, item2 -> 13 | item2.priority.compareTo(item1.priority) 14 | }) 15 | 16 | fun push(value: T) { 17 | heap.add(PriorityQueueItem(value, heap.size)) 18 | } 19 | 20 | fun pop(): T { 21 | return heap.remove().value 22 | } 23 | 24 | fun isNotEmpty(): Boolean { 25 | return heap.isNotEmpty() 26 | } 27 | 28 | override fun toString(): String { 29 | return "StackUsingHeap(heap=$heap)" 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/heaps/MergeSortedFiles.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.heaps 2 | 3 | import java.util.* 4 | 5 | /** 6 | * Problem 11.1 page 178 7 | */ 8 | fun mergeSortedLists(lists: List>): List { 9 | data class Item(val list: List) { 10 | private var position = 0 11 | val next: Int 12 | get() { 13 | val item = peek 14 | position++ 15 | return item 16 | } 17 | val peek: Int 18 | get() { 19 | return list[position] 20 | } 21 | val isNotEmpty: Boolean 22 | get() { 23 | return position < list.size 24 | } 25 | } 26 | val mergedList = mutableListOf() 27 | val heap = PriorityQueue({ 28 | firstList, secondList -> 29 | firstList.peek - secondList.peek}) 30 | heap.addAll(lists.filter { it.isNotEmpty() }.map { Item(it) }) 31 | while (heap.isNotEmpty()) { 32 | val item = heap.poll() 33 | mergedList.add(item.next) 34 | if (item.isNotEmpty) { 35 | heap.add(item) 36 | } 37 | } 38 | return mergedList 39 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/honors/FindFirstMissingPositiveEntry.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.honors 2 | 3 | /** 4 | * Problem 25.2 page 444 5 | */ 6 | fun findFirstMissingPositiveEntry(array: MutableList): Int { 7 | var incrementedIndex = 0 8 | while (incrementedIndex <= array.lastIndex) { 9 | var entry = array[incrementedIndex] 10 | ++incrementedIndex 11 | if (entry == 0) continue 12 | while (true) { 13 | if (entry !in (1..array.size)) { 14 | break 15 | } else { 16 | val entryIndex = entry - 1 17 | entry = array[entry - 1] 18 | array[entryIndex] = 0 19 | } 20 | } 21 | } 22 | println(array) 23 | return array.foldRightIndexed(array.size + 1) { 24 | index, entry, acc -> 25 | if (entry != 0) index + 1 else acc 26 | } 27 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/honors/ProductsOfAllEntriesButOne.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.honors 2 | 3 | /* Problem 25.4.2 page 448 */ 4 | 5 | /* We'll simplify cases very slightly by assuming that the input 6 | list always has more than one entry. */ 7 | 8 | fun productsOfAllEntriesButOne(list: List): List { 9 | val products = list.fold(mutableListOf()) { acc, i -> 10 | ((acc.lastOrNull() ?: 1) * i).let { 11 | acc.apply { add(it) } 12 | } 13 | } 14 | var rightProduct = 1 15 | (list.lastIndex downTo 0).forEach { index -> 16 | val leftProduct = if (index > 0) products[index - 1] else 1 17 | rightProduct *= (if (index < list.lastIndex) list[index + 1] else 1) 18 | products[index] = leftProduct * rightProduct 19 | } 20 | return products 21 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/honors/RotateArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.honors 2 | 3 | /* Problem 25.6 page 450 */ 4 | 5 | fun rotateArray(distance: Int, array: MutableList) { 6 | val rotationDistance = if (array.isNotEmpty()) distance % array.size 7 | else return 8 | var index = -1 9 | var element: T? = null 10 | var count = 1 11 | while (count <= array.size) { 12 | if (element == null) { 13 | index += 1 14 | element = array[index] 15 | array[index] = null 16 | } 17 | index = (index + rotationDistance) % array.size 18 | val nextElement = array[index] 19 | array[index] = element 20 | element = nextElement 21 | count += 1 22 | } 23 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/CyclicRightShiftForSinglyLinkedLists.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | /* Problem 8.9 page 125 */ 4 | 5 | fun cyclicRightShiftForSinglyLinkedLists(list: LinkedListNode, k: Int): LinkedListNode { 6 | if (list.next == null) return list 7 | val listCount = list.count() 8 | val shiftCount = k.rem(listCount) 9 | if (shiftCount == 0) return list 10 | val endNode = list.advance(listCount) 11 | val positionOfNewEndNode = listCount - shiftCount - 1 12 | val newEndNode = list.advance(positionOfNewEndNode) 13 | val newFirstNode = newEndNode.next 14 | newEndNode.next = null 15 | endNode.next = list 16 | return newFirstNode!! 17 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/EvenOddMerge.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | /* Problem 8.10 page 127 */ 4 | 5 | fun evenOddMerge(list: LinkedListNode) { 6 | var previousEvenNode = list 7 | var oddNode = list.next 8 | while (true) { 9 | val nextEvenNode = oddNode?.next ?: break 10 | oddNode.next = nextEvenNode.next 11 | nextEvenNode.next = previousEvenNode.next 12 | previousEvenNode.next = nextEvenNode 13 | previousEvenNode = nextEvenNode 14 | oddNode = oddNode.next 15 | } 16 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/RemoveDuplicatesFromSortedList.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | /* Problem 8.8.1 page 124 */ 4 | 5 | fun > removeDuplicatesFromSortedList(list: LinkedListNode) { 6 | var distinctEntriesTail = list 7 | var currentNode = list 8 | while (true) { 9 | if (currentNode.data != distinctEntriesTail.data) { 10 | distinctEntriesTail.next = currentNode 11 | distinctEntriesTail = currentNode 12 | } 13 | currentNode.next?.let { 14 | currentNode = it 15 | } ?: break 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/RemoveEntriesFromListWhenMoreThanMDuplicates.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | /* Problem 8.8.2 page 125 */ 4 | 5 | fun > removeEntriesFromListWhenMoreThanMDuplicates( 6 | list: LinkedListNode, m: Int): LinkedListNode? { 7 | val sentinelNode = LinkedListNode(next = list) 8 | var filteredEntriesTail: LinkedListNode = sentinelNode 9 | var currentNode = sentinelNode 10 | while (true) { 11 | currentNode.next?.let { 12 | var duplicateCount = 1 13 | currentNode = it 14 | while (true) { 15 | currentNode.next?.let { 16 | if (it.data == currentNode.data) { 17 | ++duplicateCount 18 | currentNode = it 19 | } else null 20 | } ?: break 21 | } 22 | if (duplicateCount > m) { 23 | filteredEntriesTail.next = currentNode.next 24 | } else { 25 | filteredEntriesTail = currentNode 26 | } 27 | } ?: break 28 | } 29 | return sentinelNode.next 30 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/RemoveKthLastElement.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | /* Problem 8.7 page 123 */ 4 | 5 | fun removeKthLastElement(list: LinkedListNode, k: Int): LinkedListNode? { 6 | var count = 1 7 | var pointer1 = list 8 | var pointer2 = list 9 | while (count < k + 1) { 10 | pointer1 = pointer1.next ?: break 11 | ++count 12 | } 13 | return when { 14 | count < k -> null 15 | count == k -> pointer2 16 | else -> { 17 | while (true) { 18 | pointer1.next?.let { 19 | pointer1 = it 20 | } ?: break 21 | pointer2.next?.let { 22 | pointer2 = it 23 | } 24 | } 25 | val kthNode = pointer2.next 26 | pointer2.next = kthNode?.next 27 | kthNode?.apply { 28 | next = null 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/ReverseList.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | import com.lagostout.elementsofprogramminginterviews.linkedlists.ReverseSingleSublist.reverseSingleSublist 4 | 5 | fun reverseList(list: LinkedListNode): LinkedListNode { 6 | var nodeCount = 1 7 | list.run { 8 | var node = this 9 | while (node.next != null) { 10 | node = node.next?.let { 11 | nodeCount++ 12 | it 13 | } ?: break 14 | } 15 | } 16 | return reverseSingleSublist(list, 1, nodeCount) 17 | } 18 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/TestIfDoublyLinkedListIsPalindrome.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | /* Problem 8.11.2 page 128 */ 4 | 5 | fun doublyLinkedListIsPalindrome( 6 | list: LinkedListNode, tail: LinkedListNode): Boolean { 7 | var leftNode = list 8 | var rightNode = tail 9 | var isPalindrome = true 10 | while (true) { 11 | if (leftNode.data != rightNode.data) { 12 | isPalindrome = false 13 | break 14 | } 15 | if (leftNode.next == rightNode || 16 | leftNode == rightNode) break 17 | leftNode = leftNode.next!! 18 | rightNode = rightNode.previous!! 19 | } 20 | return isPalindrome 21 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/ClosestIntegerWithSameWeightInConstantSpaceTime.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | /* Problem 5.4.2 page 50 */ 4 | 5 | fun findClosestIntegerWithSameWeightInConstantSpaceTime(number: Int): Int { 6 | if (number == 0) return 0 7 | val rightmostZeroBit = number.let { 8 | (it + 1) and it.inv() 9 | } 10 | return if (rightmostZeroBit == 1) { 11 | val rightmostOneBit = number.let { 12 | it and (it - 1).inv() 13 | } 14 | (number xor rightmostOneBit) or 15 | (rightmostOneBit ushr 1) 16 | } else { 17 | val leftmostOneBit = rightmostZeroBit ushr 1 18 | (number xor leftmostOneBit) or rightmostZeroBit 19 | } 20 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/ComputeXToPowerY.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | /* Problem 5.7 page 54 */ 4 | 5 | fun computeXToPowerY(x: Double, y: Int): Double { 6 | var result = 1.0 7 | var power = y 8 | var multipleOfX = 1.0 9 | while (power > 0) { 10 | multipleOfX *= (if (multipleOfX == 1.0) 11 | x else multipleOfX) 12 | if (power.and(1) == 1) { 13 | result *= multipleOfX 14 | } 15 | power = power shr 1 16 | } 17 | return result 18 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/Divide.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | /* Problem 5.6 page 53 */ 4 | 5 | fun divide(x: Int, y: Int): Int? { 6 | if (y == 0) return null 7 | if (x < y) return 0 8 | var dividend = x 9 | var divisor = y 10 | // Shift divisor left till its leftmost bit 11 | // is aligned with that of dividend. 12 | while (true) { 13 | val nextDivisor = divisor shl 1 14 | if (nextDivisor > dividend) break 15 | divisor = nextDivisor 16 | } 17 | var quotient = 0 18 | while (divisor >= y) { 19 | quotient = quotient shl 1 20 | if (dividend >= divisor) { 21 | quotient += 1 22 | dividend -= divisor 23 | } 24 | divisor = divisor shr 1 25 | } 26 | return quotient 27 | } 28 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/ReverseDigits.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | /* Problem 5.8 page 55 */ 4 | 5 | @Suppress("NAME_SHADOWING") 6 | fun reverseDigits2(number: Int): Int { 7 | var number = number 8 | var result = 0 9 | while (true) { 10 | // -x % y = some negative number 11 | val digit = number % 10 12 | number /= 10 13 | // When number is negative, we're adding 14 | // negative numbers here, thus preserving 15 | // the negative sign. 16 | result += digit 17 | if (number == 0) break 18 | result *= 10 19 | } 20 | return result 21 | } 22 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/SwapBits.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | fun swapBits(number: Long, from: Int, to: Int): Long { 4 | // Let's assume position 0 is the LSB, and 63 is the MSB. 5 | var swappedNumber = number 6 | // Extract the values at both positions 7 | val fromMask = (1L shl from) 8 | val toMask = (1L shl to) 9 | val fromValue = number and fromMask 10 | val toValue = number and toMask 11 | // No point in swapping if bit values are equal 12 | if (fromValue != toValue) { 13 | listOf(fromValue to toMask, toValue to fromMask).forEach { 14 | (value, mask) -> 15 | swappedNumber = swappedNumber.let { 16 | if (value == 0L) it and mask.inv() 17 | else it or mask 18 | } 19 | } 20 | } 21 | return swappedNumber 22 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/recursion/MaximumWaterTrappedByVerticalLines.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.recursion 2 | 3 | /* Problem 18.7 page 350 */ 4 | 5 | fun maximumWaterTrappedByVerticalLines(lines: List): Int { 6 | var leftIndex = 0 7 | var rightIndex = lines.lastIndex 8 | var max = 0 9 | while (leftIndex < rightIndex) { 10 | val left = lines[leftIndex] 11 | val right = lines[rightIndex] 12 | val volume = minOf(left, right) * (rightIndex - leftIndex) 13 | max = maxOf(max, volume) 14 | if (left > right) rightIndex -= 1 15 | else leftIndex += 1 16 | } 17 | return max 18 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/ComputeIntegerSquareRoot.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.4 page 196 5 | */ 6 | fun computeIntegerSquareRoot(n: Int): Int { 7 | var left = 1 8 | var right = n 9 | var mid: Int 10 | var square: Int 11 | do { 12 | mid = (right - left)/2 + left 13 | square = mid * mid 14 | if (square == n) break 15 | else if (square > n) 16 | right = mid - 1 17 | else { 18 | left = mid + 1 19 | } 20 | } while (left <= right) 21 | return if (square > n) mid - 1 else mid 22 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/ComputeRealSquareRoot.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.5.1 page 197 5 | */ 6 | fun computeRealSquareRoot(n: Double, epsilon: Double): Double { 7 | var left = 0.0 8 | var right = if (n < 1) 1.0 else n 9 | var mid: Double 10 | var square: Double 11 | var previousMid: Double? = null 12 | do { 13 | mid = (right - left)/2 + left 14 | if (previousMid != null && 15 | previousMid == mid) break 16 | square = mid * mid 17 | if (square >= n - epsilon && square <= n - epsilon) break 18 | else if (square > n) 19 | right = mid 20 | else { 21 | left = mid 22 | } 23 | previousMid = mid 24 | } while (true) 25 | return mid 26 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/DivideWithoutUsingDivisionOperator.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | import kotlin.math.absoluteValue 4 | 5 | /** 6 | * Problem 12.5.2 page 199 7 | */ 8 | fun divideWithoutUsingDivisionOperator( 9 | dividend: Double, divisor: Double, 10 | tolerance: Double): Double { 11 | var left = 0.0 12 | var right = dividend.absoluteValue 13 | val absoluteDivisor = divisor.absoluteValue 14 | val absoluteDividend = dividend.absoluteValue 15 | val dividendRange = (absoluteDividend - tolerance) 16 | .rangeTo(absoluteDividend + tolerance) 17 | var mid: Double 18 | loop@ while (true) { 19 | mid = left + (right - left)/2 20 | val product = absoluteDivisor * mid 21 | when { 22 | product in dividendRange -> 23 | break@loop 24 | product < absoluteDividend -> 25 | left = mid 26 | product > absoluteDividend -> 27 | right = mid 28 | } 29 | } 30 | return mid.let { 31 | if (dividend * divisor < 0) it * -1 else it 32 | } 33 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindArrayEntryEqualToItsIndex.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.2.1 page 194 5 | */ 6 | fun findArrayEntryEqualToItsIndex(array: List): Int? { 7 | var left = 0 8 | var right = array.lastIndex 9 | var entryEqualToIndex: Int? = null 10 | while (left <= right) { 11 | val mid = (right - left) + (left/2) 12 | val midEntry = array[mid] 13 | if (mid == midEntry) { 14 | entryEqualToIndex = mid 15 | break 16 | } else if (mid < midEntry) { 17 | right = mid - 1 18 | } else if (mid > midEntry) { 19 | left = mid + 1 20 | } 21 | } 22 | return entryEqualToIndex 23 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindArrayEntryEqualToItsIndexWhenThereMayBeDuplicates.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.2.2 page 194 5 | */ 6 | // Is this the fastest solution? 7 | fun findArrayEntryEqualToItsIndexWhenThereMayBeDuplicates( 8 | array: List): Int? { 9 | var entryEqualToIndex: Int? = null 10 | if (array.isEmpty()) return entryEqualToIndex 11 | var currentIndex = 0 12 | loop@ while (currentIndex <= array.lastIndex) { 13 | val entry = array[currentIndex] 14 | when { 15 | entry == currentIndex -> { 16 | entryEqualToIndex = entry 17 | break@loop 18 | } 19 | entry < currentIndex -> ++currentIndex 20 | else -> currentIndex = entry 21 | } 22 | } 23 | return entryEqualToIndex 24 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindElementInCyclicallySortedArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.3.1 page 194 5 | */ 6 | fun > findElementInCyclicallySortedArray( 7 | array: List, value: T): Int? { 8 | var left = 0 9 | var right = array.lastIndex 10 | var elementIndex: Int? = null 11 | while (left <= right) { 12 | val leftValue = array[left] 13 | val rightValue = array[right] 14 | val mid = (right - left) / 2 + left 15 | val midValue = array[mid] 16 | if (midValue == value) { 17 | elementIndex = mid 18 | break 19 | } else if (midValue > value) { 20 | if (value < leftValue) 21 | left = mid + 1 22 | else right = mid - 1 23 | } else { 24 | if (value > rightValue) 25 | right = mid - 1 26 | else left = mid + 1 27 | } 28 | } 29 | return elementIndex 30 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindFirstIndexOfElementGreaterThanKey.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.1.2 page 193 5 | */ 6 | fun findFirstIndexOfElementGreaterThanKey(sortedList: List, key: Int): Int? { 7 | // Cases: 8 | // Key is less than every element in the list. 9 | // Key is greater than every element in the list. 10 | // Key is in the range of elements in the list. 11 | // List is empty. 12 | var i = 0 13 | var j = sortedList.size 14 | // Condition i < j is safe when list is empty. 15 | while (i < j) { 16 | val mid = i + (j - i)/2 17 | val value = sortedList[mid] 18 | if (value <= key) 19 | i = mid + 1 20 | else if (value > key) 21 | j = mid 22 | } 23 | return if (i <= sortedList.lastIndex) i else null 24 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindIntervalEnclosingInteger.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.1.4 page 193 5 | */ 6 | fun >findIntervalEnclosingInteger( 7 | sortedList: List, k: T): Pair { 8 | var i = 0 9 | var j = sortedList.size 10 | 11 | // Find first occurrence 12 | 13 | while (i < j && sortedList[i] != k) { 14 | val mid = i + ((j - i) / 2) 15 | if (sortedList[mid] < k) { 16 | i = mid + 1 17 | } 18 | else j = mid 19 | } 20 | 21 | // Integer not present in list 22 | 23 | if (i == sortedList.size // Elements < k 24 | || sortedList[i] != k) // Elements > k 25 | return Pair(-1, -1) 26 | 27 | // Find last occurrence 28 | 29 | val left = i 30 | j = sortedList.size 31 | while (i < j) { 32 | val mid = i + ((j - i) / 2) 33 | if (sortedList[mid] > k) j = mid 34 | else i = mid + 1 35 | } 36 | val right = j - 1 37 | 38 | return Pair(left, right) 39 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindLocalMinimum.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.1.3 page 193 5 | */ 6 | fun findIndexOfLocalMinimum(array: List): Int { 7 | val indexOfMinimum: Int 8 | var left = 0 9 | var right = array.size 10 | while (true) { 11 | val middle = (left + right) / 2 12 | if (array[middle - 1] >= array[middle] && 13 | array[middle + 1] >= array[middle]) { 14 | indexOfMinimum = middle 15 | break 16 | } else if (array[middle - 1] <= array[middle]) { 17 | right = middle 18 | } else { 19 | left = middle 20 | } 21 | } 22 | return indexOfMinimum 23 | } 24 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindMaxInAscendingDescendingSequences.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.3.2 page 196 5 | */ 6 | fun findMaxInAscDescSequences(sequences: List): Int { 7 | var left = 0 8 | var right = sequences.lastIndex 9 | var mid: Int = left 10 | while (right - left > 1) { 11 | mid = (right - left) / 2 + left 12 | if (sequences[mid] > sequences[mid - 1] && 13 | sequences[mid] > sequences[mid + 1]) { 14 | break 15 | } else if (sequences[mid] > sequences[mid - 1]) { 16 | left = mid + 1 17 | } else if (sequences[mid] > sequences[mid + 1]) { 18 | right = mid 19 | } 20 | } 21 | return sequences[mid] 22 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindMinMaxSimultaneously.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /* Problem 12.7 page 201 */ 4 | 5 | fun > findMinMaxSimultaneously(list: List): Pair?> { 6 | var comparisonCount = 0 7 | if (list.isEmpty()) return Pair(comparisonCount, null) 8 | var minMax: Pair? = null 9 | (0..list.lastIndex step 2).forEach { 10 | val pair = Pair(list[it], if (it == list.lastIndex) 11 | list[it] else list[it + 1]).let { 12 | ++comparisonCount 13 | if (it.first > it.second) Pair(it.second, it.first) else it 14 | } 15 | minMax = minMax?.let { 16 | comparisonCount += 2 17 | Pair(minOf(pair.first, it.first), 18 | maxOf(pair.second, it.second)) 19 | } ?: pair 20 | } 21 | return Pair(comparisonCount, minMax) 22 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindStringWithPrefixInArrayOfSortedStrings.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.1.5 page 193 5 | */ 6 | fun findStringWithPrefix(prefix: String, strings: List): String? { 7 | var lo = 0 8 | var hi = strings.size 9 | var result: String? = null 10 | if (strings.isEmpty() || prefix.isEmpty()) return result 11 | run { 12 | while (lo <= hi) { 13 | val mid = (hi - lo)/2 + lo 14 | when (prefix.compareTo(strings[mid].substring(0, prefix.length))) { 15 | 0 -> { 16 | result = strings[mid] 17 | return@run 18 | } 19 | 1 -> lo = mid + 1 20 | -1 -> hi = mid - 1 21 | } 22 | } 23 | } 24 | return result 25 | } 26 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/Search2DSortedArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.6 page 199 5 | */ 6 | fun findInTwoDimensionSortedArray(entry: Int, array: List>): Pair? { 7 | if (array.isEmpty() || array.first().isEmpty()) return null 8 | var columnIndex = array.first().lastIndex 9 | var rowIndex = 0 10 | var done = false 11 | var result: Pair? = null 12 | while (!done && columnIndex >= 0 && 13 | rowIndex <= array.lastIndex) { 14 | array[rowIndex][columnIndex].let { 15 | when { 16 | it > entry -> --columnIndex 17 | it < entry -> ++rowIndex 18 | else -> { 19 | result = Pair(rowIndex, columnIndex) 20 | done = true 21 | } 22 | } 23 | } 24 | } 25 | return result 26 | } 27 | 28 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/SearchCyclicallySortedArray.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.3.1 page 194 5 | */ 6 | fun findPositionOfSmallestEntryInCyclicallySortedArray(list: List): Int? { 7 | if (list.isEmpty()) return null 8 | var left = 0 9 | var right = list.lastIndex 10 | while (right - left > 1) { 11 | val mid = (right - left) / 2 + left 12 | if (list[left] > list[mid]) { 13 | right = mid 14 | } else { 15 | left = mid 16 | } 17 | } 18 | return right 19 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/searching/SearchSortedArrayForFirstOccurrence.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | /** 4 | * Problem 12.1 page 192 5 | */ 6 | fun firstOccurrence(array: List, k: Int): Int? { 7 | var firstOccurrenceOfK: Int? = null 8 | var left = 0 9 | var right = array.lastIndex 10 | while (left <= right) { 11 | val middle = left + ((right - left) / 2) 12 | val middleValue = array[middle] 13 | if (middleValue >= k) { 14 | right = middle - 1 15 | if (middleValue == k) { 16 | firstOccurrenceOfK = middle 17 | } 18 | } else if (middleValue < k) { 19 | left = middle + 1 20 | } 21 | } 22 | return firstOccurrenceOfK 23 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/sorting/TeamPhotoDay.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.sorting 2 | 3 | /* Problem 14.8 page 253 */ 4 | 5 | fun playerPlacementSubjectToConstraintIsPossible( 6 | team1: List, team2: List): Boolean { 7 | if (team1.size != team2.size) return false 8 | val sortedTeam1 = team1.sorted() 9 | val sortedTeam2 = team2.sorted() 10 | val rows = if (sortedTeam1.first() < sortedTeam2.first()) 11 | Pair(sortedTeam1, sortedTeam2) 12 | else Pair(sortedTeam2, sortedTeam1) 13 | val pairs = rows.first.zip(rows.second) 14 | var result = true 15 | for (pair in pairs) { 16 | if (pair.first >= pair.second) { 17 | result = false 18 | break 19 | } 20 | } 21 | return result 22 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/stacksandqueues/ComputeBinaryTreeLevelAverages.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.stacksandqueues 2 | 3 | import com.lagostout.datastructures.BinaryTreeNode 4 | import java.util.* 5 | 6 | /** 7 | * Problem 9.7.4 page 146 8 | */ 9 | fun computeBinaryTreeLevelAverages( 10 | root: BinaryTreeNode): List { 11 | val queue = LinkedList>>().apply { 12 | add(listOf(root)) 13 | } 14 | val averages = mutableListOf() 15 | while (!queue.isEmpty()) { 16 | val level = queue.remove() 17 | level.run { 18 | sumBy { 19 | it.value 20 | }.toDouble() / size 21 | }.let { 22 | averages.add(it) 23 | } 24 | level.flatMap { 25 | listOf(it.left, it.right) 26 | .filterNotNull() 27 | }.let { 28 | if (!it.isEmpty()) 29 | queue.add(it) 30 | } 31 | } 32 | return averages 33 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/stacksandqueues/ComputeBinaryTreeNodesInBottomUpLeftToRightOrder.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.stacksandqueues 2 | 3 | import com.lagostout.datastructures.BinaryTreeNode 4 | import java.util.* 5 | 6 | /** 7 | * Problem 9.7.3 page 146 8 | */ 9 | fun computeBinaryTreeNodesInBottomUpLeftToRightOrder( 10 | root: BinaryTreeNode): List>> { 11 | val queue = LinkedList>>().apply { 12 | add(listOf(root)) 13 | } 14 | while (true) { 15 | queue.peekLast().let { 16 | val nextLevel = mutableListOf>() 17 | it.forEach { 18 | listOfNotNull(it.left, it.right).forEach { 19 | nextLevel.add(it) 20 | } 21 | } 22 | if (nextLevel.isEmpty()) null 23 | else queue.add(nextLevel) 24 | }?: break 25 | } 26 | val nodes = mutableListOf>>() 27 | while (!queue.isEmpty()) { 28 | nodes.add(queue.removeLast()) 29 | } 30 | return nodes 31 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/stacksandqueues/ComputeBinaryTreeNodesInOrderOfIncreasingDepth.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.stacksandqueues 2 | 3 | import com.lagostout.datastructures.BinaryTreeNode 4 | import java.util.* 5 | 6 | /** 7 | * Problem 9.7.1 page 144 8 | */ 9 | fun > computeBinaryTreeNodesInOrderOfIncreasingDepth( 10 | root: BinaryTreeNode) : List>> { 11 | val deque = LinkedList>().apply { 12 | addLast(root) 13 | } 14 | val orderedNodes = mutableListOf>>() 15 | while (deque.isNotEmpty()) { 16 | val nodes = mutableListOf>() 17 | (0 until deque.size).forEach { 18 | deque.removeFirst().let { 19 | nodes.add(it) 20 | listOf(it.left, it.right).filterNotNull().forEach { 21 | deque.addLast(it) 22 | } 23 | } 24 | } 25 | orderedNodes.add(nodes) 26 | } 27 | return orderedNodes 28 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/stacksandqueues/ComputeBuildingsWithSunsetViewWhenBuildingsPresentedWestToEast.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.stacksandqueues 2 | 3 | import java.util.* 4 | 5 | /** 6 | * Problem 9.6.2 page 143 7 | */ 8 | fun computeBuildingsWithSunsetViewWhenBuildingsPresentedWestToEast( 9 | buildings: List): List { 10 | if (buildings.isEmpty()) return emptyList() 11 | val stack = LinkedList>() 12 | with (buildings.withIndex()) { 13 | forEach { currentBuilding -> 14 | (stack.peek()?.let { 15 | currentBuilding.value > it.value 16 | } ?: true).let { 17 | if (it) stack.push(currentBuilding) 18 | } 19 | } 20 | } 21 | return stack.map { it.index }.reversed() 22 | } 23 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/stacksandqueues/ImplementQueueUsingStacks.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.stacksandqueues 2 | 3 | import java.util.* 4 | 5 | /** 6 | * Problem 9.9 page 147 7 | */ 8 | class Queue { 9 | 10 | private val inStack = LinkedList() 11 | private val outStack = LinkedList() 12 | 13 | val size: Int 14 | get() = inStack.size + outStack.size 15 | 16 | fun isEmpty(): Boolean { 17 | return size == 0 18 | } 19 | 20 | fun isNotEmpty(): Boolean { 21 | return !isEmpty() 22 | } 23 | 24 | fun enqueue(entry: T) { 25 | inStack.push(entry) 26 | } 27 | 28 | fun dequeue(): T { 29 | if (outStack.isEmpty()) { 30 | while (inStack.isNotEmpty()) { 31 | outStack.push(inStack.pop()) 32 | } 33 | } 34 | if (outStack.isEmpty()) throw IllegalStateException() 35 | return outStack.pop() 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/stacksandqueues/ImplementQueueWithMaxAPI.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.stacksandqueues 2 | 3 | import java.util.* 4 | 5 | /* Problem 9.10 page 148 */ 6 | 7 | class QueueWithMaxAPI { 8 | 9 | data class MaxCount(val max: Int, val count: Int) 10 | 11 | private val queue = LinkedList() 12 | private val deque = LinkedList() 13 | 14 | fun enqueue(entry: Int) { 15 | queue.add(entry) 16 | var count = 0 17 | while (true) { 18 | if (deque.isEmpty()) break 19 | val (previousMax, previousCount) = deque.last() 20 | if (previousMax > entry) break 21 | count += previousCount 22 | deque.removeLast() 23 | } 24 | deque.addLast(MaxCount(entry, count + 1)) 25 | } 26 | 27 | fun dequeue(): Int { 28 | deque.removeFirst().let { 29 | val count = it.count - 1 30 | if (count > 0) 31 | deque.addFirst(it.copy(count = count)) 32 | } 33 | return queue.remove() 34 | } 35 | 36 | fun max(): Int { 37 | return deque.first().max 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/stacksandqueues/StackWithMaxAPI.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.stacksandqueues 2 | 3 | import sun.plugin.dom.exception.InvalidStateException 4 | 5 | class Stack> { 6 | 7 | val items = mutableListOf() 8 | 9 | fun max(): T? { 10 | val otherStack = Stack() 11 | var maxItem: T? = null 12 | while (isNotEmpty()) { 13 | val item = pop() 14 | otherStack.push(item) 15 | maxItem = maxItem?.let { if (item > it) item else it } ?: item 16 | } 17 | while (otherStack.isNotEmpty()) { 18 | push(otherStack.pop()) 19 | } 20 | return maxItem 21 | } 22 | 23 | fun isNotEmpty(): Boolean { 24 | return items.isNotEmpty() 25 | } 26 | 27 | fun push(item: T) { 28 | items.add(item) 29 | } 30 | 31 | fun pop(): T { 32 | if (items.isEmpty()) 33 | throw InvalidStateException("Cannot pop when stack is empty") 34 | return items.removeAt(items.lastIndex) 35 | } 36 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/strings/ComputeMnemonicsForPhoneNumber.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | /** 4 | * Problem 7.7.1/2 page 103 5 | */ 6 | // Skipping this - it's too simple. 7 | object ComputeMnemonicsForPhoneNumber { 8 | 9 | val digitToCharsMap = mapOf(2 to listOf('A','B','C'), 10 | 3 to listOf('D','E','F'), 4 to listOf('G','H','I'), 11 | 5 to listOf('J','K','L'), 6 to listOf('M','N','O'), 12 | 7 to listOf('P','Q','R','S'), 8 to listOf('T','U','V'), 13 | 9 to listOf('X','Y','Z')) 14 | 15 | fun computeMnemonicsForPhoneNumber(number: String): List { 16 | // data class Frame() 17 | // val stack = 18 | digitToCharsMap 19 | 20 | return emptyList() 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/strings/ComputeSpreadsheetColumnEncoding.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | /** 4 | * Problem 7.3.1 page 98 5 | */ 6 | fun numericEncodingOfColumn(alphabeticEncoding: String): Int { 7 | if (alphabeticEncoding.isEmpty()) 8 | throw IllegalArgumentException( 9 | "Alphabetic encoding must contain at least one character") 10 | alphabeticEncoding.find { !it.isLetter() }?.apply { 11 | throw IllegalArgumentException( 12 | "Alphabetic encoding must contain only letters") } 13 | var magnitude = 1 14 | var numericEncoding = 0 15 | alphabeticEncoding.capitalize().reversed().forEach { 16 | numericEncoding += (it - 'A' + 1) * magnitude 17 | magnitude *= 26 18 | } 19 | return numericEncoding 20 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/strings/ComputeSpreadsheetColumnEncodingWhereAIsZero.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | /** 4 | * Problem 7.3.2 page 98 5 | */ 6 | fun numericEncodingOfColumnWhereAIsZero(alphabeticEncoding: String): Int { 7 | if (alphabeticEncoding.isEmpty()) 8 | throw IllegalArgumentException( 9 | "Alphabetic encoding must contain at least one character") 10 | alphabeticEncoding.find { !it.isLetter() }?.apply { 11 | throw IllegalArgumentException( 12 | "Alphabetic encoding must contain only letters") } 13 | var magnitude = 1 14 | var numericEncoding = 0 15 | alphabeticEncoding.capitalize().reversed().forEach { 16 | numericEncoding += (it - 'A' + 1) * magnitude 17 | magnitude *= 26 18 | } 19 | return numericEncoding - 1 20 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/strings/ConvertFromRomanToDecimal.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | /** 4 | * Problem 7.9.1 page 105 5 | */ 6 | fun convertFromRomanToDecimal(roman: String): Int { 7 | val romanToDecimalMap = mapOf( 8 | 'I' to 1, 'V' to 5, 'X' to 10, 9 | 'L' to 50, 'C' to 100, 'D' to 500, 10 | 'M' to 1000) 11 | return roman.withIndex().fold(0) { acc, (index, romanDigit) -> 12 | acc + (romanToDecimalMap[romanDigit]?.let { integer -> 13 | if (index == 0) integer 14 | else { 15 | romanToDecimalMap[roman[index - 1]]?.let { 16 | previousInteger -> 17 | integer - if (previousInteger < integer) { 18 | 2 * previousInteger 19 | } else 0 20 | } ?: 0 21 | } 22 | } ?: 0) 23 | } 24 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/strings/LookAndSayProblem.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | /** 4 | * Problem 7.8 page 104 5 | */ 6 | fun computeLookAndSaySequence(n: Int): String { 7 | var lookSay = "1" 8 | (1 until n).forEach { 9 | lookSay = lookSay.let { 10 | var index = 0 11 | var count = 0 12 | val nextLookSayBuilder = StringBuilder() 13 | do { 14 | val nextIndex = index + 1 15 | val char = it[index] 16 | ++count 17 | if (nextIndex > it.lastIndex || it[nextIndex] != char) { 18 | nextLookSayBuilder.append("$count$char") 19 | count = 0 20 | } 21 | index = nextIndex 22 | } while (index <= it.lastIndex) 23 | nextLookSayBuilder.toString() 24 | } 25 | } 26 | return lookSay 27 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/strings/TestPalindromicity.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | /** 4 | * Problem 7.5 page 100 5 | */ 6 | fun testPalindromicity(string: String): Boolean { 7 | var left = 0 8 | var right = string.lastIndex 9 | var isPalindrome = true 10 | val alphanumericPattern = Regex("[a-z0-9]", RegexOption.IGNORE_CASE) 11 | while (left <= right) { 12 | val leftChar = string[left] 13 | val rightChar = string[right] 14 | println(leftChar) 15 | println(rightChar) 16 | if (!alphanumericPattern.matches(leftChar.toString())) { 17 | ++left 18 | continue 19 | } 20 | if (!alphanumericPattern.matches(rightChar.toString())) { 21 | --right 22 | continue 23 | } 24 | if (leftChar.toLowerCase() != rightChar.toLowerCase()) { 25 | isPalindrome = false 26 | break 27 | } 28 | ++left 29 | --right 30 | } 31 | return isPalindrome 32 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/strings/TestStringForWellFormedness.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | import java.util.* 4 | 5 | object TestStringForWellFormedness { 6 | 7 | private fun isClosingBracket(bracket: Char, otherBracket: Char): Boolean { 8 | return (bracket == '(' && otherBracket == ')') || 9 | (bracket == '{' && otherBracket == '}') || 10 | (bracket == '[' && otherBracket == ']') 11 | } 12 | 13 | fun isWellFormed(string: String): Boolean { 14 | val chars = string.toList() 15 | if (chars.find { it !in "(){}[]" } != null) 16 | throw IllegalArgumentException() 17 | val stack = LinkedList() 18 | chars.forEach { 19 | if (stack.isNotEmpty() && 20 | isClosingBracket(stack.peek(), it)) stack.pop() 21 | else stack.push(it) 22 | } 23 | return stack.isEmpty() 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/elementsofprogramminginterviews/strings/WriteStringSinusoidally.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | /* Problem 7.11 page 107 */ 4 | 5 | fun writeStringSinusoidally(string: String): String { 6 | val steps = listOf(Pair(1,4), Pair(0,2), Pair(3,4)) 7 | val stringBuilder = StringBuilder() 8 | for ((start, step) in steps) { 9 | var index = start 10 | while (index <= string.lastIndex) { 11 | stringBuilder.append(string[index]) 12 | index += step 13 | } 14 | } 15 | return stringBuilder.toString() 16 | } -------------------------------------------------------------------------------- /java/src/main/kotlin/com/lagostout/scratch/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore -------------------------------------------------------------------------------- /java/src/main/sh/move-and-rename-file-for-submission.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Read path to file from parameters. 4 | # Search within the file for name and replace with Main. 5 | # Move and rename the file to src/main/java/Main. 6 | # Call uva-node to submit file. 7 | 8 | sed -i -e 's/foo/bar/g' filename -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/coderust/FindMaximumInSlidingWindowSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.coderust 2 | 3 | import spock.lang.Specification 4 | 5 | class FindMaximumInSlidingWindowSpec extends Specification { 6 | 7 | 8 | 9 | } 10 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/common/GraphsSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class GraphsSpec extends Specification { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/common/HeapsSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | import static com.lagostout.common.Heaps.heapStateIsComplete 7 | 8 | class HeapsSpec extends Specification { 9 | 10 | // TODO 11 | // Test satisfiesHeapProperty(...). Not a high priority 12 | // since I'm already using it, and it appears to work 13 | // correctly. 14 | 15 | @Unroll 16 | 'min heap maintains a complete tree'( 17 | List heap, int heapSize, boolean expected) { 18 | 19 | expect: 20 | heapStateIsComplete(heap, heapSize) == expected 21 | 22 | where: 23 | [heap, heapSize, expected] << [ 24 | [[1], 1, true], 25 | [[1, 2], 1, true], 26 | [[1, 2], 2, true], 27 | [[1, 2], 3, false], 28 | [[1, 2, null], 3, true], 29 | [[1, null, 2], 3, false], 30 | [[1, null, 2], 2, true], 31 | [[1, null, 2], 1, true], 32 | [[1, 2, null], 1, true], 33 | [[1, 2, null], 2, true], 34 | [[1, 2, 3], 3, true], 35 | ] 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/common/PriorityQueueSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PriorityQueueSpec extends Specification { 7 | 8 | // TODO 9 | // Mock heap to verify PriorityQueue interaction. 10 | 11 | def 'inserts value'() { 12 | 13 | } 14 | 15 | def 'updates value'() { 16 | 17 | } 18 | 19 | def 'peeks'() { 20 | 21 | } 22 | 23 | def 'pops'() { 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/common/RandomSpanningTreeBuilderSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.common 2 | 3 | import org.apache.commons.math3.random.RandomDataGenerator 4 | import spock.lang.Shared 5 | import spock.lang.Specification 6 | import spock.lang.Unroll 7 | import static com.lagostout.common.Graphs.* 8 | 9 | class RandomSpanningTreeBuilderSpec extends Specification { 10 | 11 | @Shared 12 | RandomDataGenerator randomDataGenerator 13 | 14 | def setupSpec() { 15 | randomDataGenerator = 16 | new RandomDataGenerator() 17 | randomDataGenerator.reSeed(1) 18 | } 19 | 20 | @Unroll('vertexCount #vertexCount') 21 | 'tree is valid'(int vertexCount) { 22 | 23 | expect: 24 | def builder = new RandomSpanningTreeBuilder(randomDataGenerator) 25 | def tree = builder.createByRandomWalk(vertexCount) 26 | isATree(tree) 27 | 28 | where: 29 | vertexCount << [(0..10).collect { 30 | randomDataGenerator.nextInt(1, 10) 31 | }, [1] // Make sure this case is handled 32 | ].collectMany { it } 33 | // vertexCount << [2] 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/elementsofprogramminginterviews/binarytrees/TestIfABinaryTreeIsHeightBalancedSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.binarytrees 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class TestIfABinaryTreeIsHeightBalancedSpec extends Specification { 7 | 8 | @Unroll 9 | 'tests if binary tree is height balanced'( 10 | HashMap> tree, boolean isBalanced) { 11 | 12 | expect: 13 | def balanceTester = new TestIfABinaryTreeIsHeightBalanced() 14 | balanceTester.isBalanced(tree) == isBalanced 15 | 16 | where: 17 | [tree, isBalanced] << [ 18 | [[], true], 19 | [[0:[1]], true], 20 | [[0:[1], 1:[2]], false], 21 | [[0:[1,2]], true], 22 | [[0:[1,2], 1:[3]], true], 23 | [[0:[1,2], 1:[3,4], 3:[5]], false], 24 | ] 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/CountNumberOfUniquePlayPointSequencesThatResultInScoreSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class CountNumberOfUniquePlayPointSequencesThatResultInScoreSpec extends Specification { 7 | 8 | @Unroll 9 | """counts number of possible unique sequences of 10 | plays that result in a score"""( 11 | int score, int expected, List possiblePlayPoints) { 12 | 13 | expect: 14 | CountNumberOfUniquePlayPointSequencesThatResultInScore 15 | .sequenceCount(score, possiblePlayPoints) == expected 16 | 17 | where: 18 | [score, expected, possiblePlayPoints] << [ 19 | [0, 1], 20 | [1, 0], 21 | [2, 1], 22 | [3, 1], 23 | [4, 2], 24 | [5, 2], 25 | [6, 4], 26 | [7, 5], 27 | [8, 8], 28 | [9, 11] 29 | ].collect { 30 | it << [2,3,4] 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/interviewbit/dynamicprograming/simplearraydp/LengthOfLongestSubsequenceSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.interviewbit.dynamicprograming.simplearraydp 2 | 3 | import com.lagostout.interviewbit.dynamicprogramming.simplearraydp.LengthOfLongestSubsequence 4 | import spock.lang.Specification 5 | import spock.lang.Unroll 6 | 7 | class LengthOfLongestSubsequenceSpec extends Specification { 8 | 9 | @Unroll("list: #list expected: #expected") 10 | def 'lengthOfLongestSubsequence'(List list, int expected) { 11 | 12 | expect: 13 | def arg = ([list.size() as Integer] + list) as int[] 14 | LengthOfLongestSubsequence.compute(arg) == expected 15 | 16 | where: 17 | [list, expected] << [ 18 | [[], 0], 19 | [[1], 1], 20 | [[2,1], 2], 21 | [[1,2,1], 3], 22 | [[1,2], 0], 23 | ] 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/leetcode/IslandPerimeterSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.leetcode 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class IslandPerimeterSpec extends Specification { 7 | @Unroll 8 | 'calculate perimeter'(int[][] map, int expected) { 9 | expect: 10 | new IslandPerimeter().islandPerimeter(map) == expected 11 | where: 12 | [map, expected] << [ 13 | [[[1,1],[1,1]], 6], 14 | // [[[1]], 4], 15 | // [[[1,1]], 6], 16 | // [[[0,1,0,0], 17 | // [1,1,1,0], 18 | // [0,1,0,0], 19 | // [1,1,0,0]], 16], 20 | // [[[0,1,0,0], 21 | // [1,1,1,1], 22 | // [1,1,0,0]], 18] 23 | ] 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/leetcode/LoggerSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.leetcode 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class LoggerSpec extends Specification { 7 | 8 | @Unroll 9 | 'should print message'(List params, List expected) { 10 | 11 | when: 12 | def logger = new Logger() 13 | def result = [] 14 | println params 15 | params.forEach { 16 | println it 17 | result << logger.shouldPrintMessage2(it[0] as int, it[1] as String) 18 | } 19 | 20 | then: 21 | result == expected 22 | 23 | where: 24 | [params, expected] << [ 25 | [[[], [1, 'foo'], [2, 'bar'], 26 | // [3, 'foo'], [8, 'bar'], 27 | // [10, 'foo'], [11, 'foo'] 28 | ], [true, true, false, false, false, true]] 29 | ] 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/leetcode/MovingAverageSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.leetcode 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll; 5 | 6 | class MovingAverageSpec extends Specification { 7 | @Unroll 8 | 'computes moving average'(int window, 9 | List numbers, 10 | List expected) { 11 | def round = { 12 | double val -> Math.round(val * 100) / 100D 13 | } 14 | 15 | when: 16 | def average = new MovingAverage(window) 17 | List result = numbers.collect { 18 | //noinspection ChangeToOperator 19 | average.next(it) 20 | } 21 | 22 | then: 23 | result.collect(round) == expected.collect(round) 24 | 25 | where: 26 | [window, numbers, expected] << [ 27 | [3, [1,10,3,5], [1,11/2,14/3,18/3]] 28 | ] 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/leetcode/ReverseStringSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.leetcode 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class ReverseStringSpec extends Specification { 7 | 8 | @Unroll 9 | 'reverse string'(String str, String expected) { 10 | expect: 11 | new ReverseString().reverseString3(str) == expected 12 | where: 13 | [str, expected] << [ 14 | ['hello', 'olleh'], 15 | // ['',''] 16 | ] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/BinomialSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class BinomialSpec extends Specification { 7 | 8 | @Unroll('#n #k #expected') 9 | def 'binomial'(int n, int k, int expected) { 10 | expect: 11 | P22_Binomial.binomial(n,k) == expected 12 | where: 13 | [n, k, expected] << [ 14 | [0, 0, 1], 15 | [1, 0, 1], 16 | [1, 1, 1], 17 | [2, 0, 1], 18 | [2, 1, 2], 19 | [2, 2, 1], 20 | [3, 0, 1], 21 | [3, 1, 3], 22 | [3, 2, 3], 23 | [3, 3, 1], 24 | ] 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/ConvertNBSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class ConvertNBSpec extends Specification { 7 | @Unroll('#n #b #expected') 8 | def 'convert'(int n, int b, String expected) { 9 | expect: 10 | P24_ConvertNB.convert(n, b) == expected 11 | where: 12 | [n, b, expected] << [ 13 | [10, 2, '1010'], 14 | [16, 3, '121'], 15 | [20, 8, '24'] 16 | ] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/ConvertSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class ConvertSpec extends Specification { 7 | 8 | @Unroll('#n #expected') 9 | def 'convert'(int n, String expected) { 10 | expect: 11 | P23_Convert.convert(n) == expected 12 | where: 13 | [n, expected] << [ 14 | [0, '0'], 15 | [1, '1'], 16 | [2, '10'], 17 | [3, '11'], 18 | [13, '1101'] 19 | ] 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/GCDSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class GCDSpec extends Specification { 7 | 8 | @Unroll('#m #n #expected') 9 | def 'gcd'(int m, int n, int expected) { 10 | 11 | expect: 12 | P9_GCD.gcd(m, n) == expected 13 | 14 | where: 15 | [m, n, expected] << [ 16 | [5,3,1], 17 | [3,5,1], 18 | [6,3,3], 19 | [1,1,1] 20 | ] 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/InvNSumSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class InvNSumSpec extends Specification { 7 | @Unroll('#n #expected') 8 | def 'sum of n inverses'(int n, double expected) { 9 | expect: 10 | P12_InvNSum.invNSum(n) == expected 11 | where: 12 | [n, expected] << [ 13 | [1, 1], 14 | [2, 1.5] 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/IsPalindromeSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class IsPalindromeSpec extends Specification { 7 | 8 | @Unroll('#n #length #expected') 9 | def 'is palindrome'(int n, int length, boolean expected) { 10 | expect: 11 | P21_IsPalindrome.isPalindrome(n, length) == expected 12 | where: 13 | [n, length, expected] << [ 14 | [1, 1, true], 15 | [12, 2, false], 16 | [121, 3, true], 17 | [2222, 4, true], 18 | [22, 2, true], 19 | ] 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/NContainsKSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class NContainsKSpec extends Specification { 7 | 8 | @Unroll('#n #k') 9 | def 'n contains k'(int n, int k, boolean expected) { 10 | 11 | expect: 12 | P8_NContainsK.nContainsK(n, k) == expected 13 | 14 | where: 15 | [n, k, expected] << [ 16 | [1234, 4, true], 17 | [1234, 5, false], 18 | [0000, 0, true], 19 | [0000, 1, false], 20 | ] 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/NSumSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class NSumSpec extends Specification { 7 | 8 | @Unroll('#n #expected') 9 | def 'sum of first n'(int n, int expected) { 10 | 11 | expect: 12 | P10_NSum.nSum(n) == expected 13 | 14 | where: 15 | [n, expected] << [ 16 | [3, 6], 17 | [1, 1] 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/NumberOfDigitsSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class NumberOfDigitsSpec extends Specification { 7 | 8 | @Unroll('#n #expected') 9 | def 'number of digits'(int n, int expected) { 10 | expect: 11 | P7_NumberOfDigits.numberOfDigits(n) == expected 12 | 13 | where: 14 | [n, expected] << [ 15 | [0, 1], 16 | [11, 2], 17 | [9999, 4] 18 | ] 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/PowerSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PowerSpec extends Specification { 7 | 8 | @Unroll('#base #exponent #expected') 9 | def 'raise to power'(double base, int exponent, double expected) { 10 | 11 | expect: 12 | // P4_Power.power1(base, exponent) == expected 13 | // P4_Power.power2(base, exponent) == expected 14 | P4_Power.power3(base, exponent) == expected 15 | 16 | where: 17 | [base, exponent, expected] << [ 18 | [2, 0, 1], 19 | [2, 2, Math.pow(2, 2)], 20 | [2.5, 2, Math.pow(2.5, 2)] 21 | ] 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/Print1ToNSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class Print1ToNSpec extends Specification { 7 | 8 | @Unroll('#n #expected') 9 | def "print 1 to n"(int n, List expected) { 10 | 11 | expect: 12 | P2_Print1ToN.print1ToN(n) 13 | 14 | where: 15 | [n, expected] << [ 16 | [1, [1]], 17 | [2, [1,2]], 18 | [3, [1,2,3]] 19 | ] 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/PrintAExpTimesSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PrintAExpTimesSpec extends Specification { 7 | @Unroll('#n #expected') 8 | def 'print A exponent times'(int n, String expected) { 9 | expect: 10 | P29_PrintAExpTimes.printAExpTimes(n) == expected 11 | where: 12 | [n, expected] << [ 13 | [2, 'AAAA'], 14 | [3, 'AAAAAAAA'], 15 | [0, 'A'], 16 | [1, 'AA'] 17 | ] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/PrintAFactorialTimesSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PrintAFactorialTimesSpec extends Specification { 7 | @Unroll('#n #expected') 8 | def 'print A factorial times'(int n, String expected) { 9 | expect: 10 | P33_PrintAFactorialTimes.printAFactorialTimes(n) == expected 11 | where: 12 | [n, expected] << [ 13 | [2, 'AA'], 14 | [3, 'AAAAAA'], 15 | [1, 'A'] 16 | ] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/PrintALogNTimesSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PrintALogNTimesSpec extends Specification { 7 | 8 | @Unroll('#n #expected') 9 | def 'print A log N times'(int n, String expected) { 10 | expect: 11 | P27_PrintALogNTimes.printALogNTimes(n) == expected 12 | where: 13 | [n, expected] << [ 14 | [4, 'AA'], 15 | [0, ''], 16 | [1, ''] 17 | ] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/PrintCommasSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PrintCommasSpec extends Specification { 7 | @Unroll('#n #expected') 8 | def 'print commas'(long n, String expected) { 9 | expect: 10 | P28_PrintCommas.printCommas(n) == expected 11 | where: 12 | [n, expected] << [ 13 | [12345, '12,345'], 14 | [123, '123'], 15 | [1000, '1,000'], 16 | [1000000, '1,000,000'], 17 | [10, '10'] 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/PrintHelloSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PrintHelloSpec extends Specification { 7 | 8 | @Unroll('#n #expected') 9 | def 'print hello'(int n, String expected) { 10 | expect: 11 | // P1_PrintHello.printHello(n) == expected 12 | P1_PrintHello.printHello_moreRecursion(n) == expected 13 | where: 14 | [n, expected] << [ 15 | [2, "Hello_1_Hello_2_"], 16 | [1, "Hello_1_"], 17 | ] 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/PrintNDownTo1Spec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PrintNDownTo1Spec extends Specification { 7 | 8 | @Unroll('#n #expected') 9 | def "print n down to 1"(int n, List expected) { 10 | 11 | expect: 12 | P3_PrintNDownTo1.printNDownTo1(n) == expected 13 | 14 | where: 15 | [n, expected] << [ 16 | [3,[3,2,1]], 17 | [1,[1]], 18 | ] 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/PrintReverseSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PrintReverseSpec extends Specification { 7 | 8 | @Unroll 9 | def 'print reverse'(int n, int expected) { 10 | expect: 11 | P20_PrintReverse.printReverse(n) == expected 12 | where: 13 | [n, expected] << [ 14 | [1, 1], 15 | [12, 21], 16 | [21, 12] 17 | ] 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch1_examplesonintegers/SumSquaresSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch1_examplesonintegers 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class SumSquaresSpec extends Specification { 7 | 8 | @Unroll('#n') 9 | def 'sums squares'(int n, int expected) { 10 | expect: 11 | P11_SumSquares.sumSquares(n) == expected 12 | where: 13 | [n, expected] << [ 14 | [2, 5], 15 | [3, 14] 16 | ] 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/BinarySearchSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class BinarySearchSpec extends Specification { 7 | @Unroll('#a #key #expected') 8 | def 'binary search'(int[] a, int key, int expected) { 9 | expect: 10 | P22_BinarySearch.binarySearch(a, key, 0, a.length - 1) == expected 11 | where: 12 | [a, key, expected] << [ 13 | [[1,2,3,4], 2, 1], 14 | // [[1,2,3,4], 5, -1], 15 | [[1,2,3,4], 5, 3], 16 | [[1,2], 1, 0], 17 | [[2], 2, 0], 18 | [[2], 1, -1], 19 | [[2,4], 3, 0], 20 | [[2,4], 5, 2] 21 | // [[2], 1, -1], 22 | ] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/BubbleSortSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class BubbleSortSpec extends Specification { 7 | @Unroll('#a #expected') 8 | def 'bubble sort'(int[] a, int[] expected) { 9 | expect: 10 | P20_BubbleSort.bubbleSort(a, a.length) 11 | a == expected 12 | where: 13 | [a, expected] << [ 14 | [[4,3,2,1], [1,2,3,4]], 15 | [[1],[1]] 16 | ] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/InsertionSortSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class InsertionSortSpec extends Specification { 7 | @Unroll('#a #expected') 8 | def 'insertion sort'(int[] a, int[] expected) { 9 | expect: 10 | P19_InsertionSort.insertionSort(a, a.length) 11 | a == expected 12 | where: 13 | [a, expected] << [ 14 | [[4,3,2,1], [1,2,3,4]], 15 | [[2,0,1,0], [0,0,1,2]], 16 | ] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/PrintArraySpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class PrintArraySpec extends Specification { 7 | @Unroll('#a #n #expected') 8 | def 'print array'(int[] a, int n, String expected) { 9 | expect: 10 | P1_PrintArray.printArray(a, n) == expected 11 | where: 12 | [a, n, expected] << [ 13 | [[1,2,3], 3, '1 2 3'], 14 | [[1], 1, '1'] 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/practicingrecursioninjava/ch2_examplesonarrays/SelectionSortSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.lagostout.practicingrecursioninjava.ch2_examplesonarrays 2 | 3 | import spock.lang.Specification 4 | import spock.lang.Unroll 5 | 6 | class SelectionSortSpec extends Specification { 7 | @Unroll('#a #expected') 8 | def 'selection sort'(int[] a, int[] expected) { 9 | expect: 10 | P18_SelectionSort.selectionSort(a, a.length) 11 | a == expected 12 | where: 13 | [a, expected] << [ 14 | [[4,3,2,1], [1,2,3,4]], 15 | [[2,0,1,0], [0,0,1,2]], 16 | ] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/src/test/groovy/com/lagostout/scratch/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/bytebybyte/dynamicprogramming/LongestIncreasingSubsequenceSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.dynamicprogramming 2 | 3 | import com.lagostout.bytebybyte.dynamicprogramming.LongestIncreasingSubsequence.computeWithBruteForceAndRecursion 4 | import org.assertj.core.api.Assertions.assertThat 5 | import org.jetbrains.spek.api.Spek 6 | import org.jetbrains.spek.api.dsl.describe 7 | import org.jetbrains.spek.api.dsl.it 8 | import org.jetbrains.spek.data_driven.data 9 | import org.jetbrains.spek.data_driven.on 10 | 11 | object LongestIncreasingSubsequenceSpek : Spek({ 12 | 13 | val data = listOfNotNull( 14 | data(listOf(1,4,2,3,5), listOf(1,2,3,5)), 15 | data(listOf(10,22,9,33,21,50,41,60), 16 | listOf(10,22,33,50,60)), 17 | null 18 | ).toTypedArray() 19 | 20 | describe("computeWithBruteForceAndRecursion") { 21 | on("integers: %s", with = *data) { integers, expected -> 22 | it("returns $expected") { 23 | assertThat(computeWithBruteForceAndRecursion( 24 | integers)).isEqualTo(expected.size) 25 | } 26 | } 27 | } 28 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/bytebybyte/recursion/PermutationsSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.recursion 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object PermutationsSpek : Spek({ 11 | 12 | val data = listOfNotNull( 13 | data(listOf(1), listOf(listOf(1))), 14 | data(listOf(1,2), listOf(listOf(1,2), listOf(2,1))), 15 | data(listOf(1,2,3), listOf(listOf(1,2,3), listOf(1,3,2), listOf(2,1,3), 16 | listOf(2,3,1), listOf(3,1,2), listOf(3,2,1))), 17 | null 18 | ).toTypedArray() 19 | 20 | describe("permutations") { 21 | on("numbers: %s", with = *data) { numbers, expected -> 22 | it("should return $expected") { 23 | assertThat(permutations(numbers)) 24 | .isEqualTo(expected) 25 | } 26 | } 27 | } 28 | 29 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/bytebybyte/recursion/PrintOddIndicesOfIntegerArraySpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.bytebybyte.recursion 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object PrintOddIndicesOfIntegerArraySpek : Spek({ 11 | 12 | fun computeByIteration(numbers: Array): List { 13 | return numbers.withIndex().mapNotNull { 14 | if (it.index % 2 == 1) it.value 15 | else null 16 | } 17 | } 18 | 19 | val data = listOfNotNull( 20 | arrayOf(0,1,2), 21 | arrayOf(0,1,2,3,4,5), 22 | null 23 | ).map { 24 | data(it, computeByIteration(it)) 25 | }.toTypedArray() 26 | 27 | describe("printOddIndicesOfIntegerArray") { 28 | on("numbers %s", with = *data) { numbers, expected -> 29 | it("should return $expected") { 30 | assertThat(printOddIndicesOfIntegerArray(numbers)) 31 | .isEqualTo(expected) 32 | } 33 | } 34 | } 35 | 36 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/IncrementArbitraryPrecisionIntegerSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | import org.jetbrains.spek.api.Spek 4 | import org.jetbrains.spek.api.dsl.describe 5 | import org.jetbrains.spek.api.dsl.it 6 | import org.jetbrains.spek.data_driven.data 7 | import org.jetbrains.spek.data_driven.on 8 | import kotlin.test.assertEquals 9 | 10 | object IncrementArbitraryPrecisionIntegerSpek : Spek({ 11 | describe("incrementInteger()") { 12 | val data = listOf( 13 | data(listOf(0), listOf(1)), 14 | data(listOf(1), listOf(2)), 15 | data(listOf(0,9), listOf(1,0)), 16 | data(listOf(0,9,9), listOf(1,0,0)), 17 | data(listOf(0,3,9), listOf(0,4,0)), 18 | null 19 | ).filterNotNull().toTypedArray() 20 | on("integer: %s", with = *data) { integer, expected -> 21 | it("returns $expected") { 22 | val integer = integer.toMutableList() 23 | incrementInteger(integer) 24 | assertEquals(expected, integer) 25 | } 26 | } 27 | } 28 | }) 29 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/NextPermutationSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.data_driven.data 7 | import org.jetbrains.spek.data_driven.on 8 | 9 | object NextPermutationSpek : Spek({ 10 | 11 | val data = listOfNotNull( 12 | data(emptyList(), emptyList()), 13 | data(listOf(3), listOf(3)), 14 | data(listOf(2,1,3), listOf(2,3,1)), 15 | data(listOf(1,3,2), listOf(2,1,3)), 16 | data(listOf(1,0,3,2,1,0), listOf(1,1,0,0,2,3)), 17 | null 18 | ).toTypedArray() 19 | 20 | describe("nextPermutation") { 21 | on("permutation %s", with = *data) { permutation, expected -> 22 | assertThat(nextPermutation(permutation)) 23 | .isEqualTo(expected) 24 | } 25 | } 26 | 27 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/arrays/PrimesToNSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.arrays 2 | 3 | import org.apache.commons.math3.primes.Primes 4 | import org.assertj.core.api.Assertions.assertThat 5 | import org.jetbrains.spek.api.Spek 6 | import org.jetbrains.spek.api.dsl.describe 7 | import org.jetbrains.spek.api.dsl.it 8 | import org.jetbrains.spek.data_driven.data 9 | import org.jetbrains.spek.data_driven.on 10 | 11 | object PrimesToNSpek : Spek({ 12 | 13 | val data = (2..20).map { n -> 14 | data(n, (2..n).mapNotNull { candidate -> 15 | if (Primes.isPrime(candidate)) candidate else null }) 16 | }.toTypedArray() 17 | 18 | describe("primesToN") { 19 | on("n %s", with = * data) { n, expected -> 20 | val primes = primesToN(n) 21 | it("should return $expected") { 22 | assertThat(primes).isEqualTo(expected) 23 | } 24 | } 25 | } 26 | 27 | }) 28 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/binarytrees/testnamespace.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.binarytrees 2 | 3 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/KnapsackProblemWithAchievableWeightSpaceComplexitySpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | import com.lagostout.elementsofprogramminginterviews.dynamicprogramming.KnapsackProblemSpek.randomData 4 | import com.lagostout.elementsofprogramminginterviews.dynamicprogramming.KnapsackProblemWithAchievableWeightSpaceComplexity.computeBottomUpWithMemoization 5 | import org.assertj.core.api.Assertions.assertThat 6 | import org.jetbrains.spek.api.Spek 7 | import org.jetbrains.spek.api.dsl.describe 8 | import org.jetbrains.spek.api.dsl.given 9 | import org.jetbrains.spek.api.dsl.it 10 | 11 | object KnapsackProblemWithAchievableWeightSpaceComplexitySpek : Spek({ 12 | 13 | describe("computeBottomUpWithMemoization") { 14 | randomData.forEach { (clocks, capacity, expected) -> 15 | given("clocks $clocks, capacity: $capacity") { 16 | it("should be $expected") { 17 | assertThat(computeBottomUpWithMemoization( 18 | capacity, clocks)) 19 | .isEqualTo(expected) 20 | } 21 | } 22 | } 23 | } 24 | 25 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/KnapsackProblemWithWeightSpaceComplexitySpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | import com.lagostout.elementsofprogramminginterviews.dynamicprogramming.KnapsackProblemSpek.randomData 4 | import com.lagostout.elementsofprogramminginterviews.dynamicprogramming.KnapsackProblemWithWeightSpaceComplexity.computeBottomUpWithMemoization 5 | import org.assertj.core.api.Assertions.assertThat 6 | import org.jetbrains.spek.api.Spek 7 | import org.jetbrains.spek.api.dsl.describe 8 | import org.jetbrains.spek.api.dsl.given 9 | import org.jetbrains.spek.api.dsl.it 10 | 11 | object KnapsackProblemWithWeightSpaceComplexitySpek : Spek({ 12 | 13 | describe("computeBottomUpWithMemoization") { 14 | randomData.forEach { (clocks, capacity, expected) -> 15 | given("clocks $clocks, capacity: $capacity") { 16 | it("should be $expected") { 17 | assertThat(computeBottomUpWithMemoization( 18 | capacity, clocks)) 19 | .isEqualTo(expected) 20 | } 21 | } 22 | } 23 | } 24 | 25 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/LevenshteinDistanceOfBestRegexMatchSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | import org.jetbrains.spek.api.Spek 4 | 5 | object LevenshteinDistanceOfBestRegexMatchSpek : Spek({ 6 | 7 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/LongestNondecreasingSubsequenceInNLogNTimeSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/NumberOfWaysToTraverse2DArraySpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object NumberOfWaysToTraverse2DArraySpek : Spek({ 11 | describe("numberOfWaysToTraverse2DArray()") { 12 | val data = listOfNotNull( 13 | data(1,1,1), 14 | data(1,2,1), 15 | data(2,1,1), 16 | data(2,2,2), 17 | data(2,3,3), 18 | data(4,4,20), 19 | data(5,5,70), 20 | null 21 | ).toTypedArray() 22 | on("array: %sx%s", with = *data) { 23 | rowCount, columnCount, expected -> 24 | it("returns $expected") { 25 | assertThat(numberOfWaysToTraverse2DArray(rowCount, columnCount)) 26 | .isEqualTo(expected) 27 | } 28 | } 29 | } 30 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/NumberOfWaysToTraverse2DArrayWithLessSpaceSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object NumberOfWaysToTraverse2DArrayWithLessSpaceSpek : Spek({ 11 | describe("numberOfWaysToTraverse2DArray()") { 12 | val data = listOfNotNull( 13 | data(1,1,1), 14 | data(1,2,1), 15 | data(2,1,1), 16 | data(2,2,2), 17 | data(2,3,3), 18 | data(4,4,20), 19 | data(5,5,70), 20 | null 21 | ).toTypedArray() 22 | on("array: %sx%s", with = *data) { 23 | rowCount, columnCount, expected -> 24 | it("returns $expected") { 25 | assertThat(numberOfWaysToTraverse2DArrayWithLessSpace( 26 | rowCount, columnCount)).isEqualTo(expected) 27 | } 28 | } 29 | } 30 | }) 31 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/dynamicprogramming/RegexMatchWithMinimumLevenshteinDistanceSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.dynamicprogramming 2 | 3 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/hashtables/ImplementHashFunctionForChessSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/hashtables/TestCollatzConjectureSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.hashtables 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.given 7 | import org.jetbrains.spek.api.dsl.it 8 | 9 | object TestCollatzConjectureSpek : Spek({ 10 | describe("testCollatzConjecture()") { 11 | val numberCount = 10_000_000 12 | given("first $numberCount positive numbers") { 13 | it("returns true") { 14 | assertThat(testCollatzConjecture(numberCount)) 15 | .isEqualTo(true) 16 | } 17 | } 18 | } 19 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/honors/FindFirstMissingPositiveEntrySpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.honors 2 | 3 | import org.jetbrains.spek.api.Spek 4 | import org.jetbrains.spek.api.dsl.describe 5 | import org.jetbrains.spek.api.dsl.it 6 | import org.jetbrains.spek.data_driven.data 7 | import org.jetbrains.spek.data_driven.on 8 | import kotlin.test.assertEquals 9 | 10 | object FindFirstMissingPositiveEntrySpek : Spek({ 11 | describe("findFirstMissingPositiveEntry()") { 12 | val data = listOf( 13 | data(mutableListOf(3,5,4,-1,5,1,-1), expected = 2), 14 | data(mutableListOf(1,2,3,4,5), expected = 6), 15 | data(mutableListOf(1,2,3,4,4), expected = 5), 16 | data(mutableListOf(4,4,1,2,3), expected = 5), 17 | data(mutableListOf(1,3,5,7,2,4), expected = 6), 18 | data(mutableListOf(1,1,2,4,2,2), expected = 3), 19 | null 20 | ).filterNotNull().toTypedArray() 21 | on("array: %s", with = *data) { array, expected -> 22 | it("returns $expected") { 23 | assertEquals(expected, findFirstMissingPositiveEntry(array)) 24 | } 25 | } 26 | } 27 | }) 28 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/honors/IdentifyPositionsAttackedByRooksSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.honors 2 | 3 | import org.jetbrains.spek.api.Spek 4 | 5 | object IdentifyPositionsAttackedByRooksSpek : Spek({ 6 | 7 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/honors/JustifyTextSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.honors 2 | 3 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/EvenOddMergeSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | import com.lagostout.kotlin.common.Alphabet.* 4 | import org.assertj.core.api.Assertions.assertThat 5 | import org.jetbrains.spek.api.Spek 6 | import org.jetbrains.spek.api.dsl.describe 7 | import org.jetbrains.spek.api.dsl.it 8 | import org.jetbrains.spek.data_driven.data 9 | import org.jetbrains.spek.data_driven.on 10 | 11 | object EvenOddMerge : Spek({ 12 | 13 | val data = listOfNotNull( 14 | data(toLinkedList(A), toLinkedList(A)), 15 | data(toLinkedList(A,B), toLinkedList(A,B)), 16 | data(toLinkedList(A,B,C), toLinkedList(A,C,B)), 17 | data(toLinkedList(A,B,C,D), toLinkedList(A,C,B,D)), 18 | data(toLinkedList(A,B,C,D,E), toLinkedList(A,C,E,B,D)), 19 | null 20 | ).toTypedArray() 21 | 22 | describe("evenOddMerge") { 23 | on("list %s", with = *data) { list, expected -> 24 | evenOddMerge(list) 25 | it("should transform the list to $expected") { 26 | assertThat(list).isEqualToComparingOnlyGivenFields("value") 27 | } 28 | } 29 | } 30 | 31 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/RemoveDuplicatesFromSortedListSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object RemoveDuplicatesFromSortedListSpek : Spek({ 11 | describe("removeDuplicatesFromSortedList") { 12 | val data = listOfNotNull( 13 | listOf(1), 14 | listOf(1,2), 15 | listOf(1,1,2), 16 | listOf(1,1,2,2,2,3), 17 | null 18 | ).map { 19 | data(toLinkedList(it), it.distinct().let(::toLinkedList)) 20 | }.toTypedArray() 21 | on("list: %s", with = *data) { list, expected -> 22 | it("returns $expected") { 23 | removeDuplicatesFromSortedList(list) 24 | assertThat(list).isEqualToIgnoringGivenFields(expected, "id", "next") 25 | } 26 | } 27 | } 28 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/ReverseListSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | import org.jetbrains.spek.api.Spek 4 | import org.jetbrains.spek.api.dsl.describe 5 | import org.jetbrains.spek.api.dsl.it 6 | import org.jetbrains.spek.data_driven.data 7 | import org.jetbrains.spek.data_driven.on 8 | import kotlin.test.assertEquals 9 | 10 | class ReverseListSpek : Spek({ 11 | describe("reverseSingleSublist()") { 12 | val data = listOfNotNull(data(toLinkedList(listOf(1)), 13 | expected = toLinkedList(listOf(1))), data(toLinkedList(listOf(1, 2)), 14 | expected = toLinkedList(listOf(2,1))), data(toLinkedList(listOf(1, 2, 3)), 15 | expected = toLinkedList(listOf(3, 2, 1))), null).toTypedArray() 16 | on("list: %s", with = *data) { list, expected -> 17 | it("returns $expected") { 18 | val head = reverseList(list) 19 | assertEquals(expected, head) 20 | } 21 | } 22 | } 23 | }) 24 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/linkedlists/TestIfListIsPalindromicSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.linkedlists 2 | 3 | import com.lagostout.kotlin.common.Alphabet.* 4 | import org.assertj.core.api.Assertions.assertThat 5 | import org.jetbrains.spek.api.Spek 6 | import org.jetbrains.spek.api.dsl.describe 7 | import org.jetbrains.spek.api.dsl.it 8 | import org.jetbrains.spek.data_driven.data 9 | import org.jetbrains.spek.data_driven.on 10 | 11 | object TestIfListIsPalindromicSpek : Spek({ 12 | 13 | val data = listOfNotNull( 14 | data(toLinkedList(A), true), 15 | data(toLinkedList(A,B), false), 16 | data(toLinkedList(A,B,A), true), 17 | data(toLinkedList(A,B,B,A), true), 18 | data(toLinkedList(A,B,B,A,C), false), 19 | data(toLinkedList(A,C,B,B,A), false), 20 | null 21 | ).toTypedArray() 22 | 23 | describe("listIsPalindromic") { 24 | on("list %s", with = *data) { list, expected -> 25 | val isPalindromic = listIsPalindromic(list) 26 | it("should return $expected") { 27 | assertThat(isPalindromic).isEqualTo(expected) 28 | } 29 | } 30 | } 31 | 32 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/ComputeXToPowerYSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | import kotlin.math.pow 10 | 11 | object ComputeXToPowerYSpek : Spek({ 12 | 13 | val data = listOfNotNull( 14 | Pair(1.0, 1), 15 | Pair(1.0, 2), 16 | Pair(2.0, 1), 17 | Pair(2.0, 2), 18 | Pair(2.0, 3), 19 | Pair(3.0, 1), 20 | Pair(3.0, 3), 21 | Pair(3.0, 4), 22 | Pair(3.0, 5), 23 | Pair(3.0, 7), 24 | Pair(3.0, 8), 25 | null 26 | ).map { (x, y) -> 27 | data(x, y, x.pow(y)) 28 | }.toTypedArray() 29 | 30 | describe("computeXToPowerY") { 31 | on("x: %s, y: %s", with = *data) { x, y, expected -> 32 | it("should return $expected") { 33 | assertThat(computeXToPowerY(x, y)) 34 | .isEqualTo(expected) 35 | } 36 | } 37 | } 38 | 39 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/DivideSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object DivideSpek : Spek({ 11 | 12 | val data = listOfNotNull( 13 | data(1,1,1), 14 | data(1,2,0), 15 | data(0,2,0), 16 | data(2,2,1), 17 | data(5,2,2), 18 | data(8,2,4), 19 | data(11,2,5), 20 | data(13,2,6), 21 | data(13,3,4), 22 | data(17,5,3), 23 | null 24 | ).toTypedArray() 25 | 26 | describe("divide") { 27 | on("x %s y %s", with = *data) { x, y, expected -> 28 | val result = divide(x, y) 29 | it("should return $expected") { 30 | assertThat(result).isEqualTo(expected) 31 | } 32 | } 33 | } 34 | 35 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/ParityOfAWordSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | import org.jetbrains.spek.api.Spek 4 | import org.jetbrains.spek.api.dsl.describe 5 | import org.jetbrains.spek.api.dsl.it 6 | import org.jetbrains.spek.data_driven.data 7 | import org.jetbrains.spek.data_driven.on 8 | import kotlin.test.assertEquals 9 | 10 | object ParityOfAWordSpek : Spek({ 11 | describe("computeParity()") { 12 | val data = listOf( 13 | data(listOf(), expected = listOf()), 14 | data(listOf(0), expected = listOf(0)), 15 | data(listOf(0,3,5,7,11), expected = listOf(0,0,0,1,1)), 16 | null 17 | ).filterNotNull().toTypedArray() 18 | on("compute parity of words %s", with = *data) { words, expected -> 19 | it("returns $expected") { 20 | assertEquals(expected, computeParity(words)) 21 | } 22 | } 23 | } 24 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/primitivetypes/ReverseDigitsSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.primitivetypes 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object ReverseDigitsSpek : Spek({ 11 | 12 | val data = listOfNotNull( 13 | data(0, 0), 14 | data(1, 1), 15 | data(-1, -1), 16 | data(12, 21), 17 | data(-12, -21), 18 | null 19 | ).toTypedArray() 20 | 21 | describe("reverseDigits2") { 22 | on("number %s", with = *data) { number, expected -> 23 | it("should return $expected") { 24 | assertThat(reverseDigits2(number)) 25 | .isEqualTo(expected) 26 | } 27 | } 28 | } 29 | 30 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/recursion/towersofhanoi/TowersOfHanoiMinimumOperationsWithFourPegsSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.recursion.towersofhanoi 2 | 3 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/searching/ComputeIntegerSquareRootSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object ComputeIntegerSquareRootSpek : Spek({ 11 | describe("computeIntegerSquareRoot") { 12 | val data = listOfNotNull( 13 | data(1, 1), 14 | data(2, 1), 15 | data(3, 1), 16 | data(4, 2), 17 | data(5, 2), 18 | data(7, 2), 19 | data(9, 3), 20 | data(300, 17), 21 | null 22 | ).toTypedArray() 23 | on("integer: %s", with = *data) { integer, expected -> 24 | it("returns: $expected") { 25 | assertThat(computeIntegerSquareRoot(integer)) 26 | .isEqualTo(expected) 27 | } 28 | } 29 | } 30 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/searching/ComputeRealSquareRootSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object ComputeRealSquareRootSpek : Spek({ 11 | describe("computeRealSquareRoot()") { 12 | val data = listOfNotNull( 13 | 0.001, 14 | 0.5, 15 | 1.0, 16 | 5.2, 17 | null 18 | ).map { 19 | data(it, Math.sqrt(it)) 20 | }.toTypedArray() 21 | on("number: %s", with = *data) { number, expected -> 22 | it("returns: $expected") { 23 | val epsilon = 0.00001 24 | assertThat(computeRealSquareRoot(number, epsilon)) 25 | .isBetween(expected - epsilon, expected + epsilon) 26 | } 27 | } 28 | } 29 | }) 30 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/searching/FindMaxInAscendingDescendingSequencesSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.searching 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object FindMaxInAscendingDescendingSequencesSpek : Spek({ 11 | describe("findMaxInAscDescSequences()") { 12 | val data = listOf( 13 | data(listOf(1,1), 1), 14 | data(listOf(1,1), 1), 15 | data(listOf(1,2,1), 2), 16 | data(listOf(3,4,2,1), 4), 17 | data(listOf(3,4,5,2,1), 5), 18 | data(listOf(3,4,5,4,3), 5), 19 | data(listOf(3,4,5,4,3,1), 5), 20 | null 21 | ).filterNotNull().toTypedArray() 22 | on("sequences: %s", with = *data) { sequences, expected -> 23 | it("returns $expected") { 24 | assertThat(findMaxInAscDescSequences(sequences)) 25 | .isEqualTo(expected) 26 | } 27 | } 28 | } 29 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/stacksandqueues/testnamespace.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.stacksandqueues 2 | 3 | import com.lagostout.datastructures.RawBinaryTreeNode 4 | 5 | typealias RBT = RawBinaryTreeNode 6 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/strings/ComputeMnemonicsForPhoneNumberSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/strings/LookAndSayProblemSpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object LookAndSayProblemSpek : Spek({ 11 | describe("computeLookAndSaySequence()") { 12 | val data = listOf( 13 | data(1,"1"), 14 | data(2, "11"), 15 | data(3, "21"), 16 | data(4, "1211"), 17 | data(5, "111221"), 18 | data(6, "312211"), 19 | data(7, "13112221"), 20 | data(8, "1113213211"), 21 | null 22 | ).filterNotNull().toTypedArray() 23 | on("n: %s", with = *data) { n, expected -> 24 | it("returns $expected") { 25 | assertThat(computeLookAndSaySequence(n)) 26 | .isEqualTo(expected) 27 | } 28 | } 29 | } 30 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/strings/TestPalindromicitySpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | import org.jetbrains.spek.api.Spek 4 | import org.jetbrains.spek.api.dsl.describe 5 | import org.jetbrains.spek.api.dsl.it 6 | import org.jetbrains.spek.data_driven.data 7 | import org.jetbrains.spek.data_driven.on 8 | import kotlin.test.assertEquals 9 | 10 | object TestPalindromicitySpek : Spek({ 11 | describe("testPalindromicity()") { 12 | val data = listOf( 13 | data("A man, a plan, a canal, Panama", expected = true), 14 | data("ab", expected = false), 15 | data("a b", expected = false), 16 | data("Ray a Ray", expected = false), 17 | data("Ray a a Yar", expected = true), 18 | data("Ray a d Yar", expected = false), 19 | null 20 | ).filterNotNull().toTypedArray() 21 | on("string: %s", with = *data) { string, expected -> 22 | it("detects palindromicity is $expected") { 23 | assertEquals(expected, testPalindromicity(string)) 24 | } 25 | } 26 | } 27 | }) -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/elementsofprogramminginterviews/strings/WriteStringSinusoidallySpek.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.elementsofprogramminginterviews.strings 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.describe 6 | import org.jetbrains.spek.api.dsl.it 7 | import org.jetbrains.spek.data_driven.data 8 | import org.jetbrains.spek.data_driven.on 9 | 10 | object WriteStringSinusoidallySpek : Spek({ 11 | 12 | @Suppress("SpellCheckingInspection") 13 | val data = listOfNotNull( 14 | data("Hello", "eHlol"), 15 | data("Hello ", "e Hlol"), 16 | data("Hello World!", "e lHloWrdlo!"), 17 | null 18 | ).toTypedArray() 19 | 20 | describe("writeStringSinusoidally") { 21 | on("string: %s", with = *data) { string, expected -> 22 | it("should return $expected") { 23 | assertThat(writeStringSinusoidally(string)) 24 | .isEqualTo(expected) 25 | } 26 | } 27 | } 28 | 29 | }) 30 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/kotlin/common/namespace.kt: -------------------------------------------------------------------------------- 1 | package com.lagostout.kotlin.common 2 | 3 | enum class Alphabet : Comparable { 4 | A, B, C, D, E, F, G, H, I, J, K, L, M 5 | } 6 | -------------------------------------------------------------------------------- /java/src/test/kotlin/com/lagostout/scratch/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore -------------------------------------------------------------------------------- /java/src/test/resources/expectedresults/CostCutting.txt: -------------------------------------------------------------------------------- 1 | Case 1: 4560 2 | Case 2: 6698 3 | Case 3: 7304 4 | Case 4: 6191 5 | Case 5: 4192 6 | Case 6: 6170 7 | Case 7: 7724 8 | Case 8: 10000 9 | Case 9: 4979 10 | Case 10: 8715 11 | Case 11: 2036 12 | Case 12: 4975 13 | Case 13: 3705 14 | Case 14: 1530 15 | Case 15: 4025 16 | Case 16: 2122 17 | Case 17: 7109 18 | Case 18: 1000 19 | Case 19: 5887 20 | -------------------------------------------------------------------------------- /java/src/test/resources/expectedresults/DivisionOfNlogonia.txt: -------------------------------------------------------------------------------- 1 | NE 2 | SO 3 | SO 4 | NO 5 | NO 6 | NO 7 | NE 8 | NO 9 | SO 10 | SE 11 | SE 12 | SO 13 | SE 14 | SE 15 | NE 16 | NE 17 | NE 18 | SO 19 | SE 20 | SO 21 | NO 22 | NO 23 | NE 24 | SE 25 | SE 26 | SO 27 | NO 28 | NO 29 | NO 30 | SO 31 | SO 32 | SO 33 | NE 34 | NO 35 | NO 36 | NE 37 | SE 38 | NE 39 | NE 40 | SE 41 | NE 42 | SE 43 | NE 44 | NE 45 | SO 46 | SO 47 | SO 48 | NO 49 | NE 50 | NE 51 | NE 52 | NE 53 | NE 54 | SE 55 | NO 56 | NO 57 | NO 58 | SO 59 | SO 60 | SE 61 | SO 62 | SO 63 | SE 64 | SO 65 | SO 66 | NE 67 | NO 68 | SE 69 | SE 70 | SE 71 | SE 72 | NE 73 | NE 74 | NO 75 | NO 76 | NO 77 | SE 78 | SE 79 | SE 80 | SE 81 | SE 82 | SE 83 | NO 84 | NO 85 | NO 86 | NO 87 | NE 88 | SO 89 | NO 90 | NO 91 | SO 92 | SE 93 | SE 94 | NE 95 | NE 96 | NE 97 | NE 98 | NE 99 | SE 100 | -------------------------------------------------------------------------------- /java/src/test/resources/tests/CostCutting.txt: -------------------------------------------------------------------------------- 1 | 19 2 | 8796 4560 4165 3 | 6698 7621 2135 4 | 4082 7304 8245 5 | 4381 6191 6792 6 | 1764 8296 4192 7 | 6170 9287 3611 8 | 9939 3825 7724 9 | 10000 10000 10000 10 | 7592 4979 1734 11 | 8715 1507 9196 12 | 3867 2036 1717 13 | 3458 4975 7554 14 | 7301 2666 3705 15 | 1924 1530 1176 16 | 4025 3269 7171 17 | 4585 2122 1522 18 | 7109 7832 3684 19 | 1000 1000 1000 20 | 6380 1693 5887 21 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/AddDigits.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | /// [Problem description](https://leetcode.com/problems/add-digits/) 6 | 7 | class AddDigits { 8 | func addDigits(_ num: Int) -> Int { 9 | let numMod9 = num % 9 10 | return num != 0 && numMod9 == 0 ? 9 : numMod9 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/CodingPractice.h: -------------------------------------------------------------------------------- 1 | // 2 | // CodingPractice.h 3 | // CodingPractice 4 | // 5 | // Created by julian abiodun on 1/17/17. 6 | // Copyright © 2017 lagostout. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | //! Project version number for CodingPractice. 12 | FOUNDATION_EXPORT double CodingPracticeVersionNumber; 13 | 14 | //! Project version string for CodingPractice. 15 | FOUNDATION_EXPORT const unsigned char CodingPracticeVersionString[]; 16 | 17 | // In this header, you should import all the public headers of your framework using statements like #import 18 | 19 | 20 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/FindDisappearedNumbers.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | 4 | /// [Problem description](https://leetcode.com/problems/find-all-mutableNumsbers-disappeared-in-an-array) 5 | 6 | class FindDisappearedNumbers { 7 | func findDisappearedNumbers(_ nums: [Int]) -> [Int] { 8 | if nums.count == 0 { 9 | return [] 10 | } 11 | var nums = Array(nums) 12 | for num in nums { 13 | let index = num - 1 14 | if (nums[index] > 0) { 15 | nums[index] = -nums[index] 16 | } 17 | } 18 | var missingNums:[Int] = [] 19 | for index in (0...nums.count-1) { 20 | let num = nums[index] 21 | if (num > 0) { 22 | missingNums += [index + 1] 23 | } 24 | } 25 | return missingNums 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/FlipGame.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | /// [Problem description](https://leetcode.com/problems/flip-game) 6 | 7 | class FlipGame { 8 | 9 | func generatePossibleNextMoves(_ s: String) -> [String] { 10 | var result = [String]() 11 | if s.count > 1 { 12 | for start in s.indices where start < s.index(s.endIndex, offsetBy:-1) { 13 | let end = s.index(start, offsetBy:2) 14 | let range = start ..< end 15 | if (s[range] == "++") { 16 | let state = s.replacingCharacters(in: range, with: "--") 17 | result.append(state) 18 | } 19 | } 20 | } 21 | return result 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/HammingDistance.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// [Problem description](https://leetcode.com/problems/hamming-distance) 4 | 5 | open class HammingDistance { 6 | 7 | func hammingDistance(_ x: Int, _ y: Int) -> Int { 8 | let z:Int = x ^ y 9 | return bitCount(z) 10 | } 11 | 12 | func bitCount(_ n: Int)->Int { 13 | var bitCount = 0 14 | var n1 = n 15 | for _:Int in 1...32 { 16 | if n1 & 1 == 1 { bitCount += 1 } 17 | n1 = (n1 >> 1) 18 | } 19 | return bitCount 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | $(CURRENT_PROJECT_VERSION) 21 | NSHumanReadableCopyright 22 | Copyright © 2017 lagostout. All rights reserved. 23 | NSPrincipalClass 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/IntersectionOfTwoArrays.swift: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | /// [Problem](https://leetcode.com/problems/intersection-of-two-arrays/#/description) 6 | 7 | class IntersectionOfTwoArrays { 8 | 9 | func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 10 | return Array(Set(nums1).intersection(Set(nums2))) 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/MaxConsecutiveOnes.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | class MaxConsecutiveOnes { 6 | func findMaxConsecutiveOnes(_ nums: [Int]) -> Int { 7 | var count = 0 8 | var currentCount = 0 9 | for num in nums { 10 | if (num == 0) { 11 | count = currentCount > count ? currentCount : count 12 | currentCount = 0 13 | } else { 14 | currentCount += 1 15 | } 16 | } 17 | count = currentCount > count ? currentCount : count 18 | return count 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/MinimumMovesToEqualArrayElements.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | /// [Problem description](https://leetcode.com/problems/minimum-moves-to-equal-array-elements) 6 | 7 | class MinimumMovesToEqualArrayElements { 8 | 9 | func minMoves(_ nums: [Int]) -> Int { 10 | var sum = 0 11 | var minVal = Int.max 12 | for num in nums { 13 | sum += num 14 | if (minVal > num) { minVal = num } 15 | } 16 | let moves = sum - minVal * nums.count 17 | return moves 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/NimGame.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | // https://leetcode.com/problems/nim-game 6 | 7 | class NimGame { 8 | 9 | class Solution { 10 | 11 | func canWinNim(_ n:Int) -> Bool { 12 | return n % 4 != 0 13 | } 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/NumberComplement.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Created by julian abiodun on 1/18/17. 3 | // Copyright (c) 2017 lagostout. All rights reserved. 4 | // 5 | 6 | import Foundation 7 | 8 | class NumberComplement { 9 | class func findComplement(_ num: Int) -> Int { 10 | let power:Int = Int(log2(Double(num))) + 1 11 | let decimalPower1 = pow(Double(2), Double(power)) - 1 12 | let mask:Int = Int(decimalPower1) 13 | return num ^ mask 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/Operators.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Operators.swift 3 | // CodingPractice 4 | // 5 | // Created by julian abiodun on 1/17/17. 6 | // Copyright © 2017 lagostout. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } 12 | infix operator ^^ : PowerPrecedence 13 | func ^^ (radix: Int, power: Int) -> Int { 14 | return Int(pow(Double(radix), Double(power))) 15 | } 16 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/PaintHouse.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | /// [Problem](https://leetcode.com/problems/paint-house/#/description) 6 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/PalindromePermutation.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | class PalindromePermutation { 6 | class Solution { 7 | func canPermutePalindrome(_ s: String) -> Bool { 8 | var charCounts: Dictionary = [:] 9 | for char in s { 10 | charCounts[char] = (charCounts[char] ?? 0) + 1 11 | } 12 | var oddCharCountCount = 0 13 | for count in charCounts.values { 14 | if count % 2 == 1 { 15 | oddCharCountCount += 1 16 | if oddCharCountCount > 1 { break } 17 | } 18 | } 19 | return oddCharCountCount <= 1 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/SingleNumber.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | // https://leetcode.com/problems/single-number/ 6 | 7 | class SingleNumber { 8 | func singleNumber(_ nums: [Int]) -> Int { 9 | var accumulation = 0 10 | for number in nums { 11 | accumulation = accumulation ^ number 12 | } 13 | return accumulation 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/SumOfTwoIntegers.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | class SumOfTwoIntegers { 6 | 7 | // Note - may also be solved recursively. 8 | 9 | func getSum(_ n1: Int, _ n2: Int) -> Int { 10 | var a = 0 11 | var sum = 0 12 | var mask = 1 13 | var bitPosition = 1 14 | // Make no assumption about the size 15 | // of the system-dependent size of the 16 | // type of Int actually in use. 17 | let maxBitPosition = Int(log2(Double(Int.max))) + 1 18 | // Making an assumption about the size of Int 19 | // cuts runtime by half, from 32ms to 16ms 20 | // let maxBitPosition = 64 21 | while (bitPosition <= maxBitPosition) { 22 | let b = n1 & mask 23 | let c = n2 & mask 24 | let d = a ^ b ^ c 25 | sum = sum | d 26 | a = (a & b) | (b & c) | (a & c) 27 | bitPosition += 1 28 | a <<= 1 29 | mask <<= 1 30 | } 31 | return sum 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPractice/Utils.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | public func _pow(_ n:Decimal, _ p:Int) -> Int { 6 | return Int(NSDecimalNumber(decimal: pow(n, p))) 7 | } 8 | 9 | public func toBinaryString(_ n:Int) -> String { 10 | var n1 = n 11 | if (n1 < 0) { 12 | // 2's complement 13 | n1 = (Int(_pow(2, 64)) - 1) ^ abs(n1) + 1 14 | } 15 | return String(n1, radix: 2) 16 | } 17 | 18 | public func getTwosComplement(_ n:Int) -> Int { 19 | let m = Int.max << 1 | 1 20 | print("m \(toBinaryString(m)) \n") 21 | let result = (n ^ m) + 1 22 | return result 23 | } 24 | 25 | public func elapsedTime(_ a:DispatchTime, _ b:DispatchTime) -> Double { 26 | return Double(b.uptimeNanoseconds - a.uptimeNanoseconds)/1_000_000_000 27 | } 28 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/AddDigitsSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class AddDigitsSpec : QuickSpec { 8 | override func spec() { 9 | describe("AddDigits") { 10 | let addDigits = AddDigits() 11 | let cases: [(number: Int, expected:Int)] = [ 12 | (0,0),(1,1),(2,2),(9,9),(10,1),(11,2),(12,3) 13 | ] 14 | describe("repeatedly adds digits of number until result has only one digit ") { 15 | for (number, expected) in cases { 16 | it("reduces \(number) to \(expected)") { 17 | expect(addDigits.addDigits(number)).to(equal(expected)) 18 | } 19 | } 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/ConstructTheRectangleSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class ConstructTheRectangleSpec : QuickSpec { 8 | override func spec() { 9 | describe("ConstructTheRectangle") { 10 | let cases:[(area:Int, expected:[Int])] = [ 11 | (1, [1,1]), 12 | (2, [2,1]), 13 | (4, [2,2]), 14 | (5, [5,1]), 15 | (6, [3,2]), 16 | (8, [4,2]), 17 | (12, [4,3]), 18 | ] 19 | let constructTheRectangle = ConstructTheRectangle() 20 | for (area, expected) in cases { 21 | it("computes \(expected) are the sides with " + 22 | "minimal difference for rectangle with area \(area)") { 23 | expect(constructTheRectangle.constructRectangle(area)) 24 | .to(equal(expected)) 25 | } 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/FindDisappearedNumbersSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | import CodingPractice 7 | 8 | class FindDisappearedNumbersSpec : QuickSpec { 9 | override func spec() { 10 | describe("FindDisappearedNumbersSpec") { 11 | let cases = [ 12 | ([1,1,2], [3]), 13 | ([2,2,1], [3]), 14 | ([3,1,1], [2]), 15 | ([4,3,2,7,8,2,3,1], [5,6]), 16 | ] 17 | for (numbers, expected) in cases { 18 | it("finds missing numbers") { 19 | let missingNumbers = FindDisappearedNumbers() 20 | .findDisappearedNumbers(numbers) 21 | expect(missingNumbers).to(equal(expected)) 22 | } 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/FirstUniqueCharacterInAStringSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class FirstUniqueCharacterInAStringSpec : QuickSpec { 8 | 9 | override func spec() { 10 | describe("FirstUniqueCharacterInAString") { 11 | let cases:[(str:String, expected:Int)] = [ 12 | ("", -1), 13 | ("leetcode", 0), 14 | ("loveleetcode", 2), 15 | ("cc", -1) 16 | ] 17 | let firstUnique = FirstUniqueCharacterInAString() 18 | for (str, expected) in cases { 19 | it("finds the index of the first non-repeating character") { 20 | expect(firstUnique.firstUniqChar(str)).to(equal(expected)) 21 | } 22 | } 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/FlipGameSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class FlipGameSpec : QuickSpec { 8 | override func spec() { 9 | describe("FlipGame") { 10 | let cases = [ 11 | ("", []), 12 | ("+", []), 13 | ("++", ["--"]), 14 | ("+-", []), 15 | ("++-", ["---"]), 16 | ("+++", ["--+","+--"]), 17 | ("++++", ["--++","+--+","++--"]), 18 | ("+-+-", []), 19 | ("+-++", ["+---"]), 20 | ("+-+++-++-+", ["+---+-++-+","+-+---++-+","+-+++----+"]) 21 | ] 22 | for (startString, expected) in cases { 23 | it("predicts state of \(startString) after first move") { 24 | let state = FlipGame().generatePossibleNextMoves(startString) 25 | print("initial state \(startString)") 26 | print("e+pected \(expected)") 27 | print("state \(state)") 28 | expect(state).to(equal(expected)) 29 | } 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/HammingDistanceTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // HammingDistanceTests.swift 3 | // CodingPractice 4 | // 5 | // Created by julian abiodun on 1/12/17. 6 | // Copyright © 2017 lagostout. All rights reserved. 7 | // 8 | 9 | import XCTest 10 | import Nimble 11 | import Dollar 12 | 13 | class HammingDistanceTests: XCTestCase { 14 | 15 | var hd:HammingDistance? 16 | 17 | override func setUp() { 18 | super.setUp() 19 | hd = HammingDistance() 20 | } 21 | 22 | override func tearDown() { 23 | super.tearDown() 24 | } 25 | 26 | func testComputesHammingDistance() { 27 | let testCases = [([1,4],2), ([2,2],0)] 28 | for testCase in testCases { 29 | let input = testCase.0 30 | expect(self.hd?.hammingDistance( 31 | input[0], input[1])).to(equal(testCase.1)) 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/MaxConsecutiveOnesSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class MaxConsecutiveOnesSpec : QuickSpec { 8 | override func spec() { 9 | it("finds max consecutive ones") { 10 | let maxConsecutiveOnes = MaxConsecutiveOnes() 11 | let cases = [ 12 | [[1,1,0,1,1,1], 3], 13 | [[0,1,1,0,0,1,1,1,0], 3] 14 | ] 15 | for aCase in cases { 16 | let max = maxConsecutiveOnes 17 | .findMaxConsecutiveOnes(aCase[0] as! [Int]) 18 | expect(max).to(equal(aCase[1] as? Int)) 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/NimGameSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class NimGameSpec: QuickSpec { 8 | override func spec() { 9 | describe("NimGame") { 10 | let cases = [(1,true),(2,true), 11 | (3,true),(4,false), 12 | (5,true),(6,true), 13 | (7,true)] 14 | for (testCount, (rockCount, expected)) in cases.enumerated() { 15 | it("detects the possibility of me winning \(testCount)") { 16 | let canWin = NimGame.Solution().canWinNim(rockCount) 17 | expect(canWin).to(equal(expected)) 18 | } 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/NumberComplementSpec.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Created by julian abiodun on 1/18/17. 3 | // Copyright (c) 2017 lagostout. All rights reserved. 4 | // 5 | 6 | import Foundation 7 | import Quick 8 | import Nimble 9 | 10 | class NumberComplementSpec : QuickSpec { 11 | override func spec() { 12 | let cases = [[5,2],[1,0]] 13 | for aCase in cases { 14 | it("computes complement of \(aCase[0])") { 15 | expect(NumberComplement 16 | .findComplement(aCase[0])).to(equal(aCase[1])) 17 | } 18 | } 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/PaintHouseSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/PalindromePermutationSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class PalindromePermutationSpec : QuickSpec { 8 | override func spec() { 9 | describe("PalindromePermutation") { 10 | it("determines if a palindrome can be formed") { 11 | let cases = [["code",false], 12 | ["aab",true], 13 | ["carerac",true]] 14 | for aCase in cases { 15 | let canBePalindrome:Bool = 16 | PalindromePermutation.Solution() 17 | .canPermutePalindrome( 18 | aCase[0] as! String) 19 | expect(canBePalindrome).to( 20 | equal(aCase[1] as? Bool)) 21 | } 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/RelativeRanksSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class RelativeRanksSpec : QuickSpec { 8 | 9 | override func spec() { 10 | let relativeRanks = RelativeRanks() 11 | describe("RelativeRanks") { 12 | describe("findRelativeRanks") { 13 | let cases:[(scores:[Int], expected:[String])] = [ 14 | ([5,4,3,2,1], 15 | ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]), 16 | ([10,3,8,9,4], 17 | ["Gold Medal","5","Bronze Medal","Silver Medal","4"])] 18 | for (scores, expected)in cases { 19 | it("ranks scores") 20 | { [scores = scores] in 21 | expect(relativeRanks.findRelativeRanks(scores)) 22 | .to(equal(expected)) 23 | } 24 | } 25 | } 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/Scratch.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class Scratch : QuickSpec { 8 | 9 | var i:Int = 0 10 | 11 | override func spec() { 12 | describe("a") { 13 | inc(i) 14 | describe("b") { 15 | inc(i) 16 | for _ in 0...0 { 17 | it("c") { 18 | self.inc(self.i) 19 | expect(true).to(equal(true)) 20 | expect(1).to(equal(1)) 21 | } 22 | } 23 | } 24 | } 25 | } 26 | 27 | func inc(_ i:Int) { 28 | self.i += 1 29 | print(self.i) 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/SingleNumberSpec.swift: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | import Quick 5 | import Nimble 6 | 7 | class CodingPracticeSpec : QuickSpec { 8 | override func spec() { 9 | describe("SingleNumber") { 10 | let cases = [ 11 | ([1,2,1], 2), 12 | ([2,2,3], 3), 13 | ([2,2,4,5,6,4,5], 6) 14 | ] 15 | for (numbers, expected) in cases { 16 | it("finds the single number non-repeated number") { 17 | let singleNumber = SingleNumber().singleNumber(numbers) 18 | expect(singleNumber).to(equal(expected)) 19 | } 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/SumOfTwoIntegersSpec.swift: -------------------------------------------------------------------------------- 1 | 2 | import Foundation 3 | import Quick 4 | import Nimble 5 | 6 | class SumOfTwoIntegersSpec : QuickSpec { 7 | override func spec() { 8 | describe("SumOfTwoIntegers") { 9 | let cases = [ 10 | ((0,-1), -1), 11 | ((1,-1), 0), 12 | ((1,1), 2), 13 | ((1,2), 3), 14 | ((0,0), 0), 15 | ((0,1), 1), 16 | ((2,4), 6), 17 | ((3, 1000), 1003), 18 | ((40, 1000), 1040) 19 | ] 20 | let sumOfTwoIntegers = SumOfTwoIntegers() 21 | for ((leftOperand, rightOperand), expected) in cases { 22 | it("sums \(leftOperand) and \(rightOperand) without using operators") { 23 | let sum = sumOfTwoIntegers.getSum(leftOperand, rightOperand) 24 | expect(sum).to(equal(expected)) 25 | } 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /swift/CodingPractice/CodingPracticeTests/TFunctions.swift: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 lagostout. All rights reserved. 2 | 3 | import Foundation 4 | 5 | func reproducibleRandom(endExclusive: Int) -> Int { 6 | let dr = drand48() 7 | return Int(dr * Double(endExclusive)) 8 | } 9 | 10 | func reproducibleRandom(endInclusive: Int) -> Int { 11 | return reproducibleRandom(endExclusive: endInclusive + 1) 12 | } -------------------------------------------------------------------------------- /swift/CodingPractice/Podfile: -------------------------------------------------------------------------------- 1 | # Podfile 2 | 3 | platform :osx, '10.13.2' 4 | 5 | use_frameworks! 6 | 7 | def testing_pods 8 | pod 'Quick' 9 | pod 'Nimble' 10 | pod 'Dollar' 11 | pod 'Combinatorics' 12 | end 13 | 14 | target 'CodingPractice' do 15 | pod 'SwiftyJSON' 16 | # testing_pods 17 | end 18 | 19 | target 'CodingPracticeTests' do 20 | testing_pods 21 | end 22 | --------------------------------------------------------------------------------