├── .gitignore ├── README.md ├── build.gradle.kts ├── interviews └── Data Migration 0 downtime.pdf ├── settings.gradle.kts └── src ├── BFS_ALL_IN_ONE.pdf ├── BS_ALL_IN_ONE.pdf ├── BinarySearch.md ├── DFS_ALL_IN_ONE.pdf ├── TREE_ALL_IN_ONE.pdf ├── bfs.md ├── main ├── java │ ├── Challenge2.java │ ├── Challenge3.java │ ├── Challenge4.java │ ├── Chanllenge5.java │ ├── binary_search │ │ ├── AdvantageShuffle870.java │ │ ├── ArrangingCoins441.java │ │ ├── BinarySearch704.java │ │ ├── CapacityToShipPackagesWithinDDays1011.java │ │ ├── CarPooling1094.java │ │ ├── CountCompleteTreeNodes222.java │ │ ├── CountNegativeNumbersinaSortedMatrix1351.java │ │ ├── CountofRangeSum327.java │ │ ├── CountofSmallerNumbersAfterSelf315.java │ │ ├── DataStreamasDisjointIntervals352.java │ │ ├── DivideTwoIntegers29.java │ │ ├── FindFirstandLastPositionofElementinSortedArray34.java │ │ ├── FindKClosestElements658.java │ │ ├── FindKthSmallestPairDistance719.java │ │ ├── FindMedianfromDataStream295.java │ │ ├── FindMinimuminRotatedSortedArray153.java │ │ ├── FindMinimuminRotatedSortedArrayII154.java │ │ ├── FindPeakElement162.java │ │ ├── FindPositiveIntegerSolutionforaGivenEquation1237.java │ │ ├── FindRightInterval436.java │ │ ├── FindSmallestLetterGreaterThanTarget744.java │ │ ├── FindinMountainArray1095.java │ │ ├── FindtheDuplicateNumber287.java │ │ ├── FindtheSmallestDivisorGivenaThreshold1283.java │ │ ├── FirstBadVersion278.java │ │ ├── FourSumII454.java │ │ ├── GuessNumberHigherorLower374.java │ │ ├── HIndex274.java │ │ ├── HIndexII275.java │ │ ├── Heaters475.java │ │ ├── IncreasingTripletSubsequence344.java │ │ ├── IntersectionofTwoArrays349.java │ │ ├── IntersectionofTwoArraysII350.java │ │ ├── IsSubsequence392.java │ │ ├── KokoEatingBananas875.java │ │ ├── KthSmallestElementinaBST230.java │ │ ├── KthSmallestElementinaSortedMatrix378.java │ │ ├── KthSmallestNumberinMultiplicationTable668.java │ │ ├── KthSmallestPrimeFraction786.java │ │ ├── LongestDuplicateSubstring1044.java │ │ ├── LongestIncreasingSubsequence300.java │ │ ├── MaxSumofRectangleNoLargerThanK363.java │ │ ├── MaximumLengthofRepeatedSubarray718.java │ │ ├── MaximumSideLengthofaSquarewithSumLessthanorEqualtoThreshold1292.java │ │ ├── MedianofTwoSortedArrays4.java │ │ ├── MinimumNumberofDaystoMakemBouquets1482.java │ │ ├── MinimumSizeSubarraySum209.java │ │ ├── NthMagicalNumber878.java │ │ ├── OnlineElection911.java │ │ ├── OnlineMajorityElementInSubarray1157.java │ │ ├── PathWithMinimumEffort1631.java │ │ ├── PeakIndexinaMountainArray852.java │ │ ├── Powxn50.java │ │ ├── PreimageSizeofFactorialZeroesFunction793.java │ │ ├── RandomPickwithBlacklist710.java │ │ ├── RandomPickwithWeight528.java │ │ ├── RandomPointinNonoverlappingRectangles497.java │ │ ├── ReversePairs493.java │ │ ├── RussianDollEnvelopes354.java │ │ ├── SearchInsertPosition35.java │ │ ├── Searcha2DMatrix74.java │ │ ├── Searcha2DMatrixII240.java │ │ ├── SearchinRotatedSortedArray33.java │ │ ├── SearchinRotatedSortedArrayII81.java │ │ ├── ShortestSubarraywithSumatLeastK862.java │ │ ├── SingleElementinaSortedArray540.java │ │ ├── SmallestGoodBase483.java │ │ ├── SplitArrayLargestSum410.java │ │ ├── Sqrt69.java │ │ ├── SumofMutatedArrayClosesttoTarget1300.java │ │ ├── SuperEggDrop887.java │ │ ├── SwiminRisingWater778.java │ │ ├── TheKWeakestRowsinaMatrix1337.java │ │ ├── ThreeEqualParts927.java │ │ ├── TimeBasedKeyValueStore981.java │ │ ├── TwoSumIIInputarrayissorted167.java │ │ ├── UglyNumber263.java │ │ ├── UglyNumberII264.java │ │ ├── UglyNumberIII1201.java │ │ └── ValidPerfectSquare367.java │ ├── bit_operation │ │ ├── CheckIfaStringContainsAllBinaryCodesofSizeK1461.java │ │ ├── ConcatenationofConsecutiveBinaryNumbersw1680.java │ │ ├── CreateSortedArraythroughInstructions1649.java │ │ ├── GrayCode89.java │ │ ├── IteratorforCombination1286.java │ │ ├── MaximumXORofTwoNumbersinanArray421.java │ │ ├── NonnegativeIntegerswithoutConsecutiveOnes600.java │ │ ├── Numberof1Bits191.java │ │ └── RepeatedDNASequences187.java │ ├── breadth_first_search │ │ ├── 1_matrix_utils │ │ ├── AllNodesDistanceKinBinaryTree863.java │ │ ├── AsFarfromLandasPossible1162.java │ │ ├── BinaryTreeLevelOrderTraversal102.java │ │ ├── BinaryTreeLevelOrderTraversalII107.java │ │ ├── BinaryTreeRightSideView199.java │ │ ├── BinaryTreeZigzagLevelOrderTraversal103.java │ │ ├── BrokenCalculator991.java │ │ ├── BusRoutes815.java │ │ ├── CheckifThereisaValidPathinaGrid1391.java │ │ ├── CloneGraph133.java │ │ ├── CourseScheduleII210.java │ │ ├── CousinsinBinaryTree993.java │ │ ├── CutOffTreesforGolfEvent675.java │ │ ├── DecodeWays91.java │ │ ├── DiagonalTraverse498.java │ │ ├── DiagonalTraverseII1424.java │ │ ├── EmployeeImportance960.java │ │ ├── EscapeaLargeMaze1036.java │ │ ├── FindBottomLeftTreeValue513.java │ │ ├── FindLargestValueinEachTreeRow515.java │ │ ├── GetWatchedVideosbyYourFriends1311.java │ │ ├── JumpGameIII1306.java │ │ ├── JumpGameIV1345.java │ │ ├── KSimilarStrings854.java │ │ ├── KeysandRooms841.java │ │ ├── Matrix01542.java │ │ ├── MaximumCandiesYouCanGetfromBoxes1298.java │ │ ├── MaximumDepthofNaryTree559.java │ │ ├── MaximumWidthofBinaryTree662.java │ │ ├── Minesweeper529.java │ │ ├── MinimumCosttoMakeatLeastOneValidPathinaGrid1368.java │ │ ├── MinimumDepthofBinaryTree111.java │ │ ├── MinimumHeightTrees310.java │ │ ├── MinimumMovestoMoveaBoxtoTheirTargetLocation1263.java │ │ ├── MinimumMovestoReachTargetwithRotations1210.java │ │ ├── MinimumNumberofFlipstoConvertBinaryMatrixtoZeroMatrix1284.java │ │ ├── NaryTreeLevelOrderTraversal429.java │ │ ├── NetworkDelayTime743.java │ │ ├── NumberofIslands200.java │ │ ├── OpentheLock752.java │ │ ├── PacificAtlanticWaterFlow417.java │ │ ├── RemoveInvalidParentheses301.java │ │ ├── RottingOranges994.java │ │ ├── SequentialDigits1291.java │ │ ├── ShortestBridge934.java │ │ ├── ShortestPathVisitingAllNodes847.java │ │ ├── ShortestPathinBinaryMatrix1091.java │ │ ├── ShortestPathinaGridwithObstaclesElimination1293.java │ │ ├── ShortestPathtoGetAllKeys864.java │ │ ├── ShortestPathwithAlternatingColors1129.java │ │ ├── SlidingPuzzle773.java │ │ ├── SnakesandLadders909.java │ │ ├── SumRoottoLeafNumbers129.java │ │ ├── SumofLeftLeaves404.java │ │ ├── SumofRootToLeafBinaryNumbers1022.java │ │ ├── SurroundedRegions130.java │ │ ├── SymmetricTree101.java │ │ ├── TrappingRainWaterII407.java │ │ ├── VerticalOrderTraversalofaBinaryTree987.java │ │ ├── WordLadder127.java │ │ ├── WordLadderII126.java │ │ └── ZombieInMatrix.java │ ├── depth_first_search │ │ ├── 1_matrix_utils │ │ ├── AccountsMerge721.java │ │ ├── AllPathsFromSourcetoTarget797.java │ │ ├── BeautifulArrangement526.java │ │ ├── ColoringABorder1034.java │ │ ├── CombinationSum39.java │ │ ├── CombinationSumIII216.java │ │ ├── Combinations77.java │ │ ├── ConcatenatedWords472.java │ │ ├── ConvertSortedListtoBinarySearchTree109.java │ │ ├── CountSortedVowelStrings1641.java │ │ ├── DistinctSubsequences115.java │ │ ├── FindEventualSafeStates802.java │ │ ├── FindWinneronaTicTacToeGame1275.java │ │ ├── FloodFill733.java │ │ ├── FreedomTrail514.java │ │ ├── FriendCircles547.java │ │ ├── FrogPositionAfterTSeconds1377.java │ │ ├── GenerateParentheses22.java │ │ ├── IncreasingSubsequences491.java │ │ ├── InterleavingString97.java │ │ ├── JumpGame55.java │ │ ├── LetterCasePermutation784.java │ │ ├── LetterCombinationsofaPhoneNumber17.java │ │ ├── LexicographicallySmallestStringAfterApplyingOperations1625.java │ │ ├── LongestIncreasingPathinaMatrix329.java │ │ ├── LoudandRich851.java │ │ ├── MakingALargeIsland827.java │ │ ├── MatchstickstoSquare473.java │ │ ├── MaxAreaofIsland695.java │ │ ├── MaximumLengthofaConcatenatedStringwithUniqueCharacters1239.java │ │ ├── MinimizeHammingDistanceAfterSwapOperations1722.java │ │ ├── MostStonesRemovedwithSameRoworColumn947.java │ │ ├── NQueens51.java │ │ ├── NQueensII52.java │ │ ├── NumberofClosedIslands1254.java │ │ ├── NumberofEnclaves1020.java │ │ ├── NumberofNodesintheSubTreeWiththeSameLabel1519.java │ │ ├── NumbersWithSameConsecutiveDifferences967.java │ │ ├── OutofBoundaryPaths576.java │ │ ├── PalindromePartitioning131.java │ │ ├── PalindromePartitioningII132.java │ │ ├── PathSumIII437.java │ │ ├── PyramidTransitionMatrix756.java │ │ ├── ReconstructItinerary332.java │ │ ├── RegionsCutBySlashes959.java │ │ ├── RemoveBoxes546.java │ │ ├── ShoppingOffers638.java │ │ ├── Subsets78.java │ │ ├── SubsetsII90.java │ │ ├── TargetSum494.java │ │ ├── TimeNeededtoInformAllEmployees1376.java │ │ ├── TreeofCoprimes1766.java │ │ ├── Triangle120.java │ │ ├── UniqueBinarySearchTrees96.java │ │ ├── UniqueBinarySearchTreesII95.java │ │ ├── UniquePathsIII980.java │ │ ├── ValidSudoku36.java │ │ ├── WordBreakII140.java │ │ ├── WordSearch79.java │ │ ├── WordSearchII212.java │ │ └── ZumaGame488.java │ ├── design │ │ ├── DesignCircularQueue622.java │ │ ├── MapSumPairs677.java │ │ ├── MyCalendarI729.java │ │ ├── MyCalendarII731.java │ │ ├── MyCalendarIII732.java │ │ ├── PrefixandSuffixSearch745.java │ │ ├── RangeSumQueryMutable307.java │ │ ├── ReadmeBuilder.kt │ │ └── SearchSuggestionsSystem1268.java │ ├── dynamic_programming │ │ ├── ArithmeticSlices413.java │ │ ├── BestTimetoBuyandSellStockwithCooldown309.java │ │ ├── BestTimetoBuyandSellStockwithTransactionFee714.java │ │ ├── BinaryTreesWithFactors823.java │ │ ├── BurstBalloons312.java │ │ ├── ClimbingStairs70.java │ │ ├── CoinChange2518.java │ │ ├── CoinChange322.java │ │ ├── CombinationSumIV377.java │ │ ├── CountSquareSubmatriceswithAllOnes1277.java │ │ ├── CountVowelsPermutation1220.java │ │ ├── DecodeWaysII639.java │ │ ├── DeleteOperationforTwoStrings583.java │ │ ├── DungeonGame174.java │ │ ├── EditDistance72.java │ │ ├── FibonacciNumber509.java │ │ ├── HouseRobber198.java │ │ ├── HouseRobberII213.java │ │ ├── JumpGameVI1696.java │ │ ├── LargestDivisibleSubset368.java │ │ ├── LargestSizeOfRussianDollString.java │ │ ├── LongestStringChain1048.java │ │ ├── MaximumProfitinJobScheduling1235.java │ │ ├── MaximumSubarray53.java │ │ ├── MaximumSumCircularSubarray918.java │ │ ├── MinCostClimbingStairs746.java │ │ ├── MinimumASCIIDeleteSumforTwoStrings712.java │ │ ├── MinimumCostForTickets983.java │ │ ├── NthTribonacciNumber1137.java │ │ ├── NumberofLongestIncreasingSubsequence673.java │ │ ├── OnesandZeroes474.java │ │ ├── PartitionArrayforMaximumSum1043.java │ │ ├── PerfectSquares279.java │ │ ├── StoneGameIV1510.java │ │ ├── TrappingRainWater42.java │ │ ├── TwoCityScheduling1029.java │ │ ├── UncrossedLines1035.java │ │ ├── UniquePaths62.java │ │ ├── UniquePathsII63.java │ │ ├── WiggleSubsequence376.java │ │ └── WordBreak139.java │ ├── easy_easy │ │ ├── AddStrings415.java │ │ ├── ArrayPartitionI561.java │ │ ├── BuildanArrayWithStackOperations1441.java │ │ ├── CanMakeArithmeticProgressionFromSequence1502.java │ │ ├── CellswithOddValuesinaMatrix1252.java │ │ ├── CheckifWordEqualsSummationofTwoWords1880.java │ │ ├── CheckiftheSentenceIsPangram1832.java │ │ ├── CountGoodTriplets1534.java │ │ ├── CountItemsMatchingaRule1773.java │ │ ├── CountofMatchesinTournament1688.java │ │ ├── CounttheNumberofConsistentStrings1684.java │ │ ├── CreateTargetArrayintheGivenOrder1389.java │ │ ├── DIStringMatch942.java │ │ ├── DecodeXORedArray1720.java │ │ ├── DecompressRunLengthEncodedList1313.java │ │ ├── DecryptStringfromAlphabettoIntegerMapping1309.java │ │ ├── DeleteColumnstoMakeSorted944.java │ │ ├── DesignParkingSystem1603.java │ │ ├── DesignanOrderedStream1656.java │ │ ├── DestinationCity1436.java │ │ ├── DetermineColorofaChessboardSquare1812.java │ │ ├── FindCommonCharacters1002.java │ │ ├── FindNUniqueIntegersSumuptoZero1304.java │ │ ├── FindNumberswithEvenNumberofDigits1295.java │ │ ├── FindtheHighestAltitude1732.java │ │ ├── GenerateaStringWithCharactersThatHaveOddCounts1374.java │ │ ├── GoalParserInterpretation1678.java │ │ ├── GroupsofSpecialEquivalentStrings893.java │ │ ├── HeightChecker1051.java │ │ ├── HowManyNumbersAreSmallerThantheCurrentNumber1365.java │ │ ├── IncreasingDecreasingString1370.java │ │ ├── IsomorphicStrings205.java │ │ ├── KidsWiththeGreatestNumberofCandies1431.java │ │ ├── LongestCommonPrefix14.java │ │ ├── LuckyNumbersinaMatrix1380.java │ │ ├── MakeTwoArraysEqualbyReversingSubarrays1460.java │ │ ├── MatrixCellsinDistanceOrder1030.java │ │ ├── MatrixDiagonalSum1572.java │ │ ├── Maximum69Number1323.java │ │ ├── MaximumNestingDepthoftheParentheses1614.java │ │ ├── MaximumNumberofBallsinaBox1742.java │ │ ├── MaximumPopulationYear1854.java │ │ ├── MaximumProductofTwoElementsinanArray1464.java │ │ ├── MaximumUnitsonaTruck1710.java │ │ ├── MergeStringsAlternately1768.java │ │ ├── MinimumMovestoEqualArrayElements453.java │ │ ├── MinimumMovestoEqualArrayElementsII462.java │ │ ├── MinimumMovestoEqualArrayElementsKotlin453.kt │ │ ├── MinimumOperationstoMaketheArrayIncreasing1827.java │ │ ├── MinimumSubsequenceinNonIncreasingOrder1403.java │ │ ├── MinimumTimeVisitingAllPoints1266.java │ │ ├── NRepeatedElementinSize2NArray961.java │ │ ├── NumberOfRectanglesThatCanFormTheLargestSquare1725.java │ │ ├── NumberofGoodPairs1512.java │ │ ├── NumberofStudentsDoingHomeworkataGivenTime1450.java │ │ ├── PalindromeNumber9.java │ │ ├── PartitionArrayIntoThreePartsWithEqualSum1013.java │ │ ├── ProjectionAreaof3DShapes883.java │ │ ├── RemoveOutermostParentheses1021.java │ │ ├── ReplaceAllDigitswithCharacters1844.java │ │ ├── ReplaceElementswithGreatestElementonRightSide1299.java │ │ ├── ReshapetheMatrix566.java │ │ ├── ReverseInteger7.java │ │ ├── ReverseWordsinaStringIII557.java │ │ ├── RichestCustomerWealth1672.java │ │ ├── RobotReturntoOrigin657.java │ │ ├── SelfDividingNumbers728.java │ │ ├── ShuffleString1528.java │ │ ├── ShuffletheArray1470.java │ │ ├── SignoftheProductofanArray1822.java │ │ ├── SortIntegersbyTheNumberof1BitsKotlin1356.kt │ │ ├── SortingtheSentence1859.java │ │ ├── SplitaStringinBalancedStrings1221.java │ │ ├── StringtoIntegeratoi8.java │ │ ├── SubdomainVisitCount811.java │ │ ├── SubtracttheProductandSumofDigitsofanInteger1281.java │ │ ├── SumofAllOddLengthSubarrays1588.java │ │ ├── SumofAllSubsetXORTotals1863.java │ │ ├── SumofDigitsinBaseK1837.java │ │ ├── SumofUniqueElements1748.java │ │ ├── ToLowerCase709.java │ │ ├── TruncateSentence1816.java │ │ ├── UniqueNumberofOccurrences1207.java │ │ └── XOROperationinanArray1486.java │ ├── graph │ │ ├── CheapestFlightsWithinKStops787.java │ │ ├── CourseSchedule207.java │ │ ├── CriticalConnectionsinaNetwork1192.java │ │ ├── EvaluateDivision399.java │ │ ├── IsGraphBipartite785.java │ │ └── PossibleBipartition886.java │ ├── hash_map_set │ │ ├── BrickWall554.java │ │ ├── DesignHashMap706.java │ │ ├── DesignHashSet705.java │ │ ├── DesignUndergroundSystem1396.java │ │ ├── DistributeCandies575.java │ │ ├── EncodeandDecodeTinyURL535.java │ │ ├── FindDuplicateFileinSystem609.java │ │ ├── FindandReplacePattern890.java │ │ ├── InsertDeleteGetRandomO1380.java │ │ ├── InsertDeleteGetRandomO1Duplicatesallowed381.java │ │ ├── LongestConsecutiveSequence128.java │ │ ├── LongestHarmoniousSubsequence594.java │ │ ├── LongestSubstringWithoutRepeatingCharacters3.java │ │ ├── NumberofMatchingSubsequences792.java │ │ ├── NumberofSubmatricesThatSumtoTarget1074.java │ │ ├── PalindromePairs336.java │ │ ├── ReduceArraySizetoTheHalf1338.java │ │ ├── SetMismatch645.java │ │ ├── ShortEncodingofWords820.java │ │ └── TwoSum1.java │ ├── list_array │ │ ├── AddTwoNumbers2.java │ │ ├── AddTwoNumbersII445.java │ │ ├── ArrayofDoubledPairs954.java │ │ ├── BagofTokens948.java │ │ ├── BeautifulArray932.java │ │ ├── Candy135.java │ │ ├── ChampagneTower799.java │ │ ├── ContainerWithMostWater11.java │ │ ├── CopyListwithRandomPointer138.java │ │ ├── DeleteNodeinaLinkedList237.java │ │ ├── DistributeCandiestoPeople1103.java │ │ ├── FlattenNestedListIterator341.java │ │ ├── FlattenaMultilevelDoublyLinkedList430.java │ │ ├── GameofLife289.java │ │ ├── GasStation134.java │ │ ├── ImageOverlap835.java │ │ ├── InsertInterval57.java │ │ ├── InsertionSortList147.java │ │ ├── IntersectionofTwoLinkedLists160.java │ │ ├── IntervalListIntersections986.java │ │ ├── KdiffPairsinanArray532.java │ │ ├── LinkedListCycle141.java │ │ ├── LinkedListCycleII142.java │ │ ├── ListNode.java │ │ ├── LongestPalindromicSubstring5.java │ │ ├── MaxNumberofKSumPairs1679.java │ │ ├── MaximizeDistancetoClosestPerson849.java │ │ ├── MaximumProductSubarray152.java │ │ ├── MaximumSubarray53.java │ │ ├── MergeIntervals56.java │ │ ├── MergeTwoSortedLists21.java │ │ ├── MergekSortedLists23.java │ │ ├── MiddleoftheLinkedList876.java │ │ ├── MinimumNumberofArrowstoBurstBalloons452.java │ │ ├── NumberofRecentCalls933.java │ │ ├── OddEvenLinkedList328.java │ │ ├── OrderlyQueue899.java │ │ ├── PalindromeLinkedList234.java │ │ ├── PartitionArrayintoDisjointIntervals915.java │ │ ├── PartitionList86.java │ │ ├── PeekingIterator284.java │ │ ├── PushDominoes838.java │ │ ├── RankTransformofaMatrix1632.java │ │ ├── RankTransformofanArray1331.java │ │ ├── RemoveCoveredIntervals1288.java │ │ ├── RemoveDuplicatesfromSortedArrayII80.java │ │ ├── RemoveDuplicatesfromSortedList83.java │ │ ├── RemoveDuplicatesfromSortedListII82.java │ │ ├── RemoveLinkedListElements203.java │ │ ├── RemoveNthNodeFromEndofList19.java │ │ ├── ReorderList143.java │ │ ├── ReverseLinkedListII92.java │ │ ├── ReverseNodesinkGroup25.java │ │ ├── RobotBoundedInCircle1041.java │ │ ├── RotateList61.java │ │ ├── SetMatrixZeroes.java │ │ ├── SortList148.java │ │ ├── SorttheMatrixDiagonally1329.java │ │ ├── SpiralMatrix54.java │ │ ├── SpiralMatrixII59.java │ │ ├── SplitLinkedListinParts725.java │ │ ├── SubarrayProductLessThanK713.java │ │ ├── SummaryRanges228.java │ │ ├── SwapNodesinPairs24.java │ │ ├── SwappingNodesinaLinkedList1721.java │ │ ├── TopKFrequentElements347.java │ │ ├── ValidTriangleNumber611.java │ │ └── WordSubsets916.java │ ├── not_categorized │ │ ├── CheckIfItIsaStraightLine1232.java │ │ ├── ComplementofBase10Integer1009.java │ │ ├── EvaluateReversePolishNotation150.java │ │ ├── FindtheTownJudge997.java │ │ ├── FirstUniqueCharacterinaString387.java │ │ ├── FlipStringtoMonotoneIncreasing926.java │ │ ├── GenerateRandomPointinaCircle478.java │ │ ├── JewelsandStones771.java │ │ ├── LongestPalindromicSubsequence516.java │ │ ├── LongestUncommonSubsequenceII522.java │ │ ├── MajorityElement169.java │ │ ├── MaximumAreaofaPieceofCakeAfterHorizontalandVerticalCuts1465.java │ │ ├── MaximumGap164.java │ │ ├── MaximumLengthofSubarrayWithPositiveProduct1567.java │ │ ├── MaximumNestingDepthofTwoValidParenthesesStrings1111.java │ │ ├── MaximumProductofWordLengths318.java │ │ ├── MaximumofAbsoluteValueExpression1131.java │ │ ├── NonoverlappingIntervals435.java │ │ ├── PartitioningIntoMinimumNumberOfDeciBinaryNumbers1689.java │ │ ├── PartitiontoKEqualSumSubsets698.java │ │ ├── PoorPigs458.java │ │ ├── QueueReconstructionbyHeight406.java │ │ ├── RectangleArea223.java │ │ ├── ShiftingLetters848.java │ │ ├── ShortestUnsortedContinuousSubarray581.java │ │ ├── SmallestIntegerDivisiblebyK1015.java │ │ ├── ThekthFactorofn1429.java │ │ ├── TransformtoChessboard782.java │ │ ├── ValidSquare593.java │ │ └── ZigZagConversion6.java │ ├── not_categorized_easy │ │ ├── CanPlaceFlowers605.java │ │ ├── CheckArrayFormationThroughConcatenation1640.java │ │ ├── FizzBuzz412.java │ │ ├── InvertBinaryTree226.java │ │ ├── KthMissingPositiveNumber1539.java │ │ ├── MergeSortedArray88.java │ │ ├── NumberofStepstoReduceaNumbertoZero1342.java │ │ ├── PairsofSongsWithTotalDurationsDivisibleby601010.java │ │ ├── RangeAdditionII598.java │ │ ├── ReachaNumber754.java │ │ ├── RemovePalindromicSubsequences1332.java │ │ ├── SearchinaBinarySearchTree700.java │ │ ├── ShortestDistancetoaCharacter821.java │ │ ├── SlowestKey1629.java │ │ ├── SquaresofaSortedArray977.java │ │ ├── UniqueEmailAddresses929.java │ │ ├── ValidAnagram242.java │ │ └── ValidMountainArray941.java │ ├── priority_queue │ │ ├── ConstructTargetArrayWithMultipleSums1354.java │ │ ├── CourseScheduleIII630.java │ │ ├── FurthestBuildingYouCanReach1642.java │ │ ├── JumpGameII45.java │ │ ├── MaximumPerformanceofaTeam1383.java │ │ ├── MinimizeDeviationinArray1675.java │ │ ├── MinimumNumberofRefuelingStops871.java │ │ ├── ReadmeBuilder.kt │ │ └── SmallestRangeCoveringElementsfromKLists632.java │ ├── sliding_window │ │ ├── BoatstoSavePeople881.java │ │ ├── FindAllAnagramsinaString438.java │ │ ├── LongestSubstringwithAtLeastKRepeatingCharacters395.java │ │ ├── MaxConsecutiveOnes485.java │ │ ├── MaxConsecutiveOnesIII1004.java │ │ ├── MaximumErasureValue1695.java │ │ ├── MaximumPointsYouCanObtainfromCards1423.java │ │ ├── MinimumWindowSubstring76.java │ │ ├── NumberofSubarrayswithBoundedMaximum795.java │ │ ├── PermutationinString567.java │ │ └── SlidingWindowMaximum239.java │ ├── stack │ │ ├── AsteroidCollision735.java │ │ ├── BasicCalculatorII227.java │ │ ├── FindtheMostCompetitiveSubsequence1673.java │ │ ├── LargestRectangleinHistogram84.java │ │ ├── LongestValidParentheses32.java │ │ ├── MaximumFrequencyStack895.java │ │ ├── MinimumRemovetoMakeValidParentheses1249.java │ │ ├── OnlineStockSpan901.java │ │ ├── Pattern132456.java │ │ ├── RemoveDuplicateLetters316.java │ │ ├── ScoreofParentheses856.java │ │ ├── SimplifyPath71.java │ │ ├── ValidParenthesisString678.java │ │ └── ValidateStackSequences946.java │ ├── string_integer │ │ ├── AddBinary67.java │ │ ├── AddDigits258.java │ │ ├── AmbiguousCoordinates816.java │ │ ├── AngleBetweenHandsofaClock1344.java │ │ ├── BasicCalculator224.java │ │ ├── BuddyStrings859.java │ │ ├── BullsandCows299.java │ │ ├── CompareVersionNumbers165.java │ │ ├── ConsecutiveCharacters1446.java │ │ ├── ContiguousArray525.java │ │ ├── CountBinarySubstrings696.java │ │ ├── CountPrimes204.java │ │ ├── CountingBits338.java │ │ ├── CustomSortString791.java │ │ ├── DecodeString394.java │ │ ├── DecodedStringatIndex880.java │ │ ├── DefanginganIPAddress1108.java │ │ ├── DetectCapital520.java │ │ ├── DetermineifStringHalvesAreAlike1704.java │ │ ├── DetermineifTwoStringsAreClose1657.java │ │ ├── ExcelSheetColumnNumber171.java │ │ ├── ExcelSheetColumnTitle168.java │ │ ├── FinalPricesWithaSpecialDiscountinaShop1475.java │ │ ├── FindAllDuplicatesinanArray442.java │ │ ├── FindAndReplaceinString833.java │ │ ├── FindtheDifference389.java │ │ ├── FirstMissingPositive41.java │ │ ├── FourSum18.java │ │ ├── GlobalandLocalInversions775.java │ │ ├── GoatLatin824.java │ │ ├── GroupAnagrams49.java │ │ ├── HammingDistance461.java │ │ ├── IslandPerimeter463.java │ │ ├── LargestNumber179.java │ │ ├── LargestTimeforGivenDigits949.java │ │ ├── LengthofLastWord58.java │ │ ├── LongestMountaininArray845.java │ │ ├── LongestPalindrome409.java │ │ ├── LongestWordinDictionarythroughDeleting524.java │ │ ├── MaximumNumberofBalloons1189.java │ │ ├── MinimumDominoRotationsForEqualRow1007.java │ │ ├── MirrorReflection858.java │ │ ├── NextGreaterElementIII556.java │ │ ├── NondecreasingArray665.java │ │ ├── NumberComplement476.java │ │ ├── NumberofOperationstoMakeNetworkConnected1319.java │ │ ├── PalindromicSubstrings647.java │ │ ├── PartitionEqualSubsetSum416.java │ │ ├── PartitionLabels763.java │ │ ├── PascalsTriangle118.java │ │ ├── PascalsTriangleII119.java │ │ ├── PermutationSequence60.java │ │ ├── Permutations46.java │ │ ├── PermutationsII47.java │ │ ├── PlusOne66.java │ │ ├── PowerfulIntegers970.java │ │ ├── PowerofFour342.java │ │ ├── PowerofThree326.java │ │ ├── PowerofTwo231.java │ │ ├── PrisonCellsAfterNDays957.java │ │ ├── RangeSumQuery2DImmutable304.java │ │ ├── RangeSumQueryImmutable303.java │ │ ├── RansomNote383.java │ │ ├── ReconstructOriginalDigitsfromEnglish423.java │ │ ├── RemoveAllAdjacentDuplicatesInString1047.java │ │ ├── RemoveAllAdjacentDuplicatesinStringII1209.java │ │ ├── RemoveKDigits402.java │ │ ├── ReorderedPowerof2869.java │ │ ├── RepeatedSubstringPattern459.java │ │ ├── ReverseBits190.java │ │ ├── ReverseOnlyLetters917.java │ │ ├── ReverseString344.java │ │ ├── ReverseWordsinaString151.java │ │ ├── SingleNumber136.java │ │ ├── SingleNumberII137.java │ │ ├── SingleNumberIII260.java │ │ ├── SmallestRangeI908.java │ │ ├── SmallestRangeII910.java │ │ ├── SmallestStringWithAGivenNumericValue1663.java │ │ ├── SortArrayByParity905.java │ │ ├── SortArrayByParityII922.java │ │ ├── SortCharactersByFrequency451.java │ │ ├── SuperPalindromes906.java │ │ ├── TaskScheduler621.java │ │ ├── TeemoAttacking495.java │ │ ├── ThreeSum15.java │ │ ├── ThreeSumClosest16.java │ │ ├── ThreeSumWithMultiplicity923.java │ │ ├── ValidNumber65.java │ │ ├── ValidPalindrome125.java │ │ ├── ValidPalindromeII680.java │ │ ├── ValidParentheses20.java │ │ ├── ValidateIPAddress468.java │ │ ├── VerifyinganAlienDictionary953.java │ │ ├── WordPattern290.java │ │ └── sort_an_array_912 │ │ │ ├── BubbleSort.java │ │ │ ├── InsertionSort.java │ │ │ ├── KClosestPointstoOrigin973.java │ │ │ ├── KthLargestElementinanArray215.java │ │ │ ├── MergeSort.java │ │ │ ├── PancakeSorting969.java │ │ │ ├── QuickSort.java │ │ │ ├── SelectionSort.java │ │ │ └── SortColors75.java │ ├── top_interview_easy │ │ └── array │ │ │ ├── BestTimetoBuyandSellStock121.java │ │ │ ├── BestTimetoBuyandSellStockII122.java │ │ │ ├── BestTimetoBuyandSellStockIII123.java │ │ │ ├── BestTimetoBuyandSellStockIV188.java │ │ │ ├── ContainsDuplicate217.java │ │ │ ├── ContainsDuplicateII219.java │ │ │ ├── ContainsDuplicateIII220.java │ │ │ ├── MoveZeroes283.java │ │ │ ├── RemoveDuplicatesfromSortedArray26.java │ │ │ ├── RotateArray189.java │ │ │ ├── RotateImage48.java │ │ │ └── ValidSudoku36.java │ ├── tree │ │ ├── AddOneRowtoTree623.java │ │ ├── AddandSearchWord211.java │ │ ├── AllElementsinTwoBinarySearchTrees1305.java │ │ ├── AllPossibleFullBinaryTrees894.java │ │ ├── AverageofLevelsinBinaryTree637.java │ │ ├── BalancedBinaryTree110.java │ │ ├── BinarySearchTreeIterator173.java │ │ ├── BinarySearchTreetoGreaterSumTree1038.java │ │ ├── BinaryTreeCameras968.java │ │ ├── BinaryTreeColoringGame1145.java │ │ ├── BinaryTreeInorderTraversal94.java │ │ ├── BinaryTreeMaximumPathSum124.java │ │ ├── BinaryTreePaths257.java │ │ ├── BinaryTreePostorderTraversal145.java │ │ ├── BinaryTreePreorderTraversal144.java │ │ ├── BinaryTreePruning814.java │ │ ├── BinaryTreeTilt563.java │ │ ├── CheckCompletenessofaBinaryTree958.java │ │ ├── CompleteBinaryTreeInserter919.java │ │ ├── ConstructBinarySearchTreefromPreorderTraversal1008.java │ │ ├── ConstructBinaryTreefromInorderandPostorderTraversal106.java │ │ ├── ConstructBinaryTreefromPreorderandInorderTraversal105.java │ │ ├── ConstructBinaryTreefromPreorderandPostorderTraversal889.java │ │ ├── ConstructStringfromBinaryTree606.java │ │ ├── ConvertBSTtoGreaterTree538.java │ │ ├── ConvertSortedArraytoBinarySearchTree108.java │ │ ├── CountGoodNodesinBinaryTree1448.java │ │ ├── DeepestLeavesSum1302.java │ │ ├── DeleteLeavesWithaGivenValue1325.java │ │ ├── DeleteNodeinaBST450.java │ │ ├── DeleteNodesAndReturnForest1110.java │ │ ├── DiameterofBinaryTree543.java │ │ ├── DistributeCoinsinBinaryTree979.java │ │ ├── EvenOddTree1609.java │ │ ├── FindDuplicateSubtrees652.java │ │ ├── FindElementsinaContaminatedBinaryTree1261.java │ │ ├── FindModeinBinarySearchTree501.java │ │ ├── FindaCorrespondingNodeofaBinaryTreeinaCloneofThatTree1379.java │ │ ├── FlattenBinaryTreetoLinkedList114.java │ │ ├── FlipBinaryTreeToMatchPreorderTraversal971.java │ │ ├── FlipEquivalentBinaryTrees951.java │ │ ├── HouseRobberIII337.java │ │ ├── ImplementTriePrefixTree208.java │ │ ├── IncreasingOrderSearchTree897.java │ │ ├── InsertintoaBinarySearchTree701.java │ │ ├── InsufficientNodesinRoottoLeafPaths1080.java │ │ ├── LeafSimilarTrees872.java │ │ ├── LinkedListinBinaryTree1367.java │ │ ├── LongestUnivaluePath687.java │ │ ├── LongestZigZagPathinaBinaryTree1372.java │ │ ├── LowestCommonAncestorofaBinarySearchTree235.java │ │ ├── LowestCommonAncestorofaBinaryTree236.java │ │ ├── MaximumBinaryTree654.java │ │ ├── MaximumBinaryTreeII998.java │ │ ├── MaximumDepthofBinaryTree104.java │ │ ├── MaximumDifferenceBetweenNodeandAncestor1026.java │ │ ├── MaximumLevelSumofaBinaryTree1161.java │ │ ├── MaximumProductofSplittedBinaryTree1339.java │ │ ├── MergeTwoBinaryTrees617.java │ │ ├── MinimumAbsoluteDifferenceinBST530.java │ │ ├── MinimumCostTreeFromLeafValues1130.java │ │ ├── MinimumTimetoCollectAllApplesinaTree1443.java │ │ ├── MostFrequentSubtreeSum508.java │ │ ├── NaryTreePostorderTraversal590.java │ │ ├── NaryTreePreorderTraversal589.java │ │ ├── NumberofGoodLeafNodesPairs1530.java │ │ ├── PathInZigzagLabelledBinaryTree1104.java │ │ ├── PathSum112.java │ │ ├── PathSumII113.java │ │ ├── PopulatingNextRightPointersinEachNode116.java │ │ ├── PopulatingNextRightPointersinEachNodeII117.java │ │ ├── PrintBinaryTree655.java │ │ ├── PseudoPalindromicPathsinaBinaryTree1457.java │ │ ├── RangeSumofBST938.java │ │ ├── RecoverBinarySearchTree99.java │ │ ├── RecoveraTreeFromPreorderTraversal1028.java │ │ ├── RedundantConnection684.java │ │ ├── RedundantConnectionII685.java │ │ ├── ReorderRoutestoMakeAllPathsLeadtotheCityZero1466.java │ │ ├── SameTree100.java │ │ ├── SecondMinimumNodeInaBinaryTree671.java │ │ ├── SerializeandDeserializeBST449.java │ │ ├── SerializeandDeserializeBinaryTree297.java │ │ ├── SmallestStringStartingFromLeaf988.java │ │ ├── SmallestSubtreewithalltheDeepestNodes865.java │ │ ├── StreamofCharacters1032.java │ │ ├── SubtreeofAnotherTree572.java │ │ ├── SumofDistancesinTree834.java │ │ ├── SumofNodeswithEvenValuedGrandparent1315.java │ │ ├── ThroneInheritance1600.java │ │ ├── TreeNode.java │ │ ├── TrimaBinarySearchTree699.java │ │ ├── TwoSumIVInputisaBST653.java │ │ ├── UnivaluedBinaryTree965.java │ │ ├── ValidateBinarySearchTree98.java │ │ ├── VerifyPreorderSerializationofaBinaryTree331.java │ │ └── VowelSpellchecker966.java │ └── union_find │ │ └── LargestComponentSizebyCommonFactor952.java └── kotlin │ ├── binary_search │ ├── ArrangingCoinsKotlin441.kt │ ├── BinarySearchKotlin704.kt │ ├── CapacityToShipPackagesWithinDDaysKotlin1011.kt │ ├── CarPoolingKotlin1094.kt │ ├── CountCompleteTreeNodesKotlin222.kt │ ├── CountNegativeNumbersinaSortedMatrixKotlin1351.kt │ ├── CountofRangeSumKotlin327.kt │ ├── CountofSmallerNumbersAfterSelfKotlin315.kt │ ├── DataStreamasDisjointIntervalsKotlin352.kt │ ├── DivideTwoIntegersKotlin29.kt │ ├── FindFirstandLastPositionofElementinSortedArrayKotlin34.kt │ ├── FindKClosestElementsKotlin658.kt │ ├── FindKthSmallestPairDistanceKotlin719.kt │ ├── FindMinimuminRotatedSortedArrayIIKotlin154.kt │ ├── FindMinimuminRotatedSortedArrayKotlin153.kt │ ├── FindPeakElementKotlin162.kt │ ├── FindRightIntervalKotlin436.kt │ ├── FindSmallestLetterGreaterThanTargetKotlin744.kt │ ├── FindinMountainArrayKotlin1095.kt │ ├── FindtheDuplicateNumberKotlin287.kt │ ├── FindtheSmallestDivisorGivenaThresholdKotlin1283.kt │ ├── FirstBadVersionKotlin278.kt │ ├── FourSumIIKotlin454.kt │ ├── GuessNumberHigherorLowerKotlin374.kt │ ├── HIndexIIKotlin275.kt │ ├── HIndexKotlin274.kt │ ├── HeatersKotlin475.kt │ ├── IntersectionofTwoArraysIIKotlin350.kt │ ├── IntersectionofTwoArraysKotlin349.kt │ ├── IsSubsequenceKotlin392.kt │ ├── KokoEatingBananasKotlin875.kt │ ├── KthSmallestElementinaBSTKotlin230.kt │ ├── KthSmallestElementinaSortedMatrixKotlin378.kt │ ├── KthSmallestNumberinMultiplicationTableKotlin668.kt │ ├── KthSmallestPrimeFractionKotlin786.kt │ ├── LongestDuplicateSubstringKotlin1044.kt │ ├── LongestIncreasingSubsequenceKotlin300.kt │ ├── MaxSumofRectangleNoLargerThanKKotlin363.kt │ ├── MaximumLengthofRepeatedSubarrayKotlin718.kt │ ├── MaximumSideLengthofaSquarewithSumLessthanorEqualtoThresholdKotlin1292.kt │ ├── MedianofTwoSortedArraysKotlin4.kt │ ├── MinimumNumberofDaystoMakemBouquetsKotlin1482.kt │ ├── MinimumSizeSubarraySumKotlin209.kt │ ├── NthMagicalNumberKotlin878.kt │ ├── OnlineElectionKotlin911.kt │ ├── OnlineMajorityElementInSubarrayKotlin1157.kt │ ├── PeakIndexinaMountainArrayKotlin852.kt │ ├── PowxnKotlin50.kt │ ├── PreimageSizeofFactorialZeroesFunctionKotlin793.kt │ ├── RandomPickwithBlacklistKotlin710.kt │ ├── RandomPickwithWeightKotlin528.kt │ ├── RandomPointinNonoverlappingRectanglesKotlin497.kt │ ├── ReadmeBuilder.kt │ ├── ReversePairsKotlin493.kt │ ├── RussianDollEnvelopesKotlin354.kt │ ├── SearchInsertPositionKotlin35.kt │ ├── Searcha2DMatrixIIKotlin240.kt │ ├── Searcha2DMatrixKotlin74.kt │ ├── SearchinRotatedSortedArrayIIKotlin81.kt │ ├── SearchinRotatedSortedArrayKotlin33.kt │ ├── ShortestSubarraywithSumatLeastKKotlin862.kt │ ├── SingleElementinaSortedArrayKotlin540.kt │ ├── SmallestGoodBaseKotlin483.kt │ ├── SplitArrayLargestSumKotlin410.kt │ ├── SqrtKotlin69.kt │ ├── SumofMutatedArrayClosesttoTargetKotlin1300.kt │ ├── SuperEggDropKotlin887.kt │ ├── SwiminRisingWaterKotlin778.kt │ ├── TheKWeakestRowsinaMatrixKotlin1337.kt │ ├── ThreeEqualPartsKotlin927.kt │ ├── TimeBasedKeyValueStoreKotlin981.kt │ ├── TwoSumIIInputarrayissortedKotlin167.kt │ ├── UglyNumberIIIKotlin1201.kt │ ├── UglyNumberIIKotlin264.kt │ ├── UglyNumberKotlin263.kt │ └── ValidPerfectSquareKotlin367.kt │ ├── bit_operation │ ├── IteratorforCombinationKotlin1286.kt │ ├── MaximumXORofTwoNumbersinanArrayKotlin421.kt │ ├── ReadmeBuilder.kt │ └── RepeatedDNASequencesKotlin187.kt │ ├── breadth_first_search │ ├── 1_matrix_utils │ ├── AllNodesDistanceKinBinaryTreeKotlin863.kt │ ├── AsFarfromLandasPossibleKotlin1162.kt │ ├── BinaryTreeLevelOrderTraversalIIKotlin107.kt │ ├── BinaryTreeLevelOrderTraversalKotlin102.kt │ ├── BinaryTreeRightSideViewKotlin199.kt │ ├── BinaryTreeZigzagLevelOrderTraversalKotlin103.kt │ ├── BusRoutesKotlin815.kt │ ├── CheckifThereisaValidPathinaGridKotlin1391.kt │ ├── CloneGraphKotlin133.kt │ ├── CourseScheduleIIKotlin210.kt │ ├── CousinsinBinaryTreeKotlin993.kt │ ├── CutOffTreesforGolfEventKotlin675.kt │ ├── EmployeeImportanceKotlin960.kt │ ├── EscapeaLargeMazeKotlin1036.kt │ ├── FindBottomLeftTreeValueKotlin513.kt │ ├── FindLargestValueinEachTreeRowKotlin515.kt │ ├── GetWatchedVideosbyYourFriendsKotlin1311.kt │ ├── JumpGameIIIKotlin1306.kt │ ├── JumpGameIVKotlin1345.kt │ ├── KSimilarStringsKotlin854.kt │ ├── Matrix01Kotlin542.kt │ ├── MaximumCandiesYouCanGetfromBoxesKotlin1298.kt │ ├── MaximumDepthofNaryTreeKotlin559.kt │ ├── MaximumWidthofBinaryTreeKotlin662.kt │ ├── MinesweeperKotlin529.kt │ ├── MinimumCosttoMakeatLeastOneValidPathinaGridKotlin1368.kt │ ├── MinimumDepthofBinaryTreeKotlin111.kt │ ├── MinimumHeightTreesKotlin310.kt │ ├── MinimumMovestoMoveaBoxtoTheirTargetLocationKotlin1263.kt │ ├── MinimumMovestoReachTargetwithRotationsKotlin1210.kt │ ├── MinimumNumberofFlipstoConvertBinaryMatrixtoZeroMatrixKotlin1284.kt │ ├── NaryTreeLevelOrderTraversalKotlin429.kt │ ├── NetworkDelayTimeKotlin743.kt │ ├── NumberofIslandsKotlin200.kt │ ├── NumberofOperationstoMakeNetworkConnectedKotlin1319.kt │ ├── OpentheLockKotlin752.kt │ ├── PacificAtlanticWaterFlowKotlin417.kt │ ├── ReadmeBuilder.kt │ ├── RemoveInvalidParenthesesKotlin301.kt │ ├── RottingOrangesKotlin994.kt │ ├── SequentialDigitsKotlin1291.kt │ ├── ShortestBridgeKotlin934.kt │ ├── ShortestPathVisitingAllNodesKotlin847.kt │ ├── ShortestPathinBinaryMatrixKotlin1091.kt │ ├── ShortestPathinaGridwithObstaclesEliminationKotlin1293.kt │ ├── ShortestPathtoGetAllKeysKotlin864.kt │ ├── ShortestPathwithAlternatingColorsKotlin1129.kt │ ├── SlidingPuzzleKotlin773.kt │ ├── SnakesandLaddersKotlin909.kt │ ├── SumRoottoLeafNumbersKotlin129.kt │ ├── SumofLeftLeavesKotlin404.kt │ ├── SumofRootToLeafBinaryNumbersKotlin1022.kt │ ├── SurroundedRegionsKotlin130.kt │ ├── SymmetricTreeKotlin101.kt │ ├── TrappingRainWaterIIKotlin407.kt │ ├── VerticalOrderTraversalofaBinaryTreeKotlin987.kt │ ├── WordLadderIIKotlin126.kt │ ├── WordLadderKotlin127.kt │ └── ZombieInMatrixKotlin.kt │ ├── depth_first_search │ ├── AllPathsFromSourcetoTargetKotlin797.kt │ ├── CombinationSumIIIKotlin216.kt │ ├── CombinationSumKotlin39.kt │ ├── FloodFillKotlin733.kt │ ├── LetterCombinationsofaPhoneNumberKotlin17.kt │ ├── NumberofNodesintheSubTreeWiththeSameLabelKotlin1519.kt │ ├── NumbersWithSameConsecutiveDifferencesKotlin967.kt │ ├── ReadmeBuilder.kt │ ├── ReadmeBuilder2.kt │ ├── ReadmeBuilder3.kt │ ├── ReconstructItineraryKotlin332.kt │ ├── SubsetsIIKotlin90.kt │ ├── SubsetsKotlin78.kt │ ├── TargetSumKotlin494.kt │ ├── UniqueBinarySearchTreesIIKotlin95.kt │ ├── UniqueBinarySearchTreesKotlin96.kt │ ├── UniquePathsIIIKotlin980.kt │ ├── WordBreakIIKotlin140.kt │ ├── WordSearchIIKotlin212.kt │ └── WordSearchKotlin79.kt │ ├── dynamic_programming │ ├── BestTimetoBuyandSellStockwithCooldownKotlin309.kt │ ├── ClimbingStairsKotlin70.kt │ ├── CoinChange2Kotlin518.kt │ ├── CoinChangeKotlin322.kt │ ├── CountSquareSubmatriceswithAllOnesKotlin1277.kt │ ├── DungeonGameKotlin174.kt │ ├── EditDistanceKotlin72.kt │ ├── FibonacciNumberKotlin509.kt │ ├── HouseRobberIIKotlin213.kt │ ├── HouseRobberKotlin198.kt │ ├── LargestDivisibleSubsetKotlin368.kt │ ├── LargestSizeOfRussianDollStringKotlin.kt │ ├── MaximumProfitinJobSchedulingKotlin1235.kt │ ├── MaximumSubarrayKotlin53.kt │ ├── MaximumSumCircularSubarrayKotlin918.kt │ ├── MinimumCostForTicketsKotlin983.kt │ ├── NumberofLongestIncreasingSubsequenceKotlin673.kt │ ├── PerfectSquaresKotlin279.kt │ ├── ReadmeBuilder.kt │ ├── StoneGameIVKotlin1510.kt │ ├── TwoCitySchedulingKotlin1029.kt │ ├── UncrossedLinesKotlin1035.kt │ ├── UniquePathsIIKotlin63.kt │ ├── UniquePathsKotlin62.kt │ └── WordBreakKotlin139.kt │ ├── graph │ ├── CheapestFlightsWithinKStopsKotlin787.kt │ ├── CourseScheduleKotlin207.kt │ ├── EvaluateDivisionKotlin399.kt │ ├── IsGraphBipartiteKotlin785.kt │ ├── PossibleBipartitionKotlin886.kt │ └── ReadmeBuilder.kt │ ├── hash_map_set │ ├── DesignHashMapKotlin706.kt │ ├── DesignHashSetKotlin705.kt │ ├── DistributeCandiesKotlin575.kt │ ├── FindDuplicateFileinSystemKotlin609.kt │ ├── InsertDeleteGetRandomO1DuplicatesallowedKotlin381.kt │ ├── InsertDeleteGetRandomO1Kotlin380.kt │ ├── ReadmeBuilder.kt │ ├── ReduceArraySizetoTheHalf1Kotlin338.kt │ └── TwoSumKotlin1.kt │ ├── list_array │ ├── BagofTokensKotlin948.kt │ ├── ChampagneTowerKotlin799.kt │ ├── DeleteNodeinaLinkedListKotlin237.kt │ ├── DistributeCandiestoPeopleKotlin1103.kt │ ├── FlattenaMultilevelDoublyLinkedListKotlin430.kt │ ├── GasStationKotlin134.kt │ ├── ImageOverlapKotlin835.kt │ ├── InsertIntervalKotlin57.kt │ ├── InsertionSortListKotlin147.kt │ ├── IntervalListIntersectionsKotlin986.kt │ ├── KdiffPairsinanArrayKotlin532.kt │ ├── LinkedListCycleIIKotlin142.kt │ ├── LinkedListCycleKotlin141.kt │ ├── MaximizeDistancetoClosestPersonKotlin849.kt │ ├── MaximumProductSubarrayKotlin152.kt │ ├── MaximumSubarrayKotlin53.kt │ ├── MergeTwoSortedListsKotlin21.kt │ ├── MiddleoftheLinkedListKotlin876.kt │ ├── MinimumNumberofArrowstoBurstBalloonsKotlin452.kt │ ├── NumberofRecentCallsKotlin933.kt │ ├── OddEvenLinkedListKotlin328.kt │ ├── ReadmeBuilder.kt │ ├── RemoveCoveredIntervalsKotlin1288.kt │ ├── RemoveLinkedListElementsKotlin203.kt │ ├── ReorderListKotlin143.kt │ ├── RobotBoundedInCircleKotlin1041.kt │ ├── RotateListKotlin61.kt │ ├── SortListKotlin148.kt │ ├── SubarrayProductLessThanKKotlin713.kt │ ├── SummaryRangesKotlin228.kt │ └── TopKFrequentElementsKotlin347.kt │ ├── not_categorized │ ├── CheckIfItIsaStraightLineKotlin1232.kt │ ├── ComplementofBase10IntegerKotlin1009.kt │ ├── FindtheTownJudgeKotlin997.kt │ ├── FirstUniqueCharacterinaStringKotlin387.kt │ ├── JewelsandStonesKotlin771.kt │ ├── MajorityElementKotlin169.kt │ ├── MaximumNestingDepthofTwoValidParenthesesStringsKotlin1111.kt │ ├── NonoverlappingIntervalsKotlin435.kt │ └── QueueReconstructionbyHeightKotlin406.kt │ ├── not_categorized_easy │ ├── FizzBuzzKotlin412.kt │ ├── GetMaximuminGeneratedArrayKotlin1646.kt │ ├── InvertBinaryTreeKotlin226.kt │ └── SearchinaBinarySearchTreeKotlin700.kt │ ├── sliding_window │ ├── FindAllAnagramsinaStringKotlin438.kt │ ├── PermutationinStringKotlin567.kt │ ├── ReadmeBuilder.kt │ └── SlidingWindowMaximumKotlin239.kt │ ├── stack │ ├── AsteroidCollisionKotlin735.kt │ ├── OnlineStockSpanKotlin901.kt │ ├── Pattern132Kotlin456.kt │ ├── ReadmeBuilder.kt │ └── RemoveDuplicateLettersKotlin316.kt │ ├── string_integer │ ├── AddBinaryKotlin67.kt │ ├── AddDigitsKotlin258.kt │ ├── AngleBetweenHandsofaClockKotlin1344.kt │ ├── BuddyStringsKotlin859.kt │ ├── BullsandCowsKotlin299.kt │ ├── CompareVersionNumbersKotlin165.kt │ ├── ConsecutiveCharactersKotlin1446.kt │ ├── ContiguousArrayKotlin525.kt │ ├── CountingBitsKotlin338.kt │ ├── DetectCapitalKotlin520.kt │ ├── ExcelSheetColumnNumberKotlin171.kt │ ├── ExcelSheetColumnTitleKotlin168.kt │ ├── FindAllDuplicatesinanArrayKotlin442.kt │ ├── FindtheDifferenceKotlin389.kt │ ├── FirstMissingPositiveKotlin41.kt │ ├── GoatLatinKotlin824.kt │ ├── HammingDistanceKotlin461.kt │ ├── IslandPerimeterKotlin463.kt │ ├── LargestNumberKotlin179.kt │ ├── LargestTimeforGivenDigitsKotlin949.kt │ ├── LengthofLastWordKotlin58.kt │ ├── LongestPalindromeKotlin409.kt │ ├── MinimumDominoRotationsForEqualRowKotlin1007.kt │ ├── NumberComplementKotlin476.kt │ ├── PartitionLabelsKotlin763.kt │ ├── PascalsTriangleIIKotlin119.kt │ ├── PascalsTriangleKotlin118.kt │ ├── PermutationSequenceKotlin60.kt │ ├── PermutationsIIKotlin47.kt │ ├── PermutationsKotlin46.kt │ ├── PlusOneKotlin66.kt │ ├── PowerofFourKotlin342.kt │ ├── PowerofThreeKotlin326.kt │ ├── PowerofTwoKotlin231.kt │ ├── PrisonCellsAfterNDaysKotlin957.kt │ ├── RansomNoteKotlin383.kt │ ├── ReadmeBuilder.kt │ ├── RemoveKDigitsKotlin402.kt │ ├── RepeatedSubstringPatternKotlin459.kt │ ├── ReverseBitsKotlin190.kt │ ├── ReverseStringKotlin344.kt │ ├── ReverseWordsinaStringKotlin151.kt │ ├── SingleNumberIIIKotlin260.kt │ ├── SingleNumberIIKotlin137.kt │ ├── SingleNumberKotlin136.kt │ ├── SortArrayByParityIIKotlin922.kt │ ├── SortArrayByParityKotlin905.kt │ ├── SortCharactersByFrequencyKotlin451.kt │ ├── TaskSchedulerKotlin621.kt │ ├── TeemoAttackingKotlin495.kt │ ├── ThreeSumClosestKotlin16.kt │ ├── ThreeSumKotlin15.kt │ ├── ValidPalindromeIIKotlin680.kt │ ├── ValidPalindromeKotlin125.kt │ ├── ValidParenthesesKotlin20.kt │ ├── ValidateIPAddressKotlin468.kt │ ├── WordPatternKotlin290.kt │ └── sort_an_array_912 │ │ ├── BubbleSortKotlin.kt │ │ ├── InsertionSortKotlin.kt │ │ ├── KClosestPointstoOriginKotlin973.kt │ │ ├── MergeSortKotlin.kt │ │ ├── QuickSortKotlin.kt │ │ ├── SelectionSortKotlin.kt │ │ └── SortColorsKotlin75.kt │ ├── top_interview_easy │ └── array │ │ ├── BestTimetoBuyandSellStockIIIKotlin123.kt │ │ ├── BestTimetoBuyandSellStockIIKotlin122.kt │ │ ├── BestTimetoBuyandSellStockKotlin121.kt │ │ ├── ContainsDuplicateIIIKotlin220.kt │ │ ├── ContainsDuplicateIIKotlin219.kt │ │ ├── ContainsDuplicateKotlin217.kt │ │ ├── MoveZeroesKotlin283.kt │ │ ├── PancakeSortingKotlin969.kt │ │ ├── ReadmeBuilder.kt │ │ ├── RemoveDuplicatesfromSortedArrayKotlin26.kt │ │ ├── RotateArrayKotlin189.kt │ │ ├── RotateImageKotlin48.kt │ │ └── ValidSudokuKotlin36.kt │ ├── tree │ ├── AddOneRowtoTreeKotlin623.kt │ ├── AddandSearchWordKotlin211.kt │ ├── AllElementsinTwoBinarySearchTreesKotlin1305.kt │ ├── AverageofLevelsinBinaryTreeKotlin637.kt │ ├── BalancedBinaryTreeKotlin110.kt │ ├── BinarySearchTreeIteratorKotlin173.kt │ ├── BinaryTreeCamerasKotlin968.kt │ ├── BinaryTreeInorderTraversalKotlin94.kt │ ├── BinaryTreeMaximumPathSumKotlin124.kt │ ├── BinaryTreePathsKotlin257.kt │ ├── BinaryTreePostorderTraversalKotlin145.kt │ ├── BinaryTreePreorderTraversalKotlin144.kt │ ├── BinaryTreePruningKotlin814.kt │ ├── BinaryTreeTiltKotlin563.kt │ ├── CheckCompletenessofaBinaryTreeKotlin958.kt │ ├── CompleteBinaryTreeInserterKotlin919.kt │ ├── ConstructBinarySearchTreefromPreorderTraversalKotlin1008.kt │ ├── ConstructBinaryTreefromInorderandPostorderTraversalKotlin106.kt │ ├── ConstructBinaryTreefromPreorderandInorderTraversalKotlin105.kt │ ├── ConstructBinaryTreefromPreorderandPostorderTraversalKotlin889.kt │ ├── ConstructStringfromBinaryTreeKotlin606.kt │ ├── ConvertBSTtoGreaterTreeKotlin538.kt │ ├── ConvertSortedArraytoBinarySearchTreeKotlin108.kt │ ├── DeepestLeavesSumKotlin1302.kt │ ├── DeleteNodeinaBSTKotlin450.kt │ ├── DiameterofBinaryTreeKotlin543.kt │ ├── DistributeCoinsinBinaryTreeKotlin979.kt │ ├── FindDuplicateSubtreesKotlin652.kt │ ├── FindModeinBinarySearchTreeKotlin501.kt │ ├── FlattenBinaryTreetoLinkedListKotlin114.kt │ ├── FlipEquivalentBinaryTreesKotlin951.kt │ ├── HouseRobberIIIKotlin337.kt │ ├── ImplementTriePrefixTreeKotlin208.kt │ ├── IncreasingOrderSearchTreeKotlin897.kt │ ├── InsertintoaBinarySearchTreeKotlin701.kt │ ├── LeafSimilarTreesKotlin872.kt │ ├── LongestUnivaluePathKotlin687.kt │ ├── LowestCommonAncestorofaBinarySearchTreeKotlin235.kt │ ├── LowestCommonAncestorofaBinaryTreeKotlin236.kt │ ├── MaximumBinaryTreeIIKotlin998.kt │ ├── MaximumBinaryTreeKotlin654.kt │ ├── MaximumDepthofBinaryTreeKotlin104.kt │ ├── MaximumDifferenceBetweenNodeandAncestorKotlin1026.kt │ ├── MaximumProductofSplittedBinaryTreeKotlin1339.kt │ ├── MergeTwoBinaryTreesKotlin617.kt │ ├── MinimumAbsoluteDifferenceinBSTKotlin530.kt │ ├── MinimumCostTreeFromLeafValuesKotlin1130.kt │ ├── MostFrequentSubtreeSumKotlin508.kt │ ├── NaryTreePostorderTraversalKotlin590.kt │ ├── NaryTreePreorderTraversalKotlin589.kt │ ├── PathInZigzagLabelledBinaryTreeKotlin1104.kt │ ├── PathSumIIIKotlin437.kt │ ├── PathSumIIKotlin113.kt │ ├── PathSumKotlin112.kt │ ├── PopulatingNextRightPointersinEachNodeIIKotlin117.kt │ ├── PopulatingNextRightPointersinEachNodeKotlin116.kt │ ├── PrintBinaryTreeKotlin655.kt │ ├── RangeSumofBSTKotlin938.kt │ ├── ReadmeBuilder.kt │ ├── RecoverBinarySearchTreeKotlin99.kt │ ├── RecoveraTreeFromPreorderTraversalKotlin1028.kt │ ├── RedundantConnectionIIKotlin685.kt │ ├── RedundantConnectionKotlin684.kt │ ├── SameTreeKotlin100.kt │ ├── SecondMinimumNodeInaBinaryTreeKotlin671.kt │ ├── SerializeandDeserializeBSTKotlin449.kt │ ├── SerializeandDeserializeBinaryTreeKotlin297.kt │ ├── SmallestSubtreewithalltheDeepestNodesKotlin865.kt │ ├── StreamofCharactersKotlin1032.kt │ ├── SubtreeofAnotherTreeKotlin572.kt │ ├── SumofDistancesinTreeKotlin834.kt │ ├── TrimaBinarySearchTreeKotlin699.kt │ ├── TwoSumIVInputisaBSTKotlin653.kt │ ├── UnivaluedBinaryTreeKotlin965.kt │ └── ValidateBinarySearchTreeKotlin98.kt │ └── union_find │ └── LargestComponentSizebyCommonFactorKotlin952.kt ├── test └── java │ └── binary_search │ ├── BinarySearch704Test.java │ ├── CapacityToShipPackagesWithinDDays1011Test.java │ ├── DivideTwoIntegers29Test.java │ ├── FindFirstandLastPositionofElementinSortedArray34Test.java │ ├── FindMinimuminRotatedSortedArray153Test.java │ ├── FindMinimuminRotatedSortedArrayII154Test.java │ ├── FindPeakElement162Test.java │ ├── FindtheDuplicateNumber287Test.java │ ├── FindtheSmallestDivisorGivenaThreshold1283Test.java │ ├── HIndex274Test.java │ ├── HIndexII275Test.java │ ├── IsSubsequence392Test.java │ ├── KokoEatingBananas875Test.java │ ├── KthSmallestElementinaSortedMatrix378Test.java │ ├── LongestIncreasingSubsequence300Test.java │ ├── MinimumSizeSubarraySum209Test.java │ ├── PeakIndexinaMountainArray852Test.java │ ├── Powxn50Test.java │ ├── SearchInsertPosition35Test.java │ ├── SearchinRotatedSortedArrayII81Test.java │ ├── Sqrt69Test.java │ ├── SumofMutatedArrayClosesttoTarget1300Test.java │ └── TwoSumIIInputarrayissorted167Test.java └── tree.md /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | .idea/ 3 | build/ 4 | gradle/ 5 | gradlew.bat 6 | gradlew 7 | -------------------------------------------------------------------------------- /interviews/Data Migration 0 downtime.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MagicienDeCode/LeetCode_Solution/3a9d677aa7773744dbe9e325186c1f589a769001/interviews/Data Migration 0 downtime.pdf -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "LeetCode_Solution" 2 | -------------------------------------------------------------------------------- /src/BFS_ALL_IN_ONE.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MagicienDeCode/LeetCode_Solution/3a9d677aa7773744dbe9e325186c1f589a769001/src/BFS_ALL_IN_ONE.pdf -------------------------------------------------------------------------------- /src/BS_ALL_IN_ONE.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MagicienDeCode/LeetCode_Solution/3a9d677aa7773744dbe9e325186c1f589a769001/src/BS_ALL_IN_ONE.pdf -------------------------------------------------------------------------------- /src/DFS_ALL_IN_ONE.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MagicienDeCode/LeetCode_Solution/3a9d677aa7773744dbe9e325186c1f589a769001/src/DFS_ALL_IN_ONE.pdf -------------------------------------------------------------------------------- /src/TREE_ALL_IN_ONE.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MagicienDeCode/LeetCode_Solution/3a9d677aa7773744dbe9e325186c1f589a769001/src/TREE_ALL_IN_ONE.pdf -------------------------------------------------------------------------------- /src/main/java/Challenge2.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | class Challenge2 { 4 | 5 | private final HashSet integers = new HashSet<>(); 6 | private int root = -1; 7 | 8 | public void addNode(int child, int parent) { 9 | if (!integers.contains(parent)) { 10 | root = parent; 11 | } 12 | integers.add(child); 13 | } 14 | 15 | public int findRoot() { 16 | return root; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/binary_search/CarPooling1094.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | public class CarPooling1094 { 4 | public boolean carPooling(int[][] trips, int capacity) { 5 | final int[] timeArray = new int[1001]; 6 | for (int[] trip : trips) { 7 | timeArray[trip[1]] += trip[0]; 8 | timeArray[trip[2]] -= trip[0]; 9 | } 10 | int current = 0; 11 | for (int t : timeArray) { 12 | current += t; 13 | if (current > capacity) { 14 | return false; 15 | } 16 | } 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/binary_search/FindPeakElement162.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | public class FindPeakElement162 { 4 | public int findPeakElement(int[] nums) { 5 | int left = 0; 6 | int right = nums.length - 1; 7 | while (left + 1 < right) { 8 | final int mid = left + (right - left) / 2; 9 | if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) { 10 | return mid; 11 | } else if (nums[mid - 1] < nums[mid]) { 12 | left = mid; 13 | } else { 14 | right = mid; 15 | } 16 | } 17 | return nums[left] > nums[right] ? left : right; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/binary_search/PeakIndexinaMountainArray852.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | public class PeakIndexinaMountainArray852 { 4 | public int peakIndexInMountainArray(int[] nums) { 5 | int left = 0; 6 | int right = nums.length - 1; 7 | while (left + 1 < right) { 8 | final int mid = left + (right - left) / 2; 9 | if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) { 10 | return mid; 11 | } else if (nums[mid - 1] < nums[mid]) { 12 | left = mid; 13 | } else { 14 | right = mid; 15 | } 16 | } 17 | return nums[left] > nums[right] ? left : right; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/binary_search/Sqrt69.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | public class Sqrt69 { 4 | public int mySqrt(int x) { 5 | int left = 0; 6 | // sqrt (Int.MAX_VALUE) = 46340.95 7 | int right = 46340; 8 | while (left + 1 < right) { 9 | final int mid = left + (right - left) / 2; 10 | if (mid * mid == x) { 11 | return mid; 12 | } else if (mid * mid < x) { 13 | left = mid; 14 | } else { 15 | right = mid; 16 | } 17 | } 18 | if (right * right <= x) { 19 | return right; 20 | } else { 21 | return left; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/binary_search/UglyNumber263.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | public class UglyNumber263 { 4 | public boolean isUgly(int num) { 5 | if (num <= 0) { 6 | return false; 7 | } 8 | while (num % 2 == 0) { 9 | num /= 2; 10 | } 11 | while (num % 3 == 0) { 12 | num /= 3; 13 | } 14 | while (num % 5 == 0) { 15 | num /= 5; 16 | } 17 | return num == 1; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/binary_search/ValidPerfectSquare367.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | public class ValidPerfectSquare367 { 4 | public boolean isPerfectSquare(int num) { 5 | int left = 0; 6 | // sqrt (Int.MAX_VALUE) = 46340.95 7 | int right = 46340; 8 | while (left + 1 < right) { 9 | final int mid = left + (right - left) / 2; 10 | if (mid * mid == num) { 11 | return true; 12 | } else if (mid * mid < num) { 13 | left = mid; 14 | } else { 15 | right = mid; 16 | } 17 | } 18 | return right * right == num; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/bit_operation/CheckIfaStringContainsAllBinaryCodesofSizeK1461.java: -------------------------------------------------------------------------------- 1 | package bit_operation; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class CheckIfaStringContainsAllBinaryCodesofSizeK1461 { 7 | public boolean hasAllCodes(String s, int k) { 8 | int total = 1 << k; 9 | final Set set = new HashSet<>(); 10 | for (int i = k; i < s.length(); i++) { 11 | final String current = s.substring(i - k, i); 12 | if (!set.contains(current)) { 13 | set.add(current); 14 | if (--total == 0) { 15 | return true; 16 | } 17 | } 18 | } 19 | return false; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/bit_operation/GrayCode89.java: -------------------------------------------------------------------------------- 1 | package bit_operation; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class GrayCode89 { 7 | public List grayCode(int n) { 8 | final List results = new LinkedList<>(); 9 | final int end = 1 << n; 10 | for (int i = 0; i < end; i++) { 11 | results.add(i ^ i >> 1); 12 | } 13 | return results; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/bit_operation/Numberof1Bits191.java: -------------------------------------------------------------------------------- 1 | package bit_operation; 2 | 3 | public class Numberof1Bits191 { 4 | // you need to treat n as an unsigned value 5 | public int hammingWeight(int n) { 6 | int result = 0; 7 | for (int i = 0; i < 32; i++) { 8 | if ((n & 1) == 1) { 9 | ++result; 10 | } 11 | n >>= 1; 12 | } 13 | return result; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/breadth_first_search/BrokenCalculator991.java: -------------------------------------------------------------------------------- 1 | package breadth_first_search; 2 | 3 | public class BrokenCalculator991 { 4 | public int brokenCalc(int start, int end) { 5 | int result = 0; 6 | while (end > start) { 7 | ++result; 8 | if (end % 2 == 1) { 9 | end++; 10 | } else { 11 | end >>= 1; 12 | } 13 | } 14 | return result + start - end; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/depth_first_search/1_matrix_utils: -------------------------------------------------------------------------------- 1 | private final int[] deltaX = {0, 0, -1, 1}; 2 | private final int[] deltaY = {-1, 1, 0, 0}; 3 | 4 | private boolean inBound( 5 | int[][] grid, 6 | int x, 7 | int y 8 | ) { 9 | return x >= 0 && y >= 0 && x < grid.length && y < grid[0].length; 10 | } -------------------------------------------------------------------------------- /src/main/java/depth_first_search/CountSortedVowelStrings1641.java: -------------------------------------------------------------------------------- 1 | package depth_first_search; 2 | 3 | public class CountSortedVowelStrings1641 { 4 | private int result; 5 | 6 | public int countVowelStrings(int n) { 7 | result = 0; 8 | dfs(0, n); 9 | return result; 10 | } 11 | 12 | private void dfs(int startIndex, int n) { 13 | if (n == 0) { 14 | ++result; 15 | } else { 16 | for (int i = startIndex; i < 5; i++) { 17 | dfs(i, n - 1); 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/depth_first_search/UniqueBinarySearchTrees96.java: -------------------------------------------------------------------------------- 1 | package depth_first_search; 2 | 3 | public class UniqueBinarySearchTrees96 { 4 | // https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0 5 | // https://en.wikipedia.org/wiki/Catalan_number 6 | public int numTrees(int n) { 7 | long result = 1L; 8 | for (int index = n + 1; index <= n * 2; index++) { 9 | result = result * index / (index - n); 10 | } 11 | return (int) (result / (n + 1)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/design/MapSumPairs677.java: -------------------------------------------------------------------------------- 1 | package design; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MapSumPairs677 { 7 | private final Map map = new HashMap<>(); 8 | private final Map prefixMap = new HashMap<>(); 9 | 10 | public void insert(String key, int val) { 11 | final int delta = val - map.getOrDefault(key, 0); 12 | map.put(key, val); 13 | String s = ""; 14 | for (char c : key.toCharArray()) { 15 | s += c; 16 | prefixMap.put(s, delta + prefixMap.getOrDefault(s, 0)); 17 | } 18 | } 19 | 20 | public int sum(String prefix) { 21 | return prefixMap.getOrDefault(prefix, 0); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/design/MyCalendarIII732.java: -------------------------------------------------------------------------------- 1 | package design; 2 | 3 | import java.util.TreeMap; 4 | 5 | public class MyCalendarIII732 { 6 | 7 | private final TreeMap map = new TreeMap<>(); 8 | 9 | public int book(int start, int end) { 10 | map.put(start, 1 + map.getOrDefault(start, 0)); 11 | map.put(end, -1 + map.getOrDefault(end, 0)); 12 | int max = 0; 13 | int count = 0; 14 | for (int v : map.values()) { 15 | count += v; 16 | max = Math.max(max, count); 17 | } 18 | return max; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/ArithmeticSlices413.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class ArithmeticSlices413 { 4 | public int numberOfArithmeticSlices(int[] a) { 5 | int result = 0; 6 | int consecutive = 0; 7 | 8 | for (int i = 2; i < a.length; i++) { 9 | if (a[i - 2] - a[i - 1] == a[i - 1] - a[i]) { 10 | ++consecutive; 11 | result += consecutive; 12 | } else { 13 | consecutive = 0; 14 | } 15 | } 16 | 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/BestTimetoBuyandSellStockwithTransactionFee714.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class BestTimetoBuyandSellStockwithTransactionFee714 { 4 | public int maxProfit(int[] prices, int fee) { 5 | int result = 0; 6 | for (int index = 1; index < prices.length; index++) { 7 | result += prices[index] - fee > prices[index - 1] ? 8 | prices[index] - prices[index - 1] - fee : 9 | 0; 10 | } 11 | return result; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/CoinChange2518.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class CoinChange2518 { 4 | public int change(int amount, int[] coins) { 5 | final int[] dp = new int[amount + 1]; 6 | dp[0] = 1; 7 | for (int coin : coins) { 8 | for (int index = coin; index <= amount; index++) { 9 | dp[index] += dp[index - coin]; 10 | } 11 | } 12 | return dp[amount]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/CoinChange322.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | import java.util.Arrays; 4 | 5 | public class CoinChange322 { 6 | public int coinChange(int[] coins, int amount) { 7 | final int[] dp = new int[amount + 1]; 8 | Arrays.fill(dp, amount + 1); 9 | dp[0] = 0; 10 | for (int index = 1; index <= amount; index++) { 11 | for (int coin : coins) { 12 | if (coin <= index) { 13 | dp[index] = Math.min(dp[index], dp[index - coin] + 1); 14 | } 15 | } 16 | } 17 | return dp[amount] > amount ? -1 : dp[amount]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/CombinationSumIV377.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class CombinationSumIV377 { 4 | public int combinationSum4(int[] nums, int target) { 5 | final int[] dp = new int[target + 1]; 6 | dp[0] = 1; 7 | for (int index = 1; index <= target; index++) { 8 | for (int coin : nums) { 9 | if (coin <= index) { 10 | dp[index] += dp[index - coin]; 11 | } 12 | } 13 | } 14 | return dp[target]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/FibonacciNumber509.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class FibonacciNumber509 { 4 | public int fib(int n) { 5 | if (n < 1) { 6 | return n; 7 | } 8 | int current = n - 1; 9 | int int1 = 0; 10 | int int2 = 1; 11 | while (current > 0) { 12 | final int sum = int1 + int2; 13 | int1 = int2; 14 | int2 = sum; 15 | --current; 16 | } 17 | return int2; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/HouseRobber198.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class HouseRobber198 { 4 | public int rob(int[] nums) { 5 | if (nums.length == 0) { 6 | return 0; 7 | } 8 | if (nums.length == 1) { 9 | return nums[0]; 10 | } 11 | final int[] dp = new int[nums.length]; 12 | dp[0] = nums[0]; 13 | dp[1] = Math.max(nums[1], dp[0]); 14 | for (int i = 2; i < nums.length; i++) { 15 | dp[i] = Math.max( 16 | // take current + i-2 17 | nums[i] + dp[i - 2], 18 | // do not take current, previous 19 | dp[i - 1] 20 | ); 21 | } 22 | return dp[nums.length - 1]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/MaximumSubarray53.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class MaximumSubarray53 { 4 | public int maxSubArray(int[] nums) { 5 | // Kadane’s Algorithm 6 | int max = Integer.MIN_VALUE; 7 | int currentMax = 0; 8 | for (int n : nums) { 9 | currentMax = Math.max(n, n + currentMax); 10 | max = Math.max(max, currentMax); 11 | } 12 | return max; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/NthTribonacciNumber1137.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class NthTribonacciNumber1137 { 4 | public int tribonacci(int n) { 5 | final int[] tribonacci = new int[38]; 6 | tribonacci[0] = 0; 7 | tribonacci[1] = 1; 8 | tribonacci[2] = 1; 9 | for (int i = 3; i <= n; i++) { 10 | tribonacci[i] = tribonacci[i - 1] + 11 | tribonacci[i - 2] + 12 | tribonacci[i - 3]; 13 | } 14 | return tribonacci[n]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/UniquePaths62.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class UniquePaths62 { 4 | public int uniquePaths(int m, int n) { 5 | final int[][] dp = new int[m + 1][n + 1]; 6 | dp[0][1] = 1; 7 | for (int i = 1; i <= m; i++) { 8 | for (int j = 1; j <= n; j++) { 9 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 10 | } 11 | } 12 | return dp[m][n]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/UniquePathsII63.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class UniquePathsII63 { 4 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 5 | final int m = obstacleGrid.length; 6 | final int n = obstacleGrid[0].length; 7 | final int[][] dp = new int[m + 1][n + 1]; 8 | dp[0][1] = 1; 9 | for (int i = 1; i <= m; i++) { 10 | for (int j = 1; j <= n; j++) { 11 | if (obstacleGrid[i - 1][j - 1] == 0) { 12 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 13 | } 14 | } 15 | } 16 | return dp[m][n]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/dynamic_programming/WiggleSubsequence376.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | public class WiggleSubsequence376 { 4 | public int wiggleMaxLength(int[] nums) { 5 | if (nums.length < 2) { 6 | return nums.length; 7 | } 8 | int up = 1; 9 | int down = 1; 10 | for (int i = 1; i < nums.length; i++) { 11 | if (nums[i] > nums[i - 1]) { 12 | up = down + 1; 13 | } 14 | if (nums[i] < nums[i - 1]) { 15 | down = up + 1; 16 | } 17 | } 18 | return Math.max(up, down); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/ArrayPartitionI561.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ArrayPartitionI561 { 6 | public int arrayPairSum(int[] nums) { 7 | int sum = 0; 8 | Arrays.sort(nums); 9 | for (int i = 0; i < nums.length; i += 2) { 10 | sum += nums[i]; 11 | } 12 | return sum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/BuildanArrayWithStackOperations1441.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class BuildanArrayWithStackOperations1441 { 7 | public List buildArray(int[] target, int n) { 8 | final List list = new LinkedList<>(); 9 | final int end = Math.min(target[target.length - 1], n); 10 | int index = 0; 11 | for (int i = 1; i <= end; i++) { 12 | list.add("Push"); 13 | if (target[index] == i) { 14 | ++index; 15 | } else { 16 | list.add("Pop"); 17 | } 18 | } 19 | return list; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/CanMakeArithmeticProgressionFromSequence1502.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.Arrays; 4 | 5 | public class CanMakeArithmeticProgressionFromSequence1502 { 6 | public boolean canMakeArithmeticProgression(int[] arr) { 7 | Arrays.sort(arr); 8 | final int gap = arr[1] - arr[0]; 9 | for (int i = 2; i < arr.length; i++) { 10 | if (arr[i] - arr[i - 1] != gap) { 11 | return false; 12 | } 13 | } 14 | return true; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/CheckifWordEqualsSummationofTwoWords1880.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class CheckifWordEqualsSummationofTwoWords1880 { 4 | public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { 5 | return transform(targetWord) == transform(firstWord) + transform(secondWord); 6 | } 7 | 8 | private int transform(String word) { 9 | int result = 0; 10 | for (int i = 0; i < word.length(); i++) { 11 | final int current = word.charAt(i) - 'a'; 12 | result = result * 10 + current; 13 | } 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/CheckiftheSentenceIsPangram1832.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class CheckiftheSentenceIsPangram1832 { 4 | public boolean checkIfPangram(String sentence) { 5 | final boolean[] letters = new boolean[26]; 6 | for (char c : sentence.toCharArray()) { 7 | letters[c - 'a'] = true; 8 | } 9 | boolean result = true; 10 | for (boolean l : letters) { 11 | result &= l; 12 | } 13 | return result; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/CountItemsMatchingaRule1773.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.List; 4 | 5 | public class CountItemsMatchingaRule1773 { 6 | public int countMatches(List> items, String ruleKey, String ruleValue) { 7 | int index = 0; 8 | if (ruleKey.equals("color")) { 9 | index = 1; 10 | } else if (ruleKey.equals("name")) { 11 | index = 2; 12 | } 13 | int count = 0; 14 | for (List item : items) { 15 | if (item.get(index).equals(ruleValue)) { 16 | ++count; 17 | } 18 | } 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/CountofMatchesinTournament1688.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class CountofMatchesinTournament1688 { 4 | public int numberOfMatches(int n) { 5 | int count = 0; 6 | while (n > 1) { 7 | if (n % 2 == 0) { 8 | n /= 2; 9 | count += n; 10 | } else { 11 | count += n / 2; 12 | n = (n + 1) >> 1; 13 | } 14 | } 15 | return count; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/CreateTargetArrayintheGivenOrder1389.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class CreateTargetArrayintheGivenOrder1389 { 7 | public int[] createTargetArray(int[] nums, int[] index) { 8 | final List results = new ArrayList<>(); 9 | for (int i = 0; i < nums.length; i++) { 10 | results.add(index[i], nums[i]); 11 | } 12 | return results.stream().mapToInt(Integer::intValue).toArray(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/DIStringMatch942.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class DIStringMatch942 { 4 | public int[] diStringMatch(String s) { 5 | final int[] result = new int[s.length() + 1]; 6 | int right = s.length(); 7 | int left = 0; 8 | for (int i = 0; i < result.length - 1; i++) { 9 | if (s.charAt(i) == 'D') { 10 | result[i] = right--; 11 | } else { 12 | result[i] = left++; 13 | } 14 | } 15 | result[s.length()] = left + 1; 16 | return result; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/DecodeXORedArray1720.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class DecodeXORedArray1720 { 4 | public int[] decode(int[] encoded, int first) { 5 | final int[] result = new int[encoded.length + 1]; 6 | result[0] = first; 7 | for (int i = 0; i < encoded.length; i++) { 8 | result[i + 1] = encoded[i] ^ result[i]; 9 | } 10 | return result; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/DecompressRunLengthEncodedList1313.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class DecompressRunLengthEncodedList1313 { 7 | public int[] decompressRLElist(int[] nums) { 8 | final List results = new ArrayList<>(); 9 | for (int i = 0; i < nums.length - 1; i += 2) { 10 | final int freq = nums[i]; 11 | final int value = nums[i + 1]; 12 | for (int j = 0; j < freq; j++) { 13 | results.add(value); 14 | } 15 | } 16 | return results.stream().mapToInt(Integer::intValue).toArray(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/DecryptStringfromAlphabettoIntegerMapping1309.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class DecryptStringfromAlphabettoIntegerMapping1309 { 4 | public String freqAlphabets(String s) { 5 | final StringBuilder sb = new StringBuilder(); 6 | for (char c : s.toCharArray()) { 7 | if (c == '#') { 8 | final int before = (sb.charAt(sb.length() - 2) - 'a' + 1) * 10 + (sb.charAt(sb.length() - 1) - 'a' + 1); 9 | sb.setCharAt(sb.length() - 2, (char) ('a' + before - 1)); 10 | sb.deleteCharAt(sb.length() - 1); 11 | } else { 12 | sb.append((char) ('a' + Integer.parseInt(String.valueOf(c)) - 1)); 13 | } 14 | } 15 | return sb.toString(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/DesignanOrderedStream1656.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class DesignanOrderedStream1656 { 7 | 8 | final String[] array; 9 | int lastReturnIndex = 0; 10 | 11 | public DesignanOrderedStream1656(int n) { 12 | array = new String[n]; 13 | } 14 | 15 | public List insert(int idKey, String value) { 16 | array[idKey - 1] = value; 17 | final List results = new LinkedList<>(); 18 | while (lastReturnIndex < array.length && array[lastReturnIndex] != null) { 19 | results.add(array[lastReturnIndex]); 20 | ++lastReturnIndex; 21 | } 22 | return results; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/DetermineColorofaChessboardSquare1812.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class DetermineColorofaChessboardSquare1812 { 4 | public boolean squareIsWhite(String coordinates) { 5 | final int i = Integer.parseInt(String.valueOf(coordinates.charAt(1))) % 2; 6 | if ((coordinates.charAt(0)-'a')%2==0){ 7 | return i == 0; 8 | }else { 9 | return i != 0; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/FindNUniqueIntegersSumuptoZero1304.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class FindNUniqueIntegersSumuptoZero1304 { 4 | public int[] sumZero(int n) { 5 | final int[] resultArray = new int[n]; 6 | int index = 0; 7 | for (int i = 1; i <= n / 2; i++) { 8 | resultArray[index++] = i; 9 | resultArray[index++] = -i; 10 | } 11 | if (n % 2 != 0) { 12 | resultArray[index] = 0; 13 | } 14 | return resultArray; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/FindNumberswithEvenNumberofDigits1295.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class FindNumberswithEvenNumberofDigits1295 { 4 | public int findNumbers(int[] nums) { 5 | int count = 0; 6 | for (int n : nums) { 7 | int d = 0; 8 | while (n > 0) { 9 | n /= 10; 10 | d++; 11 | } 12 | count += d % 2 == 0 ? 1 : 0; 13 | } 14 | return count; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/FindtheHighestAltitude1732.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class FindtheHighestAltitude1732 { 4 | public int largestAltitude(int[] gain) { 5 | int current = 0; 6 | int max = 0; 7 | for (int g : gain) { 8 | current += g; 9 | max = Math.max(max, current); 10 | } 11 | return max; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/GenerateaStringWithCharactersThatHaveOddCounts1374.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class GenerateaStringWithCharactersThatHaveOddCounts1374 { 4 | public String generateTheString(int n) { 5 | if (n % 2 == 0) { 6 | return "a".repeat(n - 1) + "x"; 7 | } else { 8 | return "x".repeat(n); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/HeightChecker1051.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.Arrays; 4 | 5 | public class HeightChecker1051 { 6 | public int heightChecker(int[] heights) { 7 | final int[] clone = heights.clone(); 8 | Arrays.sort(clone); 9 | int diff = 0; 10 | for (int i = 0; i < heights.length; i++) { 11 | if (heights[i] != clone[i]) { 12 | ++diff; 13 | } 14 | } 15 | return diff; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/KidsWiththeGreatestNumberofCandies1431.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class KidsWiththeGreatestNumberofCandies1431 { 7 | public List kidsWithCandies(int[] candies, int extraCandies) { 8 | int max = 0; 9 | for (int c : candies) { 10 | if (c > max) { 11 | max = c; 12 | } 13 | } 14 | final List results = new LinkedList<>(); 15 | for (int c : candies) { 16 | if (c + extraCandies >= max) { 17 | results.add(true); 18 | } else { 19 | results.add(false); 20 | } 21 | } 22 | return results; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MakeTwoArraysEqualbyReversingSubarrays1460.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MakeTwoArraysEqualbyReversingSubarrays1460 { 7 | public boolean canBeEqual(int[] target, int[] arr) { 8 | final Map map = new HashMap<>(); 9 | for (int t : target) { 10 | map.put(t, 1 + map.getOrDefault(t, 0)); 11 | } 12 | for (int a : arr) { 13 | map.put(a, map.getOrDefault(a, 0) - 1); 14 | } 15 | for (int v : map.values()) { 16 | if (v != 0) { 17 | return false; 18 | } 19 | } 20 | return true; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MatrixDiagonalSum1572.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class MatrixDiagonalSum1572 { 4 | public int diagonalSum(int[][] mat) { 5 | int left = 0; 6 | int right = mat[0].length - 1; 7 | int sum = 0; 8 | for (int[] ints : mat) { 9 | sum += ints[left]; 10 | sum += ints[right]; 11 | ++left; 12 | --right; 13 | } 14 | if (mat.length % 2 != 0) { 15 | sum -= mat[mat.length >> 1][mat[0].length >> 1]; 16 | } 17 | return sum; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/Maximum69Number1323.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class Maximum69Number1323 { 4 | public int maximum69Number(int num) { 5 | final StringBuilder stringBuilder = new StringBuilder(String.valueOf(num)); 6 | for (int i = 0; i < stringBuilder.length(); i++) { 7 | if (stringBuilder.charAt(i) == '6') { 8 | stringBuilder.setCharAt(i, '9'); 9 | break; 10 | } 11 | } 12 | return Integer.parseInt(stringBuilder.toString()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MaximumNestingDepthoftheParentheses1614.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class MaximumNestingDepthoftheParentheses1614 { 4 | public int maxDepth(String s) { 5 | int stack = 0; 6 | int result = 0; 7 | for (char c : s.toCharArray()) { 8 | if (c == '(') { 9 | ++stack; 10 | result = Math.max(result, stack); 11 | } 12 | if (c == ')') { 13 | --stack; 14 | } 15 | } 16 | return result; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MaximumNumberofBallsinaBox1742.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class MaximumNumberofBallsinaBox1742 { 4 | public int countBalls(int lowLimit, int highLimit) { 5 | final int[] box = new int[46]; 6 | for (int i = lowLimit; i <= highLimit; i++) { 7 | box[calculate(i)]++; 8 | } 9 | int max = 0; 10 | for (int b : box) { 11 | max = Math.max(b, max); 12 | } 13 | return max; 14 | } 15 | 16 | private int calculate(int i) { 17 | int result = 0; 18 | while (i > 0) { 19 | result += i % 10; 20 | i /= 10; 21 | } 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MaximumPopulationYear1854.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class MaximumPopulationYear1854 { 4 | public int maximumPopulation(int[][] logs) { 5 | final int[] years = new int[101]; 6 | for (int[] log : logs) { 7 | for (int i = log[0]; i < log[1]; i++) { 8 | years[i - 1950]++; 9 | } 10 | } 11 | int maxIndex = 101; 12 | int max = 0; 13 | for (int i = years.length - 1; i >= 0; i--) { 14 | if (years[i] >= max) { 15 | max = years[i]; 16 | maxIndex = i; 17 | } 18 | } 19 | return maxIndex + 1950; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MaximumProductofTwoElementsinanArray1464.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class MaximumProductofTwoElementsinanArray1464 { 4 | public int maxProduct(int[] nums) { 5 | int max1 = 0; 6 | int max2 = 0; 7 | for (int n : nums) { 8 | if (n == max1) { 9 | max2 = max1; 10 | } 11 | if (n > max1) { 12 | max2 = max1; 13 | max1 = n; 14 | } 15 | if (n > max2 && n < max1) { 16 | max2 = n; 17 | } 18 | } 19 | return (max1 - 1) * (max2 - 1); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MaximumUnitsonaTruck1710.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MaximumUnitsonaTruck1710 { 6 | public int maximumUnits(int[][] boxTypes, int truckSize) { 7 | Arrays.sort(boxTypes, (o1, o2) -> Integer.compare(o2[1], o1[1])); 8 | int count = 0; 9 | for (int[] boxType : boxTypes) { 10 | if (truckSize >= boxType[0]) { 11 | truckSize -= boxType[0]; 12 | count += boxType[0] * boxType[1]; 13 | } else { 14 | count += boxType[1] * truckSize; 15 | break; 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MinimumMovestoEqualArrayElements453.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class MinimumMovestoEqualArrayElements453 { 4 | /* 5 | Increasing n - 1 smaller elements by 1 = decreasing only the max element by 1 6 | */ 7 | public int minMoves(int[] nums) { 8 | int min = Integer.MAX_VALUE; 9 | for (int n : nums) { 10 | min = Math.min(min, n); 11 | } 12 | int count = 0; 13 | for (int n : nums) { 14 | count += n - min; 15 | } 16 | return count; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MinimumMovestoEqualArrayElementsII462.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MinimumMovestoEqualArrayElementsII462 { 6 | public int minMoves2(int[] nums) { 7 | Arrays.sort(nums); 8 | if (nums.length % 2 == 0) { 9 | return count(nums, (nums[nums.length >> 1] + nums[nums.length / 2 - 1]) / 2); 10 | } else { 11 | return count(nums, nums[nums.length >> 1]); 12 | } 13 | } 14 | 15 | private int count(int[] nums, int i) { 16 | int count = 0; 17 | for (int n : nums) { 18 | count += n > i ? n - i : i - n; 19 | } 20 | return count; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MinimumMovestoEqualArrayElementsKotlin453.kt: -------------------------------------------------------------------------------- 1 | package easy_easy 2 | 3 | class MinimumMovestoEqualArrayElementsKotlin453 { 4 | fun minMoves(nums: IntArray): Int { 5 | val min = nums.min()!! 6 | return nums.map { it - min }.sum() 7 | } 8 | } -------------------------------------------------------------------------------- /src/main/java/easy_easy/MinimumOperationstoMaketheArrayIncreasing1827.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class MinimumOperationstoMaketheArrayIncreasing1827 { 4 | public int minOperations(int[] nums) { 5 | int count = 0; 6 | for (int i = 1; i < nums.length; i++) { 7 | final int aim = nums[i - 1] + 1; 8 | final int diff = aim - nums[i]; 9 | if (diff > 0) { 10 | count += diff; 11 | nums[i] = aim; 12 | } 13 | } 14 | return count; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/MinimumTimeVisitingAllPoints1266.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class MinimumTimeVisitingAllPoints1266 { 4 | public int minTimeToVisitAllPoints(int[][] points) { 5 | int count = 0; 6 | for (int i = 1; i < points.length; i++) { 7 | final int[] p1 = points[i - 1]; 8 | final int[] p2 = points[i]; 9 | count += Math.max(Math.abs(p1[0] - p2[0]), Math.abs(p1[1] - p2[1])); 10 | } 11 | return count; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/NRepeatedElementinSize2NArray961.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class NRepeatedElementinSize2NArray961 { 7 | public int repeatedNTimes(int[] nums) { 8 | final Set set = new HashSet<>(); 9 | for (int n : nums) { 10 | if (set.contains(n)) { 11 | return n; 12 | } else { 13 | set.add(n); 14 | } 15 | } 16 | return -1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/NumberOfRectanglesThatCanFormTheLargestSquare1725.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class NumberOfRectanglesThatCanFormTheLargestSquare1725 { 7 | public int countGoodRectangles(int[][] rectangles) { 8 | final Map map = new HashMap<>(); 9 | int max = 0; 10 | for (int[] rect : rectangles) { 11 | final int m = Math.min(rect[0], rect[1]); 12 | if (m >= max) { 13 | max = m; 14 | map.put(m, 1 + map.getOrDefault(m, 0)); 15 | } 16 | } 17 | return map.get(max); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/NumberofGoodPairs1512.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class NumberofGoodPairs1512 { 4 | public int numIdenticalPairs(int[] nums) { 5 | final int[] count = new int[101]; 6 | for (int n : nums) { 7 | count[n]++; 8 | } 9 | int result = 0; 10 | for (int c : count) { 11 | result += c * (c - 1) / 2; 12 | } 13 | return result; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/NumberofStudentsDoingHomeworkataGivenTime1450.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class NumberofStudentsDoingHomeworkataGivenTime1450 { 4 | public int busyStudent(int[] startTime, int[] endTime, int queryTime) { 5 | int count = 0; 6 | for (int i = 0; i < startTime.length; i++) { 7 | if (startTime[i] <= queryTime && queryTime <= endTime[i]) { 8 | ++count; 9 | } 10 | } 11 | return count; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/ReplaceAllDigitswithCharacters1844.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class ReplaceAllDigitswithCharacters1844 { 4 | public String replaceDigits(String s) { 5 | final StringBuilder stringBuilder = new StringBuilder(s); 6 | for (int i = 1; i < stringBuilder.length(); i += 2) { 7 | stringBuilder.setCharAt(i, (char) (stringBuilder.charAt(i - 1) + Integer.parseInt(String.valueOf(stringBuilder.charAt(i))))); 8 | } 9 | return stringBuilder.toString(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/ReplaceElementswithGreatestElementonRightSide1299.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class ReplaceElementswithGreatestElementonRightSide1299 { 4 | public int[] replaceElements(int[] arr) { 5 | int max = arr[arr.length - 1]; 6 | arr[arr.length - 1] = -1; 7 | for (int i = arr.length - 2; i >= 0; i--) { 8 | final int current = arr[i]; 9 | arr[i] = max; 10 | max = Math.max(max, current); 11 | } 12 | return arr; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/ReverseInteger7.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class ReverseInteger7 { 4 | public int reverse(int x) { 5 | int result = 0; 6 | int previous; 7 | while (x != 0) { 8 | previous = result; 9 | result = result * 10 + x % 10; 10 | x /= 10; 11 | if (result / 10 != previous) { 12 | return 0; 13 | } 14 | } 15 | return result; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/ReverseWordsinaStringIII557.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class ReverseWordsinaStringIII557 { 4 | public String reverseWords(String s) { 5 | final StringBuilder result = new StringBuilder(); 6 | StringBuilder temp = new StringBuilder(); 7 | for (char c : s.toCharArray()) { 8 | if (c == ' ') { 9 | result.append(temp.reverse()).append(' '); 10 | temp = new StringBuilder(); 11 | } else { 12 | temp.append(c); 13 | } 14 | } 15 | result.append(temp.reverse()); 16 | return result.toString(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/RichestCustomerWealth1672.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class RichestCustomerWealth1672 { 4 | public int maximumWealth(int[][] accounts) { 5 | int max = 0; 6 | for (int[] account : accounts) { 7 | int sum = 0; 8 | for (int a : account) { 9 | sum += a; 10 | } 11 | max = Math.max(max, sum); 12 | } 13 | return max; 14 | } 15 | /* 16 | public int maximumWealth(int[][] accounts) { 17 | int max = 0; 18 | for (int[] account : accounts) { 19 | max = Math.max(max, Arrays.stream(account).sum()); 20 | } 21 | return max; 22 | } 23 | */ 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/RobotReturntoOrigin657.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class RobotReturntoOrigin657 { 4 | public boolean judgeCircle(String moves) { 5 | int x = 0; 6 | int y = 0; 7 | for (char c : moves.toCharArray()) { 8 | switch (c) { 9 | case 'U': 10 | ++x; 11 | break; 12 | case 'D': 13 | --x; 14 | break; 15 | case 'L': 16 | ++y; 17 | break; 18 | case 'R': 19 | --y; 20 | break; 21 | } 22 | } 23 | return x == y && x == 0; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/ShuffleString1528.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class ShuffleString1528 { 4 | public String restoreString(String s, int[] indices) { 5 | final StringBuilder stringBuilder = new StringBuilder(s); 6 | for (int i = 0; i < s.length(); i++) { 7 | stringBuilder.setCharAt(indices[i], s.charAt(i)); 8 | } 9 | return stringBuilder.toString(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/ShuffletheArray1470.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class ShuffletheArray1470 { 4 | public int[] shuffle(int[] nums, int n) { 5 | final int[] results = new int[nums.length]; 6 | int index = 0; 7 | for (int i = 0; i < n; i++) { 8 | results[index++] = nums[i]; 9 | results[index++] = nums[i + n]; 10 | } 11 | return results; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/SignoftheProductofanArray1822.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class SignoftheProductofanArray1822 { 4 | public int arraySign(int[] nums) { 5 | boolean positive = true; 6 | for (int n : nums) { 7 | if (n == 0) { 8 | return 0; 9 | } 10 | if (n < 0) { 11 | positive = !positive; 12 | } 13 | } 14 | return positive ? 1 : -1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/SortIntegersbyTheNumberof1BitsKotlin1356.kt: -------------------------------------------------------------------------------- 1 | package easy_easy 2 | 3 | class SortIntegersbyTheNumberof1BitsKotlin1356 { 4 | fun sortByBits(arr: IntArray): IntArray = 5 | arr.sortedWith(Comparator { o1, o2 -> 6 | val compareCount = compareValues(count1(o1), count1(o2)) 7 | if (compareCount == 0) { 8 | compareValues(o1, o2) 9 | } else { 10 | compareCount 11 | } 12 | }).toIntArray() 13 | 14 | private fun count1(n: Int): Int { 15 | var result = 0 16 | for (i in 0 until 32) { 17 | if (n.and(1.shl(i)) != 0) { 18 | ++result 19 | } 20 | } 21 | return result 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /src/main/java/easy_easy/SubtracttheProductandSumofDigitsofanInteger1281.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class SubtracttheProductandSumofDigitsofanInteger1281 { 4 | public int subtractProductAndSum(int n) { 5 | int product = 1; 6 | int sum = 0; 7 | while (n > 0) { 8 | final int temp = n % 10; 9 | product *= temp; 10 | sum += temp; 11 | n /= 10; 12 | } 13 | return product - sum; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/SumofAllOddLengthSubarrays1588.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class SumofAllOddLengthSubarrays1588 { 4 | public int sumOddLengthSubarrays(int[] arr) { 5 | int sum = 0; 6 | for (int i = 1; i <= arr.length; i += 2) { 7 | for (int j = 0; j < arr.length; j++) { 8 | if (j + i <= arr.length) { 9 | for (int k = 0; k < i; k++) { 10 | sum += arr[j + k]; 11 | } 12 | } 13 | } 14 | } 15 | return sum; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/SumofDigitsinBaseK1837.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class SumofDigitsinBaseK1837 { 4 | public int sumBase(int n, int k) { 5 | int sum = 0; 6 | while (n > 0) { 7 | sum += n % k; 8 | n /= k; 9 | } 10 | return sum; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/SumofUniqueElements1748.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class SumofUniqueElements1748 { 4 | public int sumOfUnique(int[] nums) { 5 | final int[] count = new int[101]; 6 | for (int n : nums) { 7 | count[n]++; 8 | } 9 | int sum = 0; 10 | for (int i = 1; i < count.length; i++) { 11 | if (count[i] == 1) { 12 | sum += i; 13 | } 14 | } 15 | return sum; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/ToLowerCase709.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class ToLowerCase709 { 4 | public String toLowerCase(String s) { 5 | final StringBuilder sb = new StringBuilder(); 6 | for (char c : s.toCharArray()) { 7 | if (c >= 65 && c <= 90) { 8 | sb.append((char) (c + 32)); 9 | } else { 10 | sb.append(c); 11 | } 12 | } 13 | return sb.toString(); 14 | } 15 | /* 16 | public String toLowerCase(String s) { 17 | return s.toLowerCase(); 18 | } 19 | */ 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/TruncateSentence1816.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class TruncateSentence1816 { 4 | public String truncateSentence(String s, int k) { 5 | int count = 0; 6 | int index = s.length(); 7 | for (int i = 0; i < s.length(); i++) { 8 | if (s.charAt(i) == ' ') { 9 | if (++count == k) { 10 | index = i; 11 | break; 12 | } 13 | } 14 | } 15 | return s.substring(0, index); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/UniqueNumberofOccurrences1207.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | import java.util.HashMap; 4 | import java.util.HashSet; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | public class UniqueNumberofOccurrences1207 { 9 | public boolean uniqueOccurrences(int[] arr) { 10 | final Map map = new HashMap<>(); 11 | for (int a : arr) { 12 | map.put(a, 1 + map.getOrDefault(a, 0)); 13 | } 14 | final Set set = new HashSet<>(); 15 | for (int v : map.values()) { 16 | if (set.contains(v)) { 17 | return false; 18 | } 19 | set.add(v); 20 | } 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/easy_easy/XOROperationinanArray1486.java: -------------------------------------------------------------------------------- 1 | package easy_easy; 2 | 3 | public class XOROperationinanArray1486 { 4 | public int xorOperation(int n, int start) { 5 | int result = start; 6 | for (int i = 1; i < n; i++) { 7 | result ^= (start + i * 2); 8 | } 9 | return result; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/graph/CheapestFlightsWithinKStops787.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import java.util.Arrays; 4 | 5 | public class CheapestFlightsWithinKStops787 { 6 | public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { 7 | int[] dp = new int[n]; 8 | Arrays.fill(dp, 1000000); 9 | dp[src] = 0; 10 | for (int time = 0; time <= k; time++) { 11 | final int[] newDp = Arrays.copyOf(dp, dp.length); 12 | for (int[] f : flights) { 13 | newDp[f[1]] = Math.min(newDp[f[1]], dp[f[0]] + f[2]); 14 | } 15 | dp = newDp; 16 | } 17 | return dp[dst] >= 1000000 ? -1 : dp[dst]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/hash_map_set/DesignHashSet705.java: -------------------------------------------------------------------------------- 1 | package hash_map_set; 2 | 3 | public class DesignHashSet705 { 4 | 5 | private final boolean[] table = new boolean[1000001]; 6 | 7 | public void add(int key) { 8 | table[key] = true; 9 | } 10 | 11 | public void remove(int key) { 12 | table[key] = false; 13 | } 14 | 15 | /** 16 | * Returns true if this set contains the specified element. 17 | */ 18 | public boolean contains(int key) { 19 | return table[key]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/hash_map_set/DistributeCandies575.java: -------------------------------------------------------------------------------- 1 | package hash_map_set; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class DistributeCandies575 { 7 | public int distributeCandies(int[] candies) { 8 | final Set set = new HashSet<>(); 9 | for (int c : candies) { 10 | set.add(c); 11 | } 12 | return Math.min(set.size(), candies.length / 2); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/hash_map_set/LongestHarmoniousSubsequence594.java: -------------------------------------------------------------------------------- 1 | package hash_map_set; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class LongestHarmoniousSubsequence594 { 7 | public int findLHS(int[] nums) { 8 | int result = 0; 9 | final Map map = new HashMap<>(); 10 | for (int n : nums) { 11 | map.put(n, 1 + map.getOrDefault(n, 0)); 12 | if (map.containsKey(n + 1)) { 13 | result = Math.max(result, map.get(n) + map.get(n + 1)); 14 | } 15 | if (map.containsKey(n - 1)) { 16 | result = Math.max(result, map.get(n) + map.get(n - 1)); 17 | } 18 | } 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/hash_map_set/SetMismatch645.java: -------------------------------------------------------------------------------- 1 | package hash_map_set; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class SetMismatch645 { 7 | public int[] findErrorNums(int[] nums) { 8 | final Map map = new HashMap<>(); 9 | for (int n : nums) { 10 | map.put(n, map.getOrDefault(n, 0) + 1); 11 | } 12 | int twice = 0; 13 | int missing = 0; 14 | for (int i = 1; i <= nums.length; i++) { 15 | if (map.containsKey(i)) { 16 | if (map.get(i) == 2) { 17 | twice = i; 18 | } 19 | } else { 20 | missing = i; 21 | } 22 | } 23 | return new int[]{twice, missing}; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/hash_map_set/ShortEncodingofWords820.java: -------------------------------------------------------------------------------- 1 | package hash_map_set; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class ShortEncodingofWords820 { 8 | public int minimumLengthEncoding(String[] words) { 9 | final Set goods = new HashSet<>(Arrays.asList(words)); 10 | for (String w : words) { 11 | for (int i = 1; i < w.length(); i++) { 12 | goods.remove(w.substring(i)); 13 | } 14 | } 15 | int result = 0; 16 | for (String w : goods) { 17 | result += 1 + w.length(); 18 | } 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/hash_map_set/TwoSum1.java: -------------------------------------------------------------------------------- 1 | package hash_map_set; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class TwoSum1 { 7 | public int[] twoSum(int[] nums, int target) { 8 | final Map valueIndexMap = new HashMap<>(); 9 | valueIndexMap.put(nums[0], 0); 10 | for (int index = 1; index < nums.length; index++) { 11 | if (valueIndexMap.containsKey(target - nums[index])) { 12 | return new int[]{valueIndexMap.get(target - nums[index]), index}; 13 | } 14 | valueIndexMap.put(nums[index], index); 15 | } 16 | return null; 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/list_array/Candy135.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Candy135 { 6 | public int candy(int[] ratings) { 7 | final int[] candies = new int[ratings.length]; 8 | Arrays.fill(candies, 1); 9 | for (int i = 1; i < candies.length; i++) { 10 | if (ratings[i] > ratings[i - 1]) { 11 | candies[i] = candies[i - 1] + 1; 12 | } 13 | } 14 | int sum = candies[candies.length - 1]; 15 | for (int i = candies.length - 2; i >= 0; i--) { 16 | if (ratings[i] > ratings[i + 1]) { 17 | candies[i] = Math.max(candies[i], candies[i + 1] + 1); 18 | } 19 | sum += candies[i]; 20 | } 21 | return sum; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/list_array/ChampagneTower799.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class ChampagneTower799 { 4 | public double champagneTower(int poured, int queryRow, int queryGlass) { 5 | final double[][] result = new double[101][101]; 6 | result[0][0] = poured; 7 | for (int i = 0; i <= queryRow; i++) { 8 | for (int j = 0; j <= i; j++) { 9 | final double now = (result[i][j] - 1.0) / 2.0; 10 | if (now > 0) { 11 | result[i + 1][j] += now; 12 | result[i + 1][j + 1] += now; 13 | } 14 | } 15 | } 16 | return Math.min(1, result[queryRow][queryGlass]); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/list_array/ContainerWithMostWater11.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class ContainerWithMostWater11 { 4 | public int maxArea(int[] height) { 5 | int result = 0; 6 | int left = 0; 7 | int right = height.length - 1; 8 | while (left < right) { 9 | result = Math.max(result, Math.min(height[left], height[right]) * (right - left)); 10 | if (height[left] > height[right]) { 11 | right--; 12 | } else { 13 | left++; 14 | } 15 | } 16 | return result; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/list_array/DeleteNodeinaLinkedList237.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class DeleteNodeinaLinkedList237 { 4 | public void deleteNode(ListNode node) { 5 | final ListNode next = node.next; 6 | node.val = next.val; 7 | node.next = next.next; 8 | } 9 | 10 | public class ListNode { 11 | int val; 12 | ListNode next; 13 | 14 | ListNode(int x) { 15 | val = x; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/list_array/DistributeCandiestoPeople1103.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class DistributeCandiestoPeople1103 { 4 | public int[] distributeCandies(int candies, int numPeople) { 5 | final int[] resultArray = new int[numPeople]; 6 | int index = 0; 7 | int given = 1; 8 | while (candies > 0) { 9 | if (candies - given >= 0) { 10 | resultArray[index % numPeople] += given; 11 | } else { 12 | resultArray[index % numPeople] += candies; 13 | } 14 | candies -= given; 15 | ++index; 16 | ++given; 17 | } 18 | return resultArray; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/list_array/LinkedListCycle141.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class LinkedListCycle141 { 4 | public boolean hasCycle(ListNode head) { 5 | if (head == null) { 6 | return false; 7 | } 8 | ListNode slow = head; 9 | ListNode fast = head; 10 | while (fast != null && fast.next != null) { 11 | slow = slow.next; 12 | fast = fast.next.next; 13 | if (fast == slow) { 14 | return true; 15 | } 16 | } 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/list_array/ListNode.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class ListNode { 4 | int val; 5 | ListNode next; 6 | 7 | ListNode() { 8 | } 9 | 10 | ListNode(int val) { 11 | this.val = val; 12 | } 13 | 14 | ListNode(int val, ListNode next) { 15 | this.val = val; 16 | this.next = next; 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/list_array/MaxNumberofKSumPairs1679.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MaxNumberofKSumPairs1679 { 7 | public int maxOperations(int[] nums, int k) { 8 | int result = 0; 9 | final Map map = new HashMap<>(); 10 | for (int i : nums) { 11 | if (map.containsKey(k - i)) { 12 | if (map.get(k - i) > 0) { 13 | map.put(k - i, map.get(k - i) - 1); 14 | ++result; 15 | } 16 | } else { 17 | map.put(i, 1 + map.getOrDefault(i, 0)); 18 | } 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/list_array/MaximumProductSubarray152.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class MaximumProductSubarray152 { 4 | public int maxProduct(int[] nums) { 5 | if (nums.length == 0) { 6 | return 0; 7 | } 8 | int result = nums[0]; 9 | int max = nums[0]; 10 | int min = nums[0]; 11 | for (int i = 1; i < nums.length; i++) { 12 | int maxCurrent = max; 13 | int minCurrent = min; 14 | max = Math.max(Math.max(nums[i], maxCurrent * nums[i]), minCurrent * nums[i]); 15 | min = Math.min(Math.min(nums[i], minCurrent * nums[i]), maxCurrent * nums[i]); 16 | result = Math.max(max, result); 17 | } 18 | return result; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/list_array/MaximumSubarray53.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class MaximumSubarray53 { 4 | public int maxSubArray(int[] nums) { 5 | if (nums.length == 0) { 6 | return 0; 7 | } 8 | int result = Integer.MIN_VALUE; 9 | int current = 0; 10 | for (int n : nums) { 11 | current = Math.max(current + n, n); 12 | result = Math.max(result, current); 13 | } 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/list_array/MiddleoftheLinkedList876.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class MiddleoftheLinkedList876 { 4 | /* 5 | 1 -> 2 -> 3 -> 4 -> 5 6 | fast = 1,slow = 1 7 | fast = 3,slow = 2 8 | fast = 5,slow = 3 9 | 10 | 1 -> 2 -> 3 -> 4 11 | fast = 1,slow = 1 12 | fast = 3,slow = 2 13 | fast = null,slow = 3 14 | 15 | */ 16 | public ListNode middleNode(ListNode head) { 17 | ListNode fast = head; 18 | ListNode slow = head; 19 | while (fast != null && fast.next != null) { 20 | fast = fast.next.next; 21 | slow = slow.next; 22 | } 23 | return slow; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/list_array/OrderlyQueue899.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | import java.util.Arrays; 4 | 5 | public class OrderlyQueue899 { 6 | public String orderlyQueue(String s, int k) { 7 | if (k == 1) { 8 | String ans = s; 9 | for (int i = 0; i < s.length(); i++) { 10 | final String temp = s.substring(i) + s.substring(0, i); 11 | if (temp.compareTo(ans) < 0) { 12 | ans = temp; 13 | } 14 | } 15 | return ans; 16 | } else { 17 | final char[] chars = s.toCharArray(); 18 | Arrays.sort(chars); 19 | return new String(chars); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/list_array/RankTransformofanArray1331.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class RankTransformofanArray1331 { 8 | public int[] arrayRankTransform(int[] arr) { 9 | final int[] clone = arr.clone(); 10 | Arrays.sort(clone); 11 | final Map map = new HashMap<>(); 12 | int rank = 1; 13 | for (int i = 0; i < arr.length; i++) { 14 | if (!map.containsKey(clone[i])) { 15 | map.put(clone[i], rank++); 16 | } 17 | } 18 | for (int i = 0; i < arr.length; i++) { 19 | clone[i] = map.get(arr[i]); 20 | } 21 | return clone; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/list_array/RemoveDuplicatesfromSortedList83.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class RemoveDuplicatesfromSortedList83 { 4 | public ListNode deleteDuplicates(ListNode head) { 5 | ListNode current = head; 6 | while (current != null) { 7 | ListNode afterLastSameNode = current.next; 8 | while (afterLastSameNode != null && current.val == afterLastSameNode.val) { 9 | afterLastSameNode = afterLastSameNode.next; 10 | } 11 | current.next = afterLastSameNode; 12 | current = current.next; 13 | } 14 | return head; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/list_array/RemoveNthNodeFromEndofList19.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class RemoveNthNodeFromEndofList19 { 4 | public ListNode removeNthFromEnd(ListNode head, int n) { 5 | final ListNode preHead = new ListNode(); 6 | preHead.next = head; 7 | ListNode fast = preHead; 8 | ListNode slow = preHead; 9 | for (int i = 0; i <= n; i++) { 10 | fast = fast.next; 11 | } 12 | while (fast != null) { 13 | fast = fast.next; 14 | slow = slow.next; 15 | } 16 | slow.next = slow.next.next; 17 | return preHead.next; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/list_array/SubarrayProductLessThanK713.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | public class SubarrayProductLessThanK713 { 4 | public int numSubarrayProductLessThanK(int[] nums, int k) { 5 | if (k <= 1) { 6 | return 0; 7 | } 8 | int result = 0; 9 | int product = 1; 10 | int start = 0; 11 | for (int end = 0; end < nums.length; end++) { 12 | product *= nums[end]; 13 | while (product >= k) { 14 | product /= nums[start++]; 15 | } 16 | result += end - start + 1; 17 | } 18 | return result; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/list_array/ValidTriangleNumber611.java: -------------------------------------------------------------------------------- 1 | package list_array; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ValidTriangleNumber611 { 6 | public int triangleNumber(int[] nums) { 7 | int count = 0; 8 | Arrays.sort(nums); 9 | for (int i = 0; i < nums.length; i++) { 10 | int k = i + 2; 11 | for (int j = i + 1; j < nums.length - 1 && nums[i] != 0; j++) { 12 | while (k < nums.length && nums[i] + nums[j] > nums[k]) { 13 | k++; 14 | } 15 | count += k - j - 1; 16 | } 17 | } 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/ComplementofBase10Integer1009.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class ComplementofBase10Integer1009 { 4 | // Also see NumberComplementKotlin476 5 | /* 6 | 5 => 101 7 | flag => 111 (32) 8 | 9 | after while 10 | flag => 111...(29)000 11 | 12 | ~5 => 11111(29)010 13 | ~flag => 00(29)111 14 | 15 | result => 00000(30)10 => 2 16 | 17 | */ 18 | public int bitwiseComplement(int numN) { 19 | if (numN == 0) { 20 | return 1; 21 | } 22 | int flag = Integer.MAX_VALUE; 23 | while ((flag & numN) != 0) { 24 | flag <<= 1; 25 | } 26 | return ~flag & ~numN; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/FlipStringtoMonotoneIncreasing926.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class FlipStringtoMonotoneIncreasing926 { 4 | public int minFlipsMonoIncr(String s) { 5 | final int N = s.length(); 6 | final int[] P = new int[N + 1]; 7 | for (int i = 0; i < N; i++) { 8 | P[i + 1] = P[i] + (s.charAt(i) == '1' ? 1 : 0); 9 | } 10 | int result = Integer.MAX_VALUE; 11 | for (int i = 0; i < N + 1; i++) { 12 | result = Math.min(result, P[i] + N - i - (P[N] - P[i])); 13 | } 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/JewelsandStones771.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class JewelsandStones771 { 7 | public int numJewelsInStones(String strJ, String strS) { 8 | final Set jCharSet = new HashSet<>(strJ.length()); 9 | for (int i = 0; i < strJ.length(); i++) { 10 | jCharSet.add(strJ.charAt(i)); 11 | } 12 | int result = 0; 13 | for (int i = 0; i < strS.length(); i++) { 14 | if (jCharSet.contains(strS.charAt(i))) { 15 | result++; 16 | } 17 | } 18 | return result; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/MajorityElement169.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class MajorityElement169 { 4 | public int majorityElement(int[] nums) { 5 | int majority = nums[0]; 6 | int count = 0; 7 | for (int i : nums) { 8 | if (i == majority) { 9 | ++count; 10 | } else if (--count == 0) { 11 | count = 1; 12 | majority = i; 13 | } 14 | } 15 | return majority; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/PartitioningIntoMinimumNumberOfDeciBinaryNumbers1689.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class PartitioningIntoMinimumNumberOfDeciBinaryNumbers1689 { 4 | public int minPartitions(String n) { 5 | int max = 0; 6 | for (char c : n.toCharArray()) { 7 | max = Math.max(c - '0', max); 8 | } 9 | return max; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/PoorPigs458.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class PoorPigs458 { 4 | public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 5 | int rounds = minutesToTest / minutesToDie + 1; 6 | int pigs = 0; 7 | long num = 1; 8 | while (num < buckets) { 9 | num *= rounds; 10 | ++pigs; 11 | } 12 | return pigs; 13 | // return log(buckets-1) / log(rounds) + 1; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/RectangleArea223.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class RectangleArea223 { 4 | public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { 5 | final int area1 = (ax2 - ax1) * (ay2 - ay1); 6 | final int area2 = (bx2 - bx1) * (by2 - by1); 7 | if (Math.min(ax2, bx2) > Math.max(ax1, bx1) && Math.min(ay2, by2) > Math.max(ay1, by1)) { 8 | return area1 + area2 - (Math.min(ax2, bx2) - Math.max(ax1, bx1)) * (Math.min(ay2, by2) - Math.max(ay1, by1)); 9 | } 10 | return area1 + area2; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/ShiftingLetters848.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class ShiftingLetters848 { 4 | public String shiftingLetters(String s, int[] shifts) { 5 | final int[] timesShifts = shifts.clone(); 6 | for (int i = timesShifts.length - 2; i >= 0; i--) { 7 | timesShifts[i] = (timesShifts[i] + timesShifts[i + 1]) % 26; 8 | } 9 | final StringBuilder stringBuilder = new StringBuilder(); 10 | for (int i = 0; i < s.length(); i++) { 11 | stringBuilder.append( 12 | (char) ('a' + (s.charAt(i) - 'a' + timesShifts[i]) % 26) 13 | ); 14 | } 15 | return stringBuilder.toString(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/ShortestUnsortedContinuousSubarray581.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ShortestUnsortedContinuousSubarray581 { 6 | public int findUnsortedSubarray(int[] nums) { 7 | final int[] original = nums.clone(); 8 | Arrays.sort(nums); 9 | int start = nums.length; 10 | int end = 0; 11 | for (int i = 0; i < nums.length; i++) { 12 | if (nums[i] != original[i]) { 13 | start = Math.min(start, i); 14 | end = Math.max(end, i); 15 | } 16 | } 17 | return end >= start ? end - start + 1 : 0; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/SmallestIntegerDivisiblebyK1015.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class SmallestIntegerDivisiblebyK1015 { 4 | /* 5 | remainder = 1 6 | length_N = 1 7 | 8 | while remainder%K != 0 9 | N = remainder*10 + 1 10 | remainder = N%K 11 | length_N += 1 12 | 13 | return length_N 14 | */ 15 | public int smallestRepunitDivByK(int k) { 16 | int remainder = 0; 17 | for (int i = 1; i <= k; i++) { 18 | remainder = (remainder * 10 + 1) % k; 19 | if (remainder == 0) { 20 | return i; 21 | } 22 | } 23 | return -1; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/ThekthFactorofn1429.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class ThekthFactorofn1429 { 4 | public int kthFactor(int n, int k) { 5 | if (k > n) { 6 | return -1; 7 | } 8 | int index = 0; 9 | for (int i = n; i > 0; i--) { 10 | if (n % i == 0) { 11 | if (++index == k) { 12 | return n / i; 13 | } 14 | } 15 | } 16 | return -1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/not_categorized/ValidSquare593.java: -------------------------------------------------------------------------------- 1 | package not_categorized; 2 | 3 | public class ValidSquare593 { 4 | public double dist(int[] p1, int[] p2) { 5 | return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]); 6 | } 7 | public boolean check(int[] p1, int[] p2, int[] p3, int[] p4) { 8 | return dist(p1,p2) > 0 && dist(p1, p2) == dist(p2, p3) && dist(p2, p3) == dist(p3, p4) && dist(p3, p4) == dist(p4, p1) && dist(p1, p3) == dist(p2, p4); 9 | } 10 | public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { 11 | return check(p1, p2, p3, p4) || check(p1, p3, p2, p4) || check(p1, p2, p4, p3); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/CanPlaceFlowers605.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | public class CanPlaceFlowers605 { 4 | public boolean canPlaceFlowers(int[] flowerbed, int n) { 5 | for (int i = 0; i < flowerbed.length; i++) { 6 | if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0) 7 | ) { 8 | flowerbed[i++] = 1; 9 | --n; 10 | } 11 | } 12 | return n <= 0; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/FizzBuzz412.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class FizzBuzz412 { 7 | public List fizzBuzz(int n) { 8 | final List result = new LinkedList<>(); 9 | for (int i = 1; i <= n; i++) { 10 | if (i % 3 == 0) { 11 | if (i % 5 == 0) { 12 | result.add("FizzBuzz"); 13 | } else { 14 | result.add("Fizz"); 15 | } 16 | } else if (i % 5 == 0) { 17 | result.add("Buzz"); 18 | } else { 19 | result.add(String.valueOf(i)); 20 | } 21 | } 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/KthMissingPositiveNumber1539.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | public class KthMissingPositiveNumber1539 { 4 | public int findKthPositive(int[] arr, int k) { 5 | int index = 0; 6 | int result = -1; 7 | for (int i = 1; i < arr[arr.length - 1]; i++) { 8 | if (i == arr[index]) { 9 | index = index == arr.length - 1 ? index : index + 1; 10 | } else { 11 | result = i; 12 | } 13 | } 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/MergeSortedArray88.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | public class MergeSortedArray88 { 4 | public void merge(int[] nums1, int m, int[] nums2, int n) { 5 | int index1 = m - 1; 6 | int index2 = n - 1; 7 | int index = m + n - 1; 8 | while (index1 >= 0 && index2 >= 0) { 9 | if (nums1[index1] > nums2[index2]) { 10 | nums1[index--] = nums1[index1--]; 11 | } else { 12 | nums1[index--] = nums2[index2--]; 13 | } 14 | } 15 | while (index1 >= 0) { 16 | nums1[index--] = nums1[index1--]; 17 | } 18 | while (index2 >= 0) { 19 | nums1[index--] = nums2[index2--]; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/NumberofStepstoReduceaNumbertoZero1342.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | public class NumberofStepstoReduceaNumbertoZero1342 { 4 | public int numberOfSteps(int num) { 5 | int result = 0; 6 | while (num != 0) { 7 | if (num % 2 == 0) { 8 | num /= 2; 9 | } else { 10 | num--; 11 | } 12 | result++; 13 | } 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/RemovePalindromicSubsequences1332.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | public class RemovePalindromicSubsequences1332 { 4 | public int removePalindromeSub(String s) { 5 | if (s.isEmpty()) { 6 | return 0; 7 | } 8 | return isPalindromic(s) ? 1 : 2; 9 | } 10 | 11 | private boolean isPalindromic(String s) { 12 | int left = 0; 13 | int right = s.length() - 1; 14 | while (left < right) { 15 | if (s.charAt(left++) != s.charAt(right--)) { 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/UniqueEmailAddresses929.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class UniqueEmailAddresses929 { 7 | public int numUniqueEmails(String[] emails) { 8 | final Set normalized = new HashSet<>(); 9 | for (String mail : emails) { 10 | final String[] splits = mail.split("@"); 11 | final String local = splits[0].split("\\+")[0].replace(".", ""); 12 | normalized.add(local + "@" + splits[1]); 13 | } 14 | return normalized.size(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/ValidAnagram242.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | public class ValidAnagram242 { 4 | public boolean isAnagram(String s, String t) { 5 | if (s.isEmpty()) { 6 | return t.isEmpty(); 7 | } 8 | if (s.length() != t.length()) { 9 | return false; 10 | } 11 | final int[] hash = new int[26]; 12 | for (int i = 0; i < s.length(); i++) { 13 | hash[s.charAt(i) - 'a']++; 14 | hash[t.charAt(i) - 'a']--; 15 | } 16 | for (int i = 0; i < 26; i++) { 17 | if (hash[i] != 0) { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/not_categorized_easy/ValidMountainArray941.java: -------------------------------------------------------------------------------- 1 | package not_categorized_easy; 2 | 3 | public class ValidMountainArray941 { 4 | public boolean validMountainArray(int[] arr) { 5 | int index = 0; 6 | while (index + 1 < arr.length && arr[index] < arr[index + 1]) { 7 | ++index; 8 | } 9 | if (index == 0 || index == arr.length - 1) { 10 | return false; 11 | } 12 | while (index + 1 < arr.length && arr[index] > arr[index + 1]) { 13 | ++index; 14 | } 15 | return index == arr.length - 1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/sliding_window/BoatstoSavePeople881.java: -------------------------------------------------------------------------------- 1 | package sliding_window; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BoatstoSavePeople881 { 6 | public int numRescueBoats(int[] people, int limit) { 7 | Arrays.sort(people); 8 | int end = people.length - 1; 9 | int start = 0; 10 | int result = 0; 11 | while (start <= end) { 12 | ++result; 13 | if (people[start] + people[end] <= limit) { 14 | ++start; 15 | } 16 | --end; 17 | } 18 | return result; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/sliding_window/MaxConsecutiveOnes485.java: -------------------------------------------------------------------------------- 1 | package sliding_window; 2 | 3 | public class MaxConsecutiveOnes485 { 4 | public int findMaxConsecutiveOnes(int[] nums) { 5 | int left = 0; 6 | int right = 0; 7 | int max = 0; 8 | while (left < nums.length) { 9 | while (right < nums.length && nums[right] == 1) { 10 | max = Math.max(max, right - left + 1); 11 | ++right; 12 | } 13 | if (right == nums.length) { 14 | return max; 15 | } 16 | left = right; 17 | ++right; 18 | } 19 | return max; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/sliding_window/MaximumPointsYouCanObtainfromCards1423.java: -------------------------------------------------------------------------------- 1 | package sliding_window; 2 | 3 | public class MaximumPointsYouCanObtainfromCards1423 { 4 | public int maxScore(int[] cardPoints, int k) { 5 | final int size = cardPoints.length - k; 6 | int sum = 0; 7 | for (int c : cardPoints) { 8 | sum += c; 9 | } 10 | int windowSum = 0; 11 | for (int i = 0; i < size; i++) { 12 | windowSum += cardPoints[i]; 13 | } 14 | int result = sum - windowSum; 15 | for (int i = size; i < cardPoints.length; i++) { 16 | windowSum += cardPoints[i] - cardPoints[i - size]; 17 | result = Math.max(result, sum - windowSum); 18 | } 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/stack/LongestValidParentheses32.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class LongestValidParentheses32 { 6 | public int longestValidParentheses(String s) { 7 | final Stack stack = new Stack<>(); 8 | int result = 0; 9 | stack.push(-1); 10 | for (int i = 0; i < s.length(); i++) { 11 | if (s.charAt(i) == '(') { 12 | stack.push(i); 13 | } else { 14 | stack.pop(); 15 | if (stack.isEmpty()) { 16 | stack.push(i); 17 | } else { 18 | result = Math.max(result, i - stack.peek()); 19 | } 20 | } 21 | } 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/stack/OnlineStockSpan901.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class OnlineStockSpan901 { 6 | 7 | private final Stack priceCount; 8 | 9 | public OnlineStockSpan901() { 10 | priceCount = new Stack<>(); 11 | } 12 | 13 | public int next(int price) { 14 | int count = 1; 15 | while (!priceCount.isEmpty() && priceCount.peek()[0] <= price) { 16 | count += priceCount.pop()[1]; 17 | } 18 | priceCount.push(new int[]{price, count}); 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/stack/ScoreofParentheses856.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class ScoreofParentheses856 { 6 | public int scoreOfParentheses(String s) { 7 | final Stack stack = new Stack(); 8 | stack.push(0); // The score of the current frame 9 | 10 | for (char c : s.toCharArray()) { 11 | if (c == '(') 12 | stack.push(0); 13 | else { 14 | int v = stack.pop(); 15 | int w = stack.pop(); 16 | stack.push(w + Math.max(v << 1, 1)); 17 | } 18 | } 19 | 20 | return stack.pop(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/stack/ValidateStackSequences946.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class ValidateStackSequences946 { 6 | public boolean validateStackSequences(int[] pushed, int[] popped) { 7 | final Stack stack = new Stack<>(); 8 | int ipush = 0; 9 | int ipop = 0; 10 | while (ipush != pushed.length) { 11 | while (!stack.isEmpty() && stack.peek() == popped[ipop]) { 12 | stack.pop(); 13 | ++ipop; 14 | } 15 | stack.push(pushed[ipush++]); 16 | } 17 | while (!stack.isEmpty() && stack.peek() == popped[ipop]) { 18 | stack.pop(); 19 | ++ipop; 20 | } 21 | return ipop == ipush; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/string_integer/AddDigits258.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class AddDigits258 { 4 | public int addDigits(int num) { 5 | return num == 0 ? 0 : 1 + (num - 1) % 9; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/string_integer/AngleBetweenHandsofaClock1344.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class AngleBetweenHandsofaClock1344 { 4 | public double angleClock(int hour, int minutes) { 5 | final int baseHour = hour == 12 ? 0 : 30 * hour; 6 | final double hourVal = minutes / 2.0 + baseHour; 7 | final double minuteVal = minutes * 6.0; 8 | final double result = Math.abs(hourVal - minuteVal); 9 | return result > 180 ? 360 - result : result; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ConsecutiveCharacters1446.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class ConsecutiveCharacters1446 { 4 | public int maxPower(String s) { 5 | if (s.isEmpty()) { 6 | return 0; 7 | } 8 | int max = 1; 9 | char currentChar = s.charAt(0); 10 | int count = 0; 11 | for (char c : s.toCharArray()) { 12 | if (c == currentChar) { 13 | ++count; 14 | max = Math.max(max, count); 15 | } else { 16 | count = 1; 17 | currentChar = c; 18 | } 19 | } 20 | return max; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ContiguousArray525.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class ContiguousArray525 { 7 | public int findMaxLength(int[] nums) { 8 | int max = 0; 9 | int sum = 0; 10 | final Map dpMap = new HashMap<>(); 11 | dpMap.put(0, -1); 12 | for (int index = 0; index < nums.length; index++) { 13 | sum += 2 * nums[index] - 1; 14 | if (dpMap.containsKey(sum)) { 15 | max = Math.max(max, index - dpMap.get(sum)); 16 | } else { 17 | dpMap.put(sum, index); 18 | } 19 | } 20 | return max; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/string_integer/CountBinarySubstrings696.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class CountBinarySubstrings696 { 4 | public int countBinarySubstrings(String s) { 5 | final char[] chars = s.toCharArray(); 6 | int current = 1; 7 | int previous = 0; 8 | int count = 0; 9 | for (int i = 1; i < chars.length; i++) { 10 | if (chars[i] == chars[i - 1]) { 11 | ++current; 12 | } else { 13 | count += Math.min(current, previous); 14 | previous = current; 15 | current = 1; 16 | } 17 | } 18 | return Math.min(current, previous) + count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/string_integer/CountPrimes204.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class CountPrimes204 { 4 | public int countPrimes(int n) { 5 | if (n <= 2) { 6 | return 0; 7 | } 8 | final boolean[] nums = new boolean[n]; 9 | final int max = (int) Math.sqrt(n); 10 | for (int i = 2; i < max; i++) { 11 | if (!nums[i]) { 12 | for (int j = i * i; j < n; j += i) { 13 | nums[j] = true; 14 | } 15 | } 16 | } 17 | int count = 0; 18 | for (int i = 2; i < n; i++) { 19 | if (!nums[i]) { 20 | ++count; 21 | } 22 | } 23 | return count; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/string_integer/CountingBits338.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class CountingBits338 { 4 | public int[] countBits(int num) { 5 | final int[] result = new int[1 + num]; 6 | for (int index = 0; index < result.length; index++) { 7 | result[index] = result[index >> 1] + (index % 2 == 0 ? 0 : 1); 8 | } 9 | return result; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/string_integer/DefanginganIPAddress1108.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class DefanginganIPAddress1108 { 4 | public String defangIPaddr(String address) { 5 | final StringBuilder stringBuilder = new StringBuilder(); 6 | for (char c : address.toCharArray()) { 7 | if (c == '.') { 8 | stringBuilder.append("[.]"); 9 | } else { 10 | stringBuilder.append(c); 11 | } 12 | } 13 | return stringBuilder.toString(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/string_integer/DetectCapital520.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class DetectCapital520 { 4 | public boolean detectCapitalUse(String word) { 5 | int count = 0; 6 | for (char c : word.toCharArray()) { 7 | if (Character.isUpperCase(c)) { 8 | ++count; 9 | } 10 | } 11 | if (count == 0) { 12 | return true; 13 | } 14 | if (count == word.length()) { 15 | return true; 16 | } 17 | return count == 1 && Character.isUpperCase(word.charAt(0)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/string_integer/DetermineifStringHalvesAreAlike1704.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.Set; 4 | 5 | public class DetermineifStringHalvesAreAlike1704 { 6 | public boolean halvesAreAlike(String s) { 7 | final Set set = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'); 8 | int count1 = 0; 9 | int count2 = 0; 10 | for (int i = 0; i < s.length() / 2; i++) { 11 | if (set.contains(s.charAt(i))) { 12 | ++count1; 13 | } 14 | } 15 | for (int i = s.length() / 2; i < s.length(); i++) { 16 | if (set.contains(s.charAt(i))) { 17 | ++count2; 18 | } 19 | } 20 | return count1 == count2; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ExcelSheetColumnNumber171.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class ExcelSheetColumnNumber171 { 4 | public int titleToNumber(String s) { 5 | int base = 26; 6 | if (s.length() == 1) { 7 | return s.charAt(0) - '@'; 8 | } 9 | int result = s.charAt(s.length() - 1) - '@'; 10 | for (int index = s.length() - 2; index >= 0; index--) { 11 | result += (s.charAt(index) - '@') * base; 12 | base *= 26; 13 | } 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ExcelSheetColumnTitle168.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class ExcelSheetColumnTitle168 { 4 | public String convertToTitle(int n) { 5 | final StringBuilder resultBuilder = new StringBuilder(); 6 | while (n != 0) { 7 | resultBuilder.append((char) ((--n % 26) + 65)); 8 | n /= 26; 9 | } 10 | return resultBuilder.reverse().toString(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/string_integer/FinalPricesWithaSpecialDiscountinaShop1475.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class FinalPricesWithaSpecialDiscountinaShop1475 { 4 | public int[] finalPrices(int[] prices) { 5 | final int[] results = new int[prices.length]; 6 | for (int i = 0; i < prices.length; i++) { 7 | final int initialPrice = prices[i]; 8 | int discount = 0; 9 | for (int j = i + 1; j < prices.length; j++) { 10 | if (prices[j] <= initialPrice) { 11 | discount = prices[j]; 12 | break; 13 | } 14 | } 15 | results[i] = initialPrice - discount; 16 | } 17 | return results; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/string_integer/FindAllDuplicatesinanArray442.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class FindAllDuplicatesinanArray442 { 7 | public List findDuplicates(int[] nums) { 8 | final List results = new LinkedList<>(); 9 | for (int num : nums) { 10 | final int index = Math.abs(num) - 1; 11 | if (nums[index] < 0) { 12 | results.add(index + 1); 13 | } 14 | nums[index] = -nums[index]; 15 | } 16 | return results; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/string_integer/FindtheDifference389.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class FindtheDifference389 { 4 | public char findTheDifference(String s, String t) { 5 | final int[] hash = new int[26]; 6 | for (int i = 0; i < s.length(); i++) { 7 | --hash[s.charAt(i) - 'a']; 8 | ++hash[t.charAt(i) - 'a']; 9 | } 10 | ++hash[t.charAt(t.length() - 1) - 'a']; 11 | for (int i = 0; i < hash.length; i++) { 12 | if (hash[i] > 0) { 13 | return (char) ('a' + i); 14 | } 15 | } 16 | return '@'; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/string_integer/GlobalandLocalInversions775.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class GlobalandLocalInversions775 { 4 | public boolean isIdealPermutation(int[] a) { 5 | for (int i = 0; i < a.length - 1; i++) { 6 | if (a[i] != i) { 7 | if (a[i + 1] == i && a[i] == i + 1) { 8 | i++; 9 | } else { 10 | return false; 11 | } 12 | } 13 | } 14 | return true; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/string_integer/GroupAnagrams49.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.*; 4 | 5 | public class GroupAnagrams49 { 6 | public List> groupAnagrams(String[] strs) { 7 | final Map> map = new HashMap<>(); 8 | for (String s : strs) { 9 | final String sorted = sort(s); 10 | map.computeIfAbsent(sorted, v -> new ArrayList<>()).add(s); 11 | } 12 | return new ArrayList<>(map.values()); 13 | } 14 | 15 | private String sort(String s) { 16 | final char[] chars = s.toCharArray(); 17 | Arrays.sort(chars); 18 | return new String(chars); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/string_integer/HammingDistance461.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class HammingDistance461 { 4 | public int hammingDistance(int x, int y) { 5 | int xor = x ^ y; 6 | int count = 0; 7 | for (int i = 1; i <= 32; i++) { 8 | if ((xor & 1) == 1) { 9 | ++count; 10 | } 11 | xor >>= 1; 12 | } 13 | return count; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/string_integer/LengthofLastWord58.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class LengthofLastWord58 { 4 | 5 | public int lengthOfLastWord(String s) { 6 | final String[] strings = s.split(" "); 7 | if (strings.length == 0) { 8 | return 0; 9 | } 10 | return strings[strings.length - 1].length(); 11 | } 12 | 13 | /* 14 | public int lengthOfLastWord(String s) { 15 | int result = 0; 16 | int index = s.length() - 1; 17 | while (index >= 0 && s.charAt(index) == ' ') { 18 | --index; 19 | } 20 | while (index >= 0 && s.charAt(index) != ' ') { 21 | ++result; 22 | --index; 23 | } 24 | return result; 25 | } 26 | */ 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/string_integer/LongestMountaininArray845.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class LongestMountaininArray845 { 4 | public int longestMountain(int[] a) { 5 | int max = 0; 6 | for (int i = 1; i < a.length - 1; i++) { 7 | if (a[i] > a[i - 1] && a[i] > a[i + 1]) { 8 | int left = i - 1; 9 | int right = i + 1; 10 | while (left > 0 && a[left] > a[left - 1]) { 11 | --left; 12 | } 13 | while (right < a.length - 1 && a[right] > a[right - 1]) { 14 | ++right; 15 | } 16 | max = Math.max(max, right - left); 17 | } 18 | } 19 | return max; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/string_integer/LongestPalindrome409.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | class LongestPalindrome409 { 4 | public int longestPalindrome(String s) { 5 | final int[] count = new int[128]; 6 | for (char c : s.toCharArray()) { 7 | ++count[c]; 8 | } 9 | int result = 0; 10 | for (int it : count) { 11 | result += (it >> 1) << 1; 12 | if (result % 2 == 0 && it % 2 == 1) { 13 | ++result; 14 | } 15 | } 16 | return result; 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/string_integer/NondecreasingArray665.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class NondecreasingArray665 { 4 | public boolean checkPossibility(int[] nums) { 5 | int count = 0; 6 | for (int i = 1; i < nums.length; i++) { 7 | if (nums[i] < nums[i - 1]) { 8 | if (count > 0) { 9 | return false; 10 | } 11 | ++count; 12 | if (i > 1 && nums[i - 2] > nums[i]) { 13 | nums[i] = nums[i - 1]; 14 | } else { 15 | nums[i - 1] = nums[i]; 16 | } 17 | } 18 | } 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/string_integer/PascalsTriangleII119.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class PascalsTriangleII119 { 8 | public List getRow(int rowIndex) { 9 | final int[] results = new int[rowIndex + 1]; 10 | results[0] = 1; 11 | for (int row = 1; row <= rowIndex; row++) { 12 | for (int index = row; index >= 1; index--) { 13 | results[index] += results[index - 1]; 14 | } 15 | } 16 | return Arrays.stream(results).boxed().collect(Collectors.toList()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/string_integer/PowerofFour342.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class PowerofFour342 { 4 | public boolean isPowerOfFour(int num) { 5 | return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/string_integer/PowerofThree326.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class PowerofThree326 { 4 | /* 5 | public boolean isPowerOfThree(int n) { 6 | if (n < 1) { 7 | return false; 8 | } 9 | while (n % 3 == 0) { 10 | n /= 3; 11 | } 12 | return n == 1; 13 | } 14 | */ 15 | public boolean isPowerOfThree(int n) { 16 | return (Math.log10(n) / Math.log10(3)) % 1 == 0; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/string_integer/PrisonCellsAfterNDays957.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class PrisonCellsAfterNDays957 { 4 | public int[] prisonAfterNDays(int[] cells, int n) { 5 | int[] result = cells; 6 | for (int time = 0; time <= ((n - 1) % 14); time++) { 7 | final int[] newCells = new int[cells.length]; 8 | for (int index = 1; index <= cells.length - 2; index++) { 9 | if (result[index - 1] == result[index + 1]) { 10 | newCells[index] = 1; 11 | } else { 12 | newCells[index] = 0; 13 | } 14 | } 15 | result = newCells; 16 | } 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/string_integer/RangeSumQuery2DImmutable304.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class RangeSumQuery2DImmutable304 { 4 | 5 | private final int[][] dp; 6 | 7 | public RangeSumQuery2DImmutable304(int[][] matrix) { 8 | dp = new int[matrix.length + 1][matrix[0].length + 1]; 9 | for (int i = 0; i < matrix.length; i++) { 10 | for (int j = 0; j < matrix[0].length; j++) { 11 | dp[i + 1][j + 1] = matrix[i][j] + dp[i + 1][j] + dp[i][j + 1] - dp[i][j]; 12 | } 13 | } 14 | } 15 | 16 | public int sumRegion(int row1, int col1, int row2, int col2) { 17 | return dp[row2 + 1][col2 + 1] - dp[row2 + 1][col1] - dp[row1][col2 + 1] + dp[row1][col1]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/string_integer/RangeSumQueryImmutable303.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class RangeSumQueryImmutable303 { 4 | 5 | private final int[] prefixSum; 6 | 7 | public RangeSumQueryImmutable303(int[] nums) { 8 | prefixSum = new int[nums.length]; 9 | prefixSum[0] = nums[0]; 10 | for (int i = 1; i < nums.length; i++) { 11 | prefixSum[i] = nums[i] + prefixSum[i - 1]; 12 | } 13 | } 14 | 15 | public int sumRange(int left, int right) { 16 | if (left == 0) { 17 | return prefixSum[right]; 18 | } else { 19 | return prefixSum[right] - prefixSum[left - 1]; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ReorderedPowerof2869.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.Arrays; 4 | 5 | public class ReorderedPowerof2869 { 6 | public boolean reorderedPowerOf2(int n) { 7 | final int[] nCount = count(n); 8 | for (int i = 0; i < 31; i++) { 9 | if (Arrays.equals(nCount, count(1 << i))) { 10 | return true; 11 | } 12 | } 13 | return false; 14 | } 15 | 16 | private int[] count(int n) { 17 | final int[] result = new int[10]; 18 | while (n > 0) { 19 | result[n % 10]++; 20 | n /= 10; 21 | } 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/string_integer/RepeatedSubstringPattern459.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class RepeatedSubstringPattern459 { 4 | public boolean repeatedSubstringPattern(String s) { 5 | return s.repeat(2).substring(1, s.length() * 2 - 1).contains(s); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ReverseBits190.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class ReverseBits190 { 4 | // you need treat n as an unsigned value 5 | public int reverseBits(int n) { 6 | int result = 0; 7 | for (int i = 0; i < 32; i++) { 8 | if ((n & 1) == 1) { 9 | result = (result << 1) + 1; 10 | } else { 11 | result <<= 1; 12 | } 13 | n >>= 1; 14 | } 15 | return result; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ReverseOnlyLetters917.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class ReverseOnlyLetters917 { 4 | public String reverseOnlyLetters(String s) { 5 | final StringBuilder sb = new StringBuilder(); 6 | int j = s.length() - 1; 7 | for (int i = 0; i < s.length(); i++) { 8 | if (Character.isLetter(s.charAt(i))) { 9 | while (!Character.isLetter(s.charAt(j))) { 10 | --j; 11 | } 12 | sb.append(s.charAt(j--)); 13 | } else { 14 | sb.append(s.charAt(i)); 15 | } 16 | } 17 | return sb.toString(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ReverseString344.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class ReverseString344 { 4 | public void reverseString(char[] s) { 5 | int left = 0; 6 | int right = s.length - 1; 7 | while (left < right) { 8 | char temp = s[left]; 9 | s[left] = s[right]; 10 | s[right] = temp; 11 | ++left; 12 | --right; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/string_integer/SingleNumber136.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class SingleNumber136 { 4 | public int singleNumber(int[] nums) { 5 | int result = nums[0]; 6 | for (int index = 1; index < nums.length; index++) { 7 | result ^= nums[index]; 8 | } 9 | return result; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/string_integer/SingleNumberII137.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class SingleNumberII137 { 4 | public int singleNumber(int[] nums) { 5 | int one = 0; 6 | int two = 0; 7 | for (int i : nums) { 8 | one = one ^ i & (~two); 9 | two = two ^ i & (~one); 10 | } 11 | return one; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/string_integer/SingleNumberIII260.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class SingleNumberIII260 { 4 | public int[] singleNumber(int[] nums) { 5 | int flag = nums[0]; 6 | for (int index = 1; index < nums.length; index++) { 7 | flag ^= nums[index]; 8 | } 9 | flag = flag & (-flag); 10 | int r1 = 0; 11 | int r2 = 0; 12 | for (int i : nums) { 13 | if ((i & flag) == 0) { 14 | r1 = r1 ^ i; 15 | } else { 16 | r2 = r2 ^ i; 17 | } 18 | } 19 | return new int[]{r1, r2}; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/string_integer/SmallestRangeI908.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class SmallestRangeI908 { 4 | /* 5 | aim = min => max(b) - min(b) 6 | the smallest max(b) = max(a) - k 7 | the largest min(b) = min(b) + k 8 | aim = max(a) - k - min(a) - k 9 | */ 10 | public int smallestRangeI(int[] a, int k) { 11 | int min = a[0]; 12 | int max = a[0]; 13 | for (int x : a) { 14 | min = Math.min(min, x); 15 | max = Math.max(max, x); 16 | } 17 | return Math.max(0, max - min - 2 * k); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/string_integer/SmallestRangeII910.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SmallestRangeII910 { 6 | public int smallestRangeII(int[] a, int k) { 7 | if (a.length == 1) { 8 | return 0; 9 | } 10 | Arrays.sort(a); 11 | int result = a[a.length - 1] - a[0]; 12 | final int maxB = a[a.length - 1] - k; 13 | final int minB = a[0] + k; 14 | for (int i = 0; i < a.length - 1; i++) { 15 | final int max = Math.max(maxB, a[i] + k); 16 | final int min = Math.min(minB, a[i + 1] - k); 17 | result = Math.min(result, max - min); 18 | } 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/string_integer/SortArrayByParity905.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class SortArrayByParity905 { 4 | public int[] sortArrayByParity(int[] nums) { 5 | int lastNonOdd = 0; 6 | for (int index = 0; index < nums.length; index++) { 7 | if (nums[index] % 2 == 0) { 8 | if (index != lastNonOdd) { 9 | final int temp = nums[index]; 10 | nums[index] = nums[lastNonOdd]; 11 | nums[lastNonOdd] = temp; 12 | } 13 | ++lastNonOdd; 14 | } 15 | } 16 | return nums; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/string_integer/SortArrayByParityII922.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class SortArrayByParityII922 { 4 | public int[] sortArrayByParityII(int[] nums) { 5 | int lastOdd = 1; 6 | for (int index = 0; index < nums.length; index += 2) { 7 | if (nums[index] % 2 == 1) { 8 | while (nums[lastOdd] % 2 != 0) { 9 | lastOdd += 2; 10 | } 11 | final int temp = nums[index]; 12 | nums[index] = nums[lastOdd]; 13 | nums[lastOdd] = temp; 14 | } 15 | } 16 | return nums; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/string_integer/TaskScheduler621.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.Arrays; 4 | 5 | public class TaskScheduler621 { 6 | public int leastInterval(char[] tasks, int n) { 7 | final int[] chars = new int[26]; 8 | for (char c : tasks) { 9 | ++chars[c - 'A']; 10 | } 11 | Arrays.sort(chars); 12 | int index = 25; 13 | while (index >= 0 && chars[index] == chars[25]) { 14 | --index; 15 | } 16 | final int result = (chars[25] - 1) * (n + 1) + 25 - index; 17 | return Math.max(tasks.length, result); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/string_integer/TeemoAttacking495.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class TeemoAttacking495 { 4 | public int findPoisonedDuration(int[] timeSeries, int duration) { 5 | if (timeSeries.length == 0) { 6 | return 0; 7 | } 8 | int result = 0; 9 | for (int i = 0; i < timeSeries.length; i++) { 10 | result += Math.min(timeSeries[i + 1] - timeSeries[i], duration); 11 | } 12 | return result + duration; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ValidPalindrome125.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | public class ValidPalindrome125 { 4 | public boolean isPalindrome(String s) { 5 | int left = 0; 6 | int right = s.length() - 1; 7 | while (left < right) { 8 | while (left < right && !Character.isLetterOrDigit(s.charAt(left))) { 9 | ++left; 10 | } 11 | while (left < right && !Character.isLetterOrDigit(s.charAt(right))) { 12 | --right; 13 | } 14 | if (Character.toLowerCase(s.charAt(left++)) != 15 | Character.toLowerCase(s.charAt(right--))) { 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/string_integer/ValidParentheses20.java: -------------------------------------------------------------------------------- 1 | package string_integer; 2 | 3 | import java.util.Stack; 4 | 5 | public class ValidParentheses20 { 6 | public boolean isValid(String s) { 7 | final Stack stack = new Stack<>(); 8 | for (Character c : s.toCharArray()) { 9 | if (c.equals('(')) { 10 | stack.push(')'); 11 | } else if (c.equals('{')) { 12 | stack.push('}'); 13 | } else if (c.equals('[')) { 14 | stack.push(']'); 15 | } else { 16 | if (stack.isEmpty() || !stack.pop().equals(c)) { 17 | return false; 18 | } 19 | } 20 | } 21 | return stack.isEmpty(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/top_interview_easy/array/BestTimetoBuyandSellStock121.java: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array; 2 | 3 | public class BestTimetoBuyandSellStock121 { 4 | public int maxProfit(int[] prices) { 5 | int minPrice = Integer.MAX_VALUE; 6 | int result = 0; 7 | for (int price : prices) { 8 | minPrice = Math.min(minPrice, price); 9 | result = Math.max(result, price - minPrice); 10 | } 11 | return result; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/top_interview_easy/array/BestTimetoBuyandSellStockII122.java: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array; 2 | 3 | public class BestTimetoBuyandSellStockII122 { 4 | public int maxProfit(int[] prices) { 5 | int result = 0; 6 | for (int index = 1; index < prices.length; index++) { 7 | result += prices[index] > prices[index - 1] ? 8 | prices[index] - prices[index - 1] : 9 | 0; 10 | } 11 | return result; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/top_interview_easy/array/ContainsDuplicate217.java: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class ContainsDuplicate217 { 7 | public boolean containsDuplicate(int[] nums) { 8 | final Set set = new HashSet<>(); 9 | for (int n : nums) { 10 | if (set.contains(n)) { 11 | return true; 12 | } 13 | set.add(n); 14 | } 15 | return false; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/top_interview_easy/array/ContainsDuplicateII219.java: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class ContainsDuplicateII219 { 7 | public boolean containsNearbyDuplicate(int[] nums, int k) { 8 | final Map map = new HashMap<>(); 9 | for (int index = 0; index < nums.length; index++) { 10 | if (map.containsKey(nums[index])) { 11 | final int old = map.get(nums[index]); 12 | if (index - old <= k) { 13 | return true; 14 | } 15 | } 16 | map.put(nums[index], index); 17 | } 18 | return false; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/top_interview_easy/array/MoveZeroes283.java: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array; 2 | 3 | public class MoveZeroes283 { 4 | public void moveZeroes(int[] nums) { 5 | int lastNonZeroIndex = 0; 6 | for (int index = 0; index < nums.length; index++) { 7 | if (nums[index] != 0) { 8 | if (index != lastNonZeroIndex) { 9 | final int temp = nums[index]; 10 | nums[index] = nums[lastNonZeroIndex]; 11 | nums[lastNonZeroIndex] = temp; 12 | } 13 | ++lastNonZeroIndex; 14 | } 15 | } 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/main/java/top_interview_easy/array/RemoveDuplicatesfromSortedArray26.java: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array; 2 | 3 | public class RemoveDuplicatesfromSortedArray26 { 4 | public int removeDuplicates(int[] nums) { 5 | if (nums.length == 0) { 6 | return 0; 7 | } 8 | int current = 0; 9 | for (int index = 1; index < nums.length; index++) { 10 | if (nums[current] != nums[index]) { 11 | ++current; 12 | nums[current] = nums[index]; 13 | } 14 | } 15 | return current + 1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/tree/BinaryTreeMaximumPathSum124.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class BinaryTreeMaximumPathSum124 { 4 | private int result = Integer.MIN_VALUE; 5 | 6 | public int maxPathSum(TreeNode root) { 7 | result = Integer.MIN_VALUE; 8 | dfs(root); 9 | return result; 10 | } 11 | 12 | private int dfs(TreeNode root) { 13 | if (root == null) { 14 | return 0; 15 | } 16 | final int leftResult = Math.max(0, dfs(root.left)); 17 | final int rightResult = Math.max(0, dfs(root.right)); 18 | result = Math.max(result, leftResult + rightResult + root.val); 19 | return Math.max(leftResult, rightResult) + root.val; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/tree/BinaryTreeTilt563.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class BinaryTreeTilt563 { 4 | 5 | private int sum = 0; 6 | 7 | public int findTilt(TreeNode root) { 8 | dfs(root); 9 | return sum; 10 | } 11 | 12 | private int dfs(TreeNode root) { 13 | if (root == null) { 14 | return 0; 15 | } 16 | final int leftVal = dfs(root.left); 17 | final int rightVal = dfs(root.right); 18 | sum += Math.abs(leftVal - rightVal); 19 | return leftVal + rightVal + root.val; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/tree/ConstructStringfromBinaryTree606.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class ConstructStringfromBinaryTree606 { 4 | public String tree2str(TreeNode t) { 5 | if (t == null) { 6 | return ""; 7 | } else if (t.left == null && t.right == null) { 8 | return t.val + ""; 9 | } else if (t.right == null) { 10 | return t.val + "(" + tree2str(t.left) + ")"; 11 | } else if (t.left == null) { 12 | return t.val + "(" + tree2str(t.right) + ")"; 13 | } else { 14 | return t.val + "(" + tree2str(t.left) + ")(" + tree2str(t.right) + ")"; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/tree/ConvertSortedArraytoBinarySearchTree108.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class ConvertSortedArraytoBinarySearchTree108 { 4 | public TreeNode sortedArrayToBST(int[] nums) { 5 | return helper(nums, 0, nums.length - 1); 6 | } 7 | 8 | private TreeNode helper(int[] nums, int start, int end) { 9 | if (start > end) { 10 | return null; 11 | } 12 | if (start == end) { 13 | return new TreeNode(nums[start]); 14 | } 15 | final int mid = start + ((end - start) >> 1); 16 | final TreeNode root = new TreeNode(nums[mid]); 17 | root.left = helper(nums, start, mid - 1); 18 | root.right = helper(nums, mid + 1, end); 19 | return root; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/tree/CountGoodNodesinBinaryTree1448.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class CountGoodNodesinBinaryTree1448 { 4 | 5 | int sum = 0; 6 | 7 | public int goodNodes(TreeNode root) { 8 | sum = 0; 9 | dfs(root, root.val); 10 | return sum; 11 | } 12 | 13 | private void dfs(TreeNode root, int maxValue) { 14 | if (root == null) { 15 | return; 16 | } 17 | if (root.val >= maxValue) { 18 | ++sum; 19 | maxValue = root.val; 20 | } 21 | dfs(root.left, maxValue); 22 | dfs(root.right, maxValue); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/tree/DeleteLeavesWithaGivenValue1325.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class DeleteLeavesWithaGivenValue1325 { 4 | public TreeNode removeLeafNodes(TreeNode root, int target) { 5 | if (root == null) { 6 | return null; 7 | } 8 | root.left = removeLeafNodes(root.left, target); 9 | root.right = removeLeafNodes(root.right, target); 10 | 11 | if (root.left == null && root.right == null && root.val == target) { 12 | return null; 13 | } 14 | return root; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/tree/DiameterofBinaryTree543.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class DiameterofBinaryTree543 { 4 | 5 | private int max = 0; 6 | 7 | public int diameterOfBinaryTree(TreeNode root) { 8 | dfs(root); 9 | return max == 0 ? 0 : max - 1; 10 | } 11 | 12 | private int dfs(TreeNode root) { 13 | if (root == null) { 14 | return 0; 15 | } 16 | final int leftResult = dfs(root.left); 17 | final int rightResult = dfs(root.right); 18 | max = Math.max(max, leftResult + rightResult + 1); 19 | return Math.max(leftResult, rightResult) + 1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/tree/DistributeCoinsinBinaryTree979.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class DistributeCoinsinBinaryTree979 { 4 | int result = 0; 5 | 6 | public int distributeCoins(TreeNode root) { 7 | result = 0; 8 | dfs(root); 9 | return result; 10 | } 11 | 12 | private int dfs(TreeNode node) { 13 | if (node == null) { 14 | return 0; 15 | } 16 | final int leftResult = dfs(node.left); 17 | final int rightResult = dfs(node.right); 18 | result += Math.abs(leftResult) + Math.abs(rightResult); 19 | return node.val + leftResult + rightResult - 1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/tree/FindaCorrespondingNodeofaBinaryTreeinaCloneofThatTree1379.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class FindaCorrespondingNodeofaBinaryTreeinaCloneofThatTree1379 { 4 | 5 | TreeNode result = null; 6 | 7 | public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) { 8 | dfs(original, cloned, target); 9 | return result; 10 | } 11 | 12 | private void dfs(TreeNode original, TreeNode cloned, TreeNode target) { 13 | if (original == null) { 14 | return; 15 | } 16 | if (original == target) { 17 | result = cloned; 18 | } 19 | dfs(original.left, cloned.left, target); 20 | dfs(original.right, cloned.right, target); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/tree/InsertintoaBinarySearchTree701.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class InsertintoaBinarySearchTree701 { 4 | public TreeNode insertIntoBST(TreeNode root, int val) { 5 | if (root == null) { 6 | return new TreeNode(val); 7 | } 8 | if (val > root.val) { 9 | root.right = insertIntoBST(root.right, val); 10 | } else { 11 | root.left = insertIntoBST(root.left, val); 12 | } 13 | return root; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/tree/MaximumBinaryTreeII998.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class MaximumBinaryTreeII998 { 4 | public TreeNode insertIntoMaxTree(TreeNode root, int val) { 5 | if (root == null || val > root.val) { 6 | final TreeNode newRoot = new TreeNode(val); 7 | newRoot.left = root; 8 | return newRoot; 9 | } 10 | root.right = insertIntoMaxTree(root.right, val); 11 | return root; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/tree/MergeTwoBinaryTrees617.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class MergeTwoBinaryTrees617 { 4 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 5 | if (t1 == null) { 6 | return t2; 7 | } 8 | if (t2 == null) { 9 | return t1; 10 | } 11 | t1.val += t2.val; 12 | t1.left = mergeTrees(t1.left, t2.left); 13 | t1.right = mergeTrees(t1.right, t2.right); 14 | return t1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/tree/PathSum112.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class PathSum112 { 4 | public boolean hasPathSum(TreeNode root, int sum) { 5 | return helper(root, 0, sum); 6 | } 7 | 8 | private boolean helper(TreeNode root, int current, int sum) { 9 | if (root == null) { 10 | return false; 11 | } 12 | final int currentSum = current + root.val; 13 | if (root.left == null && root.right == null) { 14 | return currentSum == sum; 15 | } 16 | return helper(root.left, currentSum, sum) || 17 | helper(root.right, currentSum, sum); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/tree/PseudoPalindromicPathsinaBinaryTree1457.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class PseudoPalindromicPathsinaBinaryTree1457 { 4 | 5 | int result = 0; 6 | 7 | public int pseudoPalindromicPaths(TreeNode root) { 8 | result = 0; 9 | dfs(root, 0); 10 | return result; 11 | } 12 | 13 | private void dfs(TreeNode root, int mask) { 14 | if (root == null) { 15 | return; 16 | } 17 | mask = mask ^ (1 << (root.val - 1)); 18 | if (root.left == null && root.right == null) { 19 | if ((mask & (mask - 1)) == 0) { 20 | ++result; 21 | } 22 | return; 23 | } 24 | dfs(root.left, mask); 25 | dfs(root.right, mask); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/tree/SecondMinimumNodeInaBinaryTree671.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class SecondMinimumNodeInaBinaryTree671 { 4 | 5 | int min1; 6 | long ans = Long.MAX_VALUE; 7 | 8 | public void dfs(TreeNode root) { 9 | if (root != null) { 10 | if (min1 < root.val && root.val < ans) { 11 | ans = root.val; 12 | } else if (min1 == root.val) { 13 | dfs(root.left); 14 | dfs(root.right); 15 | } 16 | } 17 | } 18 | 19 | public int findSecondMinimumValue(TreeNode root) { 20 | min1 = root.val; 21 | dfs(root); 22 | return ans < Long.MAX_VALUE ? (int) ans : -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/tree/SumofNodeswithEvenValuedGrandparent1315.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class SumofNodeswithEvenValuedGrandparent1315 { 4 | int sum = 0; 5 | 6 | public int sumEvenGrandparent(TreeNode root) { 7 | sum = 0; 8 | dfs(root, -1, -1); 9 | return sum; 10 | } 11 | 12 | private void dfs(TreeNode root, int parent, int grandParent) { 13 | if (root == null) { 14 | return; 15 | } 16 | if (grandParent > 0 && grandParent % 2 == 0) { 17 | sum += root.val; 18 | } 19 | dfs(root.left, root.val, parent); 20 | dfs(root.right, root.val, parent); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/tree/TreeNode.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | 8 | TreeNode() { 9 | } 10 | 11 | TreeNode(int val) { 12 | this.val = val; 13 | } 14 | 15 | TreeNode(int val, TreeNode left, TreeNode right) { 16 | this.val = val; 17 | this.left = left; 18 | this.right = right; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/tree/TrimaBinarySearchTree699.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class TrimaBinarySearchTree699 { 4 | 5 | public TreeNode trimBST(TreeNode root, int low, int high) { 6 | if (root == null) { 7 | return null; 8 | } 9 | if (root.val < low) { 10 | return trimBST(root.right, low, high); 11 | } 12 | if (root.val > high) { 13 | return trimBST(root.left, low, high); 14 | } 15 | root.left = trimBST(root.left, low, high); 16 | root.right = trimBST(root.right, low, high); 17 | return root; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/tree/ValidateBinarySearchTree98.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | public class ValidateBinarySearchTree98 { 4 | public boolean isValidBST(TreeNode root) { 5 | return helper(root, null, null); 6 | } 7 | 8 | private boolean helper(TreeNode root, Integer min, Integer max) { 9 | if (root == null) { 10 | return true; 11 | } 12 | 13 | if (min != null && root.val <= min) { 14 | return false; 15 | } 16 | if (max != null && root.val >= max) { 17 | return false; 18 | } 19 | 20 | return helper(root.left, min, root.val) && 21 | helper(root.right, root.val, max); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/BinarySearchKotlin704.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class BinarySearchKotlin704 { 4 | fun search(nums: IntArray, target: Int): Int { 5 | if (nums.isEmpty()) { 6 | return -1 7 | } 8 | var left = 0 9 | var right = nums.size - 1 10 | while (left + 1 < right) { 11 | val mid = left + (right - left) / 2 12 | when { 13 | nums[mid] == target -> return mid 14 | nums[mid] < target -> left = mid 15 | nums[mid] > target -> right = mid 16 | } 17 | } 18 | return when (target) { 19 | nums[left] -> left 20 | nums[right] -> right 21 | else -> -1 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/CarPoolingKotlin1094.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class CarPoolingKotlin1094 { 4 | 5 | fun carPooling(trips: Array, capacity: Int): Boolean { 6 | val timeArray = IntArray(1001) 7 | for (trip in trips) { 8 | timeArray[trip[1]] += trip[0] 9 | timeArray[trip[2]] -= trip[0] 10 | } 11 | var current = 0 12 | for (t in timeArray) { 13 | current += t 14 | if (current > capacity) { 15 | return false 16 | } 17 | } 18 | return true 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/FindPeakElementKotlin162.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class FindPeakElementKotlin162 { 4 | fun findPeakElement(nums: IntArray): Int { 5 | var left = 0 6 | var right = nums.size - 1 7 | while (left + 1 < right) { 8 | val mid = left + (right - left) / 2 9 | when { 10 | nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1] -> return mid 11 | nums[mid - 1] < nums[mid] -> left = mid 12 | else -> right = mid 13 | } 14 | } 15 | return when { 16 | nums[left] > nums[right] -> left 17 | else -> right 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/FirstBadVersionKotlin278.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class FirstBadVersionKotlin278 { 4 | fun firstBadVersion(n: Int): Int { 5 | var left = 0 6 | var right = n 7 | // never dead loop 8 | while (left + 1 < right) { 9 | val mid = left + (right - left) / 2 10 | when { 11 | // find first bad version, so move right to mid 12 | isBadVersion(mid) -> right = mid 13 | else -> left = mid 14 | } 15 | } 16 | return when { 17 | isBadVersion(left) -> left 18 | else -> right 19 | } 20 | } 21 | 22 | private fun isBadVersion(version: Int) = version > 3 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/GuessNumberHigherorLowerKotlin374.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class GuessNumberHigherorLowerKotlin374 { 4 | 5 | fun guessNumber(n: Int): Int { 6 | var left = 0 7 | var right = n 8 | while (left + 1 < right) { 9 | val mid = left + (right - left) / 2 10 | when { 11 | guess(mid) == 0 -> return mid 12 | guess(mid) <= 0 -> left = mid 13 | guess(mid) >= 0 -> right = mid 14 | } 15 | } 16 | return when { 17 | guess(left) == 0 -> left 18 | guess(right) == 0 -> right 19 | else -> -1 20 | } 21 | } 22 | 23 | private fun guess(num: Int) = compareValues(num, 6) 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/HIndexIIKotlin275.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class HIndexIIKotlin275 { 4 | fun hIndex(citations: IntArray): Int { 5 | if (citations.isEmpty()) { 6 | return 0 7 | } 8 | var left = 0 9 | var right = citations.size 10 | while (left + 1 < right) { 11 | val mid = left + (right - left) / 2 12 | when { 13 | citations[citations.size - mid] >= mid -> left = mid 14 | else -> right = mid 15 | } 16 | } 17 | return when { 18 | citations[citations.size - right] >= right -> right 19 | left == 0 -> 0 20 | citations[citations.size - left] >= left -> left 21 | else -> -1 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/HIndexKotlin274.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class HIndexKotlin274 { 4 | fun hIndex(citations: IntArray): Int { 5 | var left = 0 6 | var right = citations.size 7 | while (left + 1 < right) { 8 | val mid = left + (right - left) / 2 9 | when { 10 | isValidH(citations, mid) -> left = mid 11 | else -> right = mid 12 | } 13 | } 14 | return when { 15 | isValidH(citations, right) -> right 16 | isValidH(citations, left) -> left 17 | else -> -1 18 | } 19 | } 20 | 21 | private fun isValidH(citations: IntArray, target: Int): Boolean = 22 | citations.filter { it >= target }.size >= target 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/IntersectionofTwoArraysIIKotlin350.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class IntersectionofTwoArraysIIKotlin350 { 4 | fun intersect(nums1: IntArray, nums2: IntArray): IntArray { 5 | if (nums2.size < nums1.size) { 6 | return intersect(nums2, nums1) 7 | } 8 | val num1Map = mutableMapOf() 9 | nums1.forEach { i -> num1Map[i] = num1Map.computeIfAbsent(i) { 0 } + 1 } 10 | val result = mutableListOf() 11 | nums2.forEach { i -> 12 | if (num1Map.containsKey(i) && num1Map.getValue(i) > 0) { 13 | result.add(i) 14 | num1Map[i] = num1Map.getValue(i).minus(1) 15 | } 16 | } 17 | return result.toIntArray() 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/IntersectionofTwoArraysKotlin349.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class IntersectionofTwoArraysKotlin349 { 4 | fun intersection(nums1: IntArray, nums2: IntArray): IntArray { 5 | return nums1.toHashSet().intersect(nums2.toHashSet()).toIntArray() 6 | } 7 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/SearchInsertPositionKotlin35.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class SearchInsertPositionKotlin35 { 4 | fun searchInsert(nums: IntArray, target: Int): Int { 5 | if (nums.isEmpty()) { 6 | return -1 7 | } 8 | var left = 0 9 | var right = nums.size - 1 10 | while (left + 1 < right) { 11 | val mid = left + (right - left) / 2 12 | when { 13 | nums[mid] <= target -> left = mid 14 | nums[mid] > target -> right = mid 15 | } 16 | } 17 | return when { 18 | target <= nums[left] -> left 19 | target <= nums[right] -> right 20 | else -> right + 1 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/SqrtKotlin69.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class SqrtKotlin69 { 4 | fun mySqrt(x: Int): Int { 5 | var left = 0 6 | // sqrt (Int.MAX_VALUE) = 46340.95 7 | var right = 46340 8 | while (left + 1 < right) { 9 | val mid = left + (right - left) / 2 10 | when { 11 | mid * mid == x -> return mid 12 | mid * mid < x -> left = mid 13 | mid * mid > x -> right = mid 14 | } 15 | } 16 | return when { 17 | right * right <= x -> right 18 | else -> left 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/UglyNumberKotlin263.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class UglyNumberKotlin263 { 4 | fun isUgly(num: Int): Boolean { 5 | if (num <= 0) { 6 | return false 7 | } 8 | var current = num 9 | while (current % 2 == 0) { 10 | current /= 2 11 | } 12 | while (current % 3 == 0) { 13 | current /= 3 14 | } 15 | while (current % 5 == 0) { 16 | current /= 5 17 | } 18 | return num == 1 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/binary_search/ValidPerfectSquareKotlin367.kt: -------------------------------------------------------------------------------- 1 | package binary_search 2 | 3 | class ValidPerfectSquareKotlin367 { 4 | fun isPerfectSquare(num: Int): Boolean { 5 | var left = 0 6 | // Int.MAX_VALUE = 2147483647 Sqrt(~) = 46340.95... 7 | var right = 46340 8 | while (left + 1 < right) { 9 | val mid = left + (right - left) / 2 // Int.MAX_VALUE = 2147483647 10 | when { 11 | mid * mid == num -> return true 12 | mid * mid < num -> left = mid 13 | mid * mid > num -> right = mid 14 | } 15 | } 16 | return when (num) { 17 | right * right -> true 18 | else -> false 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/bit_operation/RepeatedDNASequencesKotlin187.kt: -------------------------------------------------------------------------------- 1 | package bit_operation 2 | 3 | class RepeatedDNASequencesKotlin187 { 4 | fun findRepeatedDnaSequences(s: String): List { 5 | val results: MutableSet = HashSet() 6 | val set: MutableSet = HashSet() 7 | var i = 0 8 | while (i + 9 < s.length) { 9 | val current = s.substring(i, i + 10) 10 | if (set.contains(current)) { 11 | results.add(current) 12 | } else { 13 | set.add(current) 14 | } 15 | i++ 16 | } 17 | return results.toList() 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/breadth_first_search/MaximumDepthofNaryTreeKotlin559.kt: -------------------------------------------------------------------------------- 1 | package breadth_first_search 2 | 3 | import java.util.* 4 | 5 | class MaximumDepthofNaryTreeKotlin559 { 6 | class Node(var `val`: Int) { 7 | var children: List = listOf() 8 | } 9 | 10 | fun maxDepth(root: Node?): Int { 11 | if (root == null) { 12 | return 0 13 | } 14 | val queue: Queue = LinkedList() 15 | queue.offer(root) 16 | var level = 0 17 | while (queue.isNotEmpty()) { 18 | for (size in queue.indices) { 19 | val current = queue.poll() 20 | current.children.forEach { queue.offer(it) } 21 | } 22 | ++level 23 | } 24 | return level 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/kotlin/depth_first_search/TargetSumKotlin494.kt: -------------------------------------------------------------------------------- 1 | package depth_first_search 2 | 3 | class TargetSumKotlin494 { 4 | // Time Limit Exceeded 5 | fun findTargetSumWays(nums: IntArray, sum: Int): Int = 6 | nums.map { listOf(it, -it) }.reduce { acc, list -> 7 | acc.flatMap { accItem -> list.map { listItem -> accItem + listItem } } 8 | }.count { it == sum } 9 | } -------------------------------------------------------------------------------- /src/main/kotlin/depth_first_search/UniqueBinarySearchTreesKotlin96.kt: -------------------------------------------------------------------------------- 1 | package depth_first_search 2 | 3 | class UniqueBinarySearchTreesKotlin96 { 4 | // https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0 5 | // https://en.wikipedia.org/wiki/Catalan_number 6 | fun numTrees(n: Int): Int { 7 | var result = 1L 8 | for (index in n + 1..n * 2) { 9 | result = result * index / (index - n) 10 | } 11 | return (result / (n + 1)).toInt() 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/dynamic_programming/ClimbingStairsKotlin70.kt: -------------------------------------------------------------------------------- 1 | package dynamic_programming 2 | 3 | class ClimbingStairsKotlin70 { 4 | fun climbStairs(n: Int): Int { 5 | if (n == 1) { 6 | return 1 7 | } 8 | var i1 = 1 9 | var i2 = 2 10 | for (index in 3..n) { 11 | val sum = i1 + i2 12 | i1 = i2 13 | i2 = sum 14 | } 15 | return i2 16 | } 17 | /* 18 | fun climbStairs(n: Int): Int { 19 | if (n == 1) { 20 | return 1 21 | } 22 | val dp = IntArray(n + 1) 23 | dp[1] = 1 24 | dp[2] = 2 25 | for (index in 3..n) { 26 | dp[index] = dp[index - 1] + dp[index - 2] 27 | } 28 | return dp[n] 29 | } 30 | */ 31 | } -------------------------------------------------------------------------------- /src/main/kotlin/dynamic_programming/FibonacciNumberKotlin509.kt: -------------------------------------------------------------------------------- 1 | package dynamic_programming 2 | 3 | class FibonacciNumberKotlin509 { 4 | fun fib(N: Int): Int { 5 | if (N <= 1) { 6 | return N 7 | } 8 | var current = N - 1 9 | var int1 = 0 10 | var int2 = 1 11 | while (current > 0) { 12 | val sum = int1 + int2 13 | int1 = int2 14 | int2 = sum 15 | --current 16 | } 17 | return int2 18 | } 19 | } 20 | 21 | fun main() { 22 | val solution = FibonacciNumberKotlin509() 23 | println(solution.fib(0)) 24 | println(solution.fib(1)) 25 | println(solution.fib(2)) 26 | println(solution.fib(3)) 27 | println(solution.fib(4)) 28 | } -------------------------------------------------------------------------------- /src/main/kotlin/dynamic_programming/HouseRobberKotlin198.kt: -------------------------------------------------------------------------------- 1 | package dynamic_programming 2 | 3 | class HouseRobberKotlin198 { 4 | fun rob(nums: IntArray): Int { 5 | if (nums.isEmpty()) { 6 | return 0 7 | } 8 | if (nums.size == 1) { 9 | return nums[0] 10 | } 11 | val dp = IntArray(nums.size) 12 | dp[0] = nums[0] 13 | dp[1] = maxOf(nums[1], dp[0]) 14 | for (i in 2 until nums.size) { 15 | dp[i] = maxOf( 16 | // take current + i-2 17 | nums[i] + dp[i - 2], 18 | // do not take current, previous 19 | dp[i - 1] 20 | ) 21 | } 22 | return dp[nums.size - 1] 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/dynamic_programming/MaximumSubarrayKotlin53.kt: -------------------------------------------------------------------------------- 1 | package dynamic_programming 2 | 3 | class MaximumSubarrayKotlin53 { 4 | fun maxSubArray(nums: IntArray): Int { 5 | // Kadane’s Algorithm 6 | var currentMax = 0 7 | return nums.fold(Int.MIN_VALUE) { acc: Int, i: Int -> 8 | currentMax = maxOf(i, i + currentMax) 9 | maxOf(acc, currentMax) 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/main/kotlin/dynamic_programming/UniquePathsKotlin62.kt: -------------------------------------------------------------------------------- 1 | package dynamic_programming 2 | 3 | class UniquePathsKotlin62 { 4 | fun uniquePaths(m: Int, n: Int): Int { 5 | val dp = Array(m + 1) { IntArray(n + 1) } 6 | dp[0][1] = 1 7 | for (i in 1..m) { 8 | for (j in 1..n) { 9 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1] 10 | } 11 | } 12 | return dp[m][n] 13 | } 14 | } 15 | 16 | fun main() { 17 | val solution = UniquePathsKotlin62() 18 | // 3 19 | println(solution.uniquePaths(3, 2)) 20 | // 28 21 | println(solution.uniquePaths(7, 3)) 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/hash_map_set/DesignHashMapKotlin706.kt: -------------------------------------------------------------------------------- 1 | package hash_map_set 2 | 3 | class DesignHashMapKotlin706 { 4 | 5 | /** Initialize your data structure here. */ 6 | private val table = IntArray(1000001) { -1 } 7 | 8 | /** value will always be non-negative. */ 9 | fun put(key: Int, value: Int) { 10 | table[key] = value 11 | } 12 | 13 | /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ 14 | fun get(key: Int): Int { 15 | return table[key] 16 | } 17 | 18 | /** Removes the mapping of the specified value key if this map contains a mapping for the key */ 19 | fun remove(key: Int) { 20 | table[key] = -1 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/hash_map_set/DesignHashSetKotlin705.kt: -------------------------------------------------------------------------------- 1 | package hash_map_set 2 | 3 | class DesignHashSetKotlin705 { 4 | /** Initialize your data structure here. */ 5 | private val table = BooleanArray(1000001) 6 | 7 | fun add(key: Int) { 8 | table[key] = true 9 | } 10 | 11 | fun remove(key: Int) { 12 | table[key] = false 13 | } 14 | 15 | /** Returns true if this set contains the specified element */ 16 | fun contains(key: Int): Boolean { 17 | return table[key] 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/hash_map_set/DistributeCandiesKotlin575.kt: -------------------------------------------------------------------------------- 1 | package hash_map_set 2 | 3 | import java.util.* 4 | 5 | class DistributeCandiesKotlin575 { 6 | fun distributeCandies(candies: IntArray): Int { 7 | val set: MutableSet = HashSet() 8 | for (c in candies) { 9 | set.add(c) 10 | } 11 | return minOf(set.size, candies.size / 2) 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/hash_map_set/ReduceArraySizetoTheHalf1Kotlin338.kt: -------------------------------------------------------------------------------- 1 | package hash_map_set 2 | 3 | class ReduceArraySizetoTheHalf1Kotlin338 { 4 | fun minSetSize(arr: IntArray): Int { 5 | val half = arr.size.shr(1) 6 | arr.toList() 7 | .groupingBy { it } 8 | .eachCount() 9 | .map { it.value } 10 | .sortedDescending() 11 | .reduceIndexed { index, acc, i -> 12 | if (acc >= half) { 13 | return index 14 | } 15 | acc + i 16 | } 17 | return 1 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/hash_map_set/TwoSumKotlin1.kt: -------------------------------------------------------------------------------- 1 | package hash_map_set 2 | 3 | class TwoSumKotlin1 { 4 | fun twoSum(nums: IntArray, target: Int): IntArray { 5 | val valueIndexMap: MutableMap = HashMap() 6 | valueIndexMap[nums[0]] = 0 7 | for (index in 1 until nums.size) { 8 | if (valueIndexMap.containsKey(target - nums[index])) { 9 | return intArrayOf(valueIndexMap.getValue(target - nums[index]), index) 10 | } 11 | valueIndexMap[nums[index]] = index 12 | } 13 | return intArrayOf() 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/ChampagneTowerKotlin799.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class ChampagneTowerKotlin799 { 4 | fun champagneTower(poured: Int, queryRow: Int, queryGlass: Int): Double { 5 | val result = Array(101) { DoubleArray(101) } 6 | result[0][0] = poured.toDouble() 7 | for (i in 0..queryRow) { 8 | for (j in 0..i) { 9 | val now = (result[i][j] - 1.0) / 2.0 10 | if (now > 0) { 11 | result[i + 1][j] += now 12 | result[i + 1][j + 1] += now 13 | } 14 | } 15 | } 16 | // 2 1 1 17 | return Math.min(1.0, result[queryRow][queryGlass]) 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/DeleteNodeinaLinkedListKotlin237.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class DeleteNodeinaLinkedListKotlin237 { 4 | fun deleteNode(node: ListNode?) { 5 | val next = node!!.next!! 6 | node.`val` = next.`val` 7 | node.next = next.next 8 | } 9 | 10 | class ListNode(var `val`: Int) { 11 | var next: ListNode? = null 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/GasStationKotlin134.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class GasStationKotlin134 { 4 | fun canCompleteCircuit(gas: IntArray, cost: IntArray): Int { 5 | var sum = 0 6 | var count = 0 7 | var start = 0 8 | for (i in gas.indices) { 9 | val current = gas[i] - cost[i] 10 | if (count + current < 0) { 11 | start = i + 1 12 | count = 0 13 | } else { 14 | count += current 15 | } 16 | sum += current 17 | } 18 | return if (sum < 0) -1 else start 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/KdiffPairsinanArrayKotlin532.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class KdiffPairsinanArrayKotlin532 { 4 | 5 | fun findPairs(nums: IntArray, k: Int): Int { 6 | val map = HashMap() 7 | for (n in nums) { 8 | map[n] = map.getOrDefault(n, 0) + 1 9 | } 10 | var result = 0 11 | if (k == 0) { 12 | for (n in map.values) { 13 | result += if (n > 1) 1 else 0 14 | } 15 | } else { 16 | for (n in map.keys) { 17 | if (map.containsKey(n + k)) { 18 | ++result 19 | } 20 | } 21 | } 22 | return result 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/LinkedListCycleKotlin141.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class LinkedListCycleKotlin141 { 4 | fun hasCycle(head: ListNode?): Boolean { 5 | if (head == null) { 6 | return false 7 | } 8 | var slow: ListNode = head 9 | var fast = head 10 | while (fast?.next != null) { 11 | slow = slow.next 12 | fast = fast.next.next 13 | if (fast === slow) { 14 | return true 15 | } 16 | } 17 | return false 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/MaximizeDistancetoClosestPersonKotlin849.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class MaximizeDistancetoClosestPersonKotlin849 { 4 | fun maxDistToClosest(seats: IntArray): Int { 5 | var start = 0 6 | var end = 0 7 | var result = 1 8 | while (end < seats.size) { 9 | while (end < seats.size - 1 && seats[end] == 0) { 10 | ++end 11 | } 12 | val currentDistance: Int = if (start == 0 && seats[0] != 1 || end == seats.size - 1 && seats[end] != 1) { 13 | end - start 14 | } else { 15 | end - start shr 1 16 | } 17 | result = Math.max(result, currentDistance) 18 | start = end++ 19 | } 20 | return result 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/MaximumProductSubarrayKotlin152.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class MaximumProductSubarrayKotlin152 { 4 | fun maxProduct(nums: IntArray): Int { 5 | if (nums.isEmpty()) { 6 | return 0 7 | } 8 | var result = nums[0] 9 | var max = nums[0] 10 | var min = nums[0] 11 | for (i in 1 until nums.size) { 12 | val maxCurrent = max 13 | val minCurrent = min 14 | max = maxOf(maxOf(nums[i], maxCurrent * nums[i]), minCurrent * nums[i]) 15 | min = minOf(minOf(nums[i], minCurrent * nums[i]), maxCurrent * nums[i]) 16 | result = maxOf(max, result) 17 | } 18 | return result 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/MaximumSubarrayKotlin53.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class MaximumSubarrayKotlin53 { 4 | fun maxSubArray(nums: IntArray): Int { 5 | if (nums.isEmpty()) { 6 | return 0 7 | } 8 | var result = Int.MIN_VALUE 9 | var current = 0 10 | for (n in nums) { 11 | current = maxOf(current + n, n) 12 | result = maxOf(result, current) 13 | } 14 | return result 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/MiddleoftheLinkedListKotlin876.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class MiddleoftheLinkedListKotlin876 { 4 | fun middleNode(head: ListNode): ListNode? { 5 | var fast: ListNode? = head 6 | var slow = head 7 | while (fast?.next != null) { 8 | fast = fast.next.next 9 | slow = slow.next 10 | } 11 | return slow 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/RemoveCoveredIntervalsKotlin1288.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | import java.util.* 4 | 5 | class RemoveCoveredIntervalsKotlin1288 { 6 | fun removeCoveredIntervals(intervals: Array): Int { 7 | var result = 1 8 | intervals.sortWith(Comparator { o1, o2 -> 9 | if (o1[0] == o2[0]) { 10 | compareValues(o2[1], o1[1]) 11 | } else { 12 | compareValues(o1[0], o2[0]) 13 | } 14 | }) 15 | var minY = intervals[0][1] 16 | for (interval in intervals) { 17 | if (interval[1] > minY) { 18 | ++result 19 | minY = interval[1] 20 | } 21 | } 22 | return result 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/RobotBoundedInCircleKotlin1041.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class RobotBoundedInCircleKotlin1041 { 4 | fun isRobotBounded(instructions: String): Boolean { 5 | var x = 0 6 | var y = 0 7 | var direction = 0 8 | val deltaX = intArrayOf(0, 1, 0, -1) 9 | val deltaY = intArrayOf(1, 0, -1, 0) 10 | for (c in instructions.toCharArray()) { 11 | if (c == 'R') { 12 | direction = (direction + 1) % 4 13 | } else if (c == 'L') { 14 | direction = (direction + 3) % 4 15 | } else { 16 | x += deltaX[direction] 17 | y += deltaY[direction] 18 | } 19 | } 20 | return x == 0 && y == 0 || direction > 0 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/RotateListKotlin61.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class RotateListKotlin61 { 4 | fun rotateRight(head: ListNode?, k: Int): ListNode? { 5 | if (k == 0 || head == null) { 6 | return head 7 | } 8 | var current: ListNode = head 9 | var count = 1 10 | while (current.next != null) { 11 | current = current.next 12 | ++count 13 | } 14 | val moveRight = k % count 15 | var move = count - moveRight - 1 16 | var split: ListNode = head 17 | while (move != 0) { 18 | split = split.next 19 | --move 20 | } 21 | current.next = head 22 | val result = split.next 23 | split.next = null 24 | return result 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/SubarrayProductLessThanKKotlin713.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class SubarrayProductLessThanKKotlin713 { 4 | fun numSubarrayProductLessThanK(nums: IntArray, k: Int): Int { 5 | if (k <= 1) { 6 | return 0 7 | } 8 | var result = 0 9 | var product = 1 10 | var start = 0 11 | for (end in nums.indices) { 12 | product *= nums[end] 13 | while (product >= k) { 14 | product /= nums[start++] 15 | } 16 | result += end - start + 1 17 | } 18 | return result 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/list_array/TopKFrequentElementsKotlin347.kt: -------------------------------------------------------------------------------- 1 | package list_array 2 | 3 | class TopKFrequentElementsKotlin347 { 4 | fun topKFrequent(nums: IntArray, k: Int): IntArray { 5 | val map: MutableMap = HashMap() 6 | nums.forEach { 7 | map[it] = map.getOrDefault(it, 0) + 1 8 | } 9 | return map 10 | .toList() 11 | .sortedByDescending(Pair::second) 12 | .subList(0, k) 13 | .map { it.first } 14 | .toIntArray() 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/not_categorized/ComplementofBase10IntegerKotlin1009.kt: -------------------------------------------------------------------------------- 1 | package not_categorized 2 | 3 | class ComplementofBase10IntegerKotlin1009 { 4 | fun bitwiseComplement(N: Int): Int { 5 | if (N == 0) { 6 | return 1 7 | } 8 | var flag = Int.MAX_VALUE 9 | while (flag.and(N) != 0) { 10 | flag = flag.shl(1) 11 | } 12 | return (flag.inv()).and(N.inv()) 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/kotlin/not_categorized/JewelsandStonesKotlin771.kt: -------------------------------------------------------------------------------- 1 | package not_categorized 2 | 3 | class JewelsandStonesKotlin771 { 4 | fun numJewelsInStones(J: String, S: String): Int { 5 | // 164ms use HashSet 6 | val jCharSet = J.toHashSet() 7 | // 180ms because use LinkedHashSet 8 | // val jCharSet = J.toSet() 9 | return S.count { jCharSet.contains(it) } 10 | } 11 | } -------------------------------------------------------------------------------- /src/main/kotlin/not_categorized/NonoverlappingIntervalsKotlin435.kt: -------------------------------------------------------------------------------- 1 | package not_categorized 2 | 3 | class NonoverlappingIntervalsKotlin435 { 4 | fun eraseOverlapIntervals(intervals: Array): Int { 5 | var result = 0 6 | var last = 0 7 | intervals.sortWith(Comparator { int1, int2 -> compareValues(int1[0], int2[0]) }) 8 | for (index in 1 until intervals.size) { 9 | if (intervals[index][0] < intervals[last][1]) { 10 | ++result 11 | if (intervals[index][1] < intervals[last][1]) { 12 | last = index 13 | } 14 | } else { 15 | last = index 16 | } 17 | } 18 | return result 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/not_categorized/QueueReconstructionbyHeightKotlin406.kt: -------------------------------------------------------------------------------- 1 | package not_categorized 2 | 3 | class QueueReconstructionbyHeightKotlin406 { 4 | fun reconstructQueue(people: Array): Array { 5 | people.sortWith(Comparator { t, t2 -> 6 | when { 7 | t[0] == t2[0] -> compareValues(t[1], t2[1]) 8 | else -> compareValues(t2[0], t[0]) 9 | } 10 | }) 11 | val result: MutableList = ArrayList() 12 | people.forEach { 13 | result.add(it[1], it) 14 | } 15 | return result.toTypedArray() 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/kotlin/not_categorized_easy/FizzBuzzKotlin412.kt: -------------------------------------------------------------------------------- 1 | package not_categorized_easy 2 | 3 | import java.util.* 4 | 5 | class FizzBuzzKotlin412 { 6 | fun fizzBuzz(n: Int): List { 7 | val result: MutableList = LinkedList() 8 | for (i in 1..n) { 9 | when { 10 | i % 3 == 0 -> { 11 | when { 12 | i % 5 == 0 -> result.add("FizzBuzz") 13 | else -> result.add("Fizz") 14 | } 15 | } 16 | i % 5 == 0 -> { 17 | result.add("Buzz") 18 | } 19 | else -> result.add(i.toString()) 20 | } 21 | } 22 | return result 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/not_categorized_easy/GetMaximuminGeneratedArrayKotlin1646.kt: -------------------------------------------------------------------------------- 1 | package not_categorized_easy 2 | 3 | class GetMaximuminGeneratedArrayKotlin1646 { 4 | fun getMaximumGenerated(n: Int): Int { 5 | val nums: Array = Array(n + 1) { 0 } 6 | if (n < 2) { 7 | return n 8 | } 9 | nums[0] = 0 10 | nums[1] = 1 11 | var max = 1 12 | for (i in 2..n) { 13 | nums[i] = if (i % 2 == 0) nums[i.shr(1)] else nums[i.shr(1)] + nums[i.shr(1) + 1] 14 | max = maxOf(max, nums[i]) 15 | } 16 | return max 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/not_categorized_easy/InvertBinaryTreeKotlin226.kt: -------------------------------------------------------------------------------- 1 | package not_categorized_easy 2 | 3 | class InvertBinaryTreeKotlin226 { 4 | fun invertTree(root: TreeNode?): TreeNode? { 5 | invert(root) 6 | return root 7 | } 8 | 9 | private fun invert(root: TreeNode?) { 10 | if (root == null) { 11 | return 12 | } 13 | val temp = root.left 14 | root.left = root.right 15 | root.right = temp 16 | root.left?.let { invert(it) } 17 | root.right?.let { invert(it) } 18 | } 19 | 20 | class TreeNode(var `val`: Int) { 21 | var left: TreeNode? = null 22 | var right: TreeNode? = null 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/not_categorized_easy/SearchinaBinarySearchTreeKotlin700.kt: -------------------------------------------------------------------------------- 1 | package not_categorized_easy 2 | 3 | class SearchinaBinarySearchTreeKotlin700 { 4 | fun searchBST(root: TreeNode?, `val`: Int): TreeNode? { 5 | return when { 6 | root == null -> null 7 | root.`val` == `val` -> root 8 | root.`val` < `val` -> searchBST(root.right, `val`) 9 | root.`val` > `val` -> searchBST(root.left, `val`) 10 | else -> null 11 | } 12 | } 13 | 14 | class TreeNode(var `val`: Int) { 15 | var left: TreeNode? = null 16 | var right: TreeNode? = null 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/ConsecutiveCharactersKotlin1446.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class ConsecutiveCharactersKotlin1446 { 4 | fun maxPower(s: String): Int { 5 | if (s.isEmpty()) { 6 | return 0 7 | } 8 | var max = 1 9 | var currentChar = s[0] 10 | var count = 0 11 | for (c in s.toCharArray()) { 12 | if (c == currentChar) { 13 | ++count 14 | max = Math.max(max, count) 15 | } else { 16 | count = 1 17 | currentChar = c 18 | } 19 | } 20 | return max 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/DetectCapitalKotlin520.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class DetectCapitalKotlin520 { 4 | fun detectCapitalUse(word: String): Boolean { 5 | val count = word.count { it.isUpperCase() } 6 | return when { 7 | count == word.length -> true 8 | count == 1 && word[0].isUpperCase() -> true 9 | count == 0 -> true 10 | else -> false 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/ExcelSheetColumnNumberKotlin171.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class ExcelSheetColumnNumberKotlin171 { 4 | 5 | fun titleToNumber(s: String): Int { 6 | var base = 26 7 | if (s.length == 1) { 8 | return s[0] - '@' 9 | } 10 | var result = s[s.length - 1] - '@' 11 | for (index in s.length - 2 downTo 0) { 12 | result += (s[index] - '@') * base 13 | base *= 26 14 | } 15 | return result 16 | } 17 | } 18 | 19 | fun main() { 20 | val solution = ExcelSheetColumnNumberKotlin171() 21 | // 701 22 | println(solution.titleToNumber("ZY")) 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/ExcelSheetColumnTitleKotlin168.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class ExcelSheetColumnTitleKotlin168 { 4 | fun convertToTitle(n: Int): String { 5 | val resultBuilder = StringBuilder() 6 | var current = n 7 | while (current != 0) { 8 | val temp = --current % 26 9 | resultBuilder.append((temp + 65).toChar()) 10 | current /= 26 11 | } 12 | return resultBuilder.reverse().toString() 13 | } 14 | } 15 | 16 | fun main() { 17 | val solution = ExcelSheetColumnTitleKotlin168() 18 | // ZY 19 | println(solution.convertToTitle(701)) 20 | // Z 21 | println(solution.convertToTitle(26)) 22 | // A 23 | println(solution.convertToTitle(1)) 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/FindtheDifferenceKotlin389.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class FindtheDifferenceKotlin389 { 4 | fun findTheDifference(s: String, t: String): Char { 5 | val hash = IntArray(26) 6 | for (i in s.indices) { 7 | --hash[s[i] - 'a'] 8 | ++hash[t[i] - 'a'] 9 | } 10 | ++hash[t[t.length - 1] - 'a'] 11 | for (i in hash.indices) { 12 | if (hash[i] > 0) { 13 | return ('a'.toInt() + i).toChar() 14 | } 15 | } 16 | return '@' 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/FirstMissingPositiveKotlin41.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class FirstMissingPositiveKotlin41 { 4 | fun firstMissingPositive(nums: IntArray): Int { 5 | val set = HashSet() 6 | for (n in nums) { 7 | set.add(n) 8 | } 9 | var result = 1 10 | while (true) { 11 | if (set.contains(result)) { 12 | ++result 13 | } else { 14 | return result 15 | } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/HammingDistanceKotlin461.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class HammingDistanceKotlin461 { 4 | fun hammingDistance(x: Int, y: Int): Int { 5 | var xor = x.xor(y) 6 | var count = 0 7 | for (times in 1..32) { 8 | if (xor.and(1) == 1) { 9 | ++count 10 | } 11 | xor = xor.shr(1) 12 | } 13 | return count 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/LargestNumberKotlin179.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | import java.util.* 4 | 5 | class LargestNumberKotlin179 { 6 | fun largestNumber(nums: IntArray): String { 7 | var strings = nums.map { it.toString() } 8 | strings = strings.sortedWith(Comparator { s1: String, s2: String -> 9 | val order1 = s1 + s2 10 | val order2 = s2 + s1 11 | order2.compareTo(order1) 12 | }) 13 | 14 | if (strings[0] == "0") { 15 | return "0" 16 | } 17 | 18 | val result = StringBuilder() 19 | for (s in strings) { 20 | result.append(s) 21 | } 22 | return result.toString() 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/LengthofLastWordKotlin58.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class LengthofLastWordKotlin58 { 4 | 5 | fun lengthOfLastWord(s: String): Int { 6 | var result = 0 7 | var index = s.length - 1 8 | while (index >= 0 && s[index] == ' ') { 9 | --index 10 | } 11 | while (index >= 0 && s[index] != ' ') { 12 | ++result 13 | --index 14 | } 15 | return result 16 | } 17 | /* 18 | ! Wrong Answer! 19 | fun lengthOfLastWord(s: String): Int { 20 | val strings = s.split(" "); 21 | if (strings.isEmpty()) { 22 | return 0 23 | } 24 | return strings[strings.size - 1].length 25 | } 26 | */ 27 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/LongestPalindromeKotlin409.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class LongestPalindromeKotlin409 { 4 | fun longestPalindrome(s: String): Int { 5 | val count = IntArray(128) 6 | s.toCharArray().forEach { 7 | ++count[it.toInt()] 8 | } 9 | var result = 0 10 | count.forEach { 11 | result += it.shr(1).shl(1) 12 | if (result % 2 == 0 && it % 2 == 1) { 13 | ++result 14 | } 15 | } 16 | return result 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/PartitionLabelsKotlin763.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | import java.util.* 4 | 5 | class PartitionLabelsKotlin763 { 6 | fun partitionLabels(s: String): List { 7 | val last = IntArray(26) 8 | for (i in s.indices) { 9 | last[s[i] - 'a'] = i 10 | } 11 | var end = 0 12 | var start = 0 13 | val results: MutableList = LinkedList() 14 | for (i in s.indices) { 15 | end = maxOf(end, last[s[i] - 'a']) 16 | if (i == end) { 17 | results.add(end - start + 1) 18 | start = i + 1 19 | } 20 | } 21 | return results 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/PascalsTriangleIIKotlin119.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class PascalsTriangleIIKotlin119 { 4 | fun getRow(rowIndex: Int): List { 5 | val results = IntArray(rowIndex + 1) 6 | results[0] = 1 7 | for (row in 1..rowIndex) { 8 | for (index in row downTo 1) { 9 | results[index] += results[index - 1] 10 | } 11 | } 12 | return results.toList() 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/PowerofThreeKotlin326.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | import kotlin.math.log10 4 | 5 | class PowerofThreeKotlin326 { 6 | fun isPowerOfThree(n: Int): Boolean { 7 | return (log10(n.toDouble()) / log10(3.toDouble())) % 1 == 0.0 8 | } 9 | /* 10 | fun isPowerOfThree(n: Int): Boolean { 11 | var current = n 12 | if (current < 1) { 13 | return false 14 | } 15 | while (current % 3 == 0) { 16 | current /= 3 17 | } 18 | return current == 1 19 | } 20 | */ 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/RepeatedSubstringPatternKotlin459.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class RepeatedSubstringPatternKotlin459 { 4 | fun repeatedSubstringPattern(s: String): Boolean = s.repeat(1).substring(1, s.length * 2 - 1).contains(s) 5 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/ReverseBitsKotlin190.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class ReverseBitsKotlin190 { 4 | // you need treat n as an unsigned value 5 | fun reverseBits(n: Int): Int { 6 | var current = n 7 | var result = 0 8 | for (time in 0 until 32) { 9 | result = if (current.and(1) == 1) { 10 | result.shl(1) + 1 11 | } else { 12 | result.shl(1) 13 | } 14 | current = current.shr(1) 15 | } 16 | return result 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/ReverseStringKotlin344.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class ReverseStringKotlin344 { 4 | fun reverseString(s: CharArray) { 5 | var left = 0 6 | var right = s.size - 1 7 | while (left < right) { 8 | val temp = s[left] 9 | s[left] = s[right] 10 | s[right] = temp 11 | ++left 12 | --right 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/SingleNumberIIIKotlin260.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class SingleNumberIIIKotlin260 { 4 | fun singleNumber(nums: IntArray): IntArray { 5 | var flag = nums.reduce { acc, i -> acc.xor(i) } 6 | flag = flag.and(-flag) 7 | var r1 = 0 8 | var r2 = 0 9 | nums.forEach { 10 | if (it.and(flag) == 0) { 11 | r1 = r1.xor(it) 12 | } else { 13 | r2 = r2.xor(it) 14 | } 15 | } 16 | return intArrayOf(r1, r2) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/SingleNumberIIKotlin137.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class SingleNumberIIKotlin137 { 4 | fun singleNumber(nums: IntArray): Int { 5 | var one = 0 6 | var two = 0 7 | nums.forEach { 8 | one = one.xor(it).and(two.inv()) 9 | two = two.xor(it).and(one.inv()) 10 | } 11 | return one 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/SingleNumberKotlin136.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class SingleNumberKotlin136 { 4 | fun singleNumber(nums: IntArray): Int = nums.reduce { acc, i -> acc.xor(i) } 5 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/SortArrayByParityIIKotlin922.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class SortArrayByParityIIKotlin922 { 4 | fun sortArrayByParityII(nums: IntArray): IntArray { 5 | var lastOdd = 1 6 | for (index in nums.indices step 2) { 7 | if (nums[index] % 2 == 1) { 8 | while (nums[lastOdd] % 2 != 0) { 9 | lastOdd += 2 10 | } 11 | val temp = nums[index] 12 | nums[index] = nums[lastOdd] 13 | nums[lastOdd] = temp 14 | } 15 | } 16 | return nums 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/SortArrayByParityKotlin905.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class SortArrayByParityKotlin905 { 4 | fun sortArrayByParity(nums: IntArray): IntArray { 5 | var lastNonZeroIndex = 0 6 | for (index in nums.indices) { 7 | if (nums[index] % 2 == 0) { 8 | if (index != lastNonZeroIndex) { 9 | val temp = nums[index] 10 | nums[index] = nums[lastNonZeroIndex] 11 | nums[lastNonZeroIndex] = temp 12 | } 13 | ++lastNonZeroIndex 14 | } 15 | } 16 | return nums 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/TaskSchedulerKotlin621.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class TaskSchedulerKotlin621 { 4 | fun leastInterval(tasks: CharArray, n: Int): Int { 5 | val chars = IntArray(26) 6 | tasks.forEach { 7 | ++chars[it - 'A'] 8 | } 9 | chars.sort() 10 | var index = 25 11 | while (index >= 0 && chars[index] == chars[25]) { 12 | --index 13 | } 14 | val result = (chars[25] - 1) * (n + 1) + 25 - index 15 | return maxOf(tasks.size, result) 16 | } 17 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/TeemoAttackingKotlin495.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | class TeemoAttackingKotlin495 { 4 | fun findPoisonedDuration(timeSeries: IntArray, duration: Int): Int { 5 | if (timeSeries.isEmpty()) { 6 | return 0 7 | } 8 | var result = 0 9 | for (i in 0..timeSeries.size - 2) { 10 | result += Math.min(timeSeries[i + 1] - timeSeries[i], duration) 11 | } 12 | return result + duration 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/ValidParenthesesKotlin20.kt: -------------------------------------------------------------------------------- 1 | package string_integer 2 | 3 | import java.util.* 4 | 5 | class ValidParenthesesKotlin20 { 6 | fun isValid(s: String): Boolean { 7 | val stack: Stack = Stack() 8 | s.forEach { 9 | when (it) { 10 | '{' -> stack.push('}') 11 | '[' -> stack.push(']') 12 | '(' -> stack.push(')') 13 | else -> { 14 | if (stack.isEmpty() || it != stack.pop()) { 15 | return false 16 | } 17 | } 18 | } 19 | } 20 | return stack.isEmpty() 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/sort_an_array_912/BubbleSortKotlin.kt: -------------------------------------------------------------------------------- 1 | package array.sort_an_array_912 2 | 3 | class BubbleSortKotlin { 4 | fun sortArray(nums: IntArray): IntArray { 5 | // Time Limit Exceeded 6 | /* 7 | a = a ^ b 8 | b = a ^ b 9 | a = a ^ b 10 | */ 11 | for (i in nums.indices) { 12 | for (j in 0 until nums.size - 1 - i) { 13 | if (nums[j] > nums[j + 1]) { 14 | nums[j] = nums[j].xor(nums[j + 1]) 15 | nums[j + 1] = nums[j].xor(nums[j + 1]) 16 | nums[j] = nums[j].xor(nums[j + 1]) 17 | } 18 | } 19 | } 20 | return nums 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/string_integer/sort_an_array_912/InsertionSortKotlin.kt: -------------------------------------------------------------------------------- 1 | package array.sort_an_array_912 2 | 3 | class InsertionSortKotlin { 4 | fun sortArray(nums: IntArray): IntArray { 5 | for (index in 1 until nums.size) { 6 | var lastPosition = index - 1 7 | val current = nums[index] 8 | while (lastPosition >= 0 && nums[lastPosition] > current) { 9 | nums[lastPosition + 1] = nums[lastPosition] 10 | --lastPosition 11 | } 12 | nums[lastPosition + 1] = current 13 | } 14 | return nums 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/top_interview_easy/array/BestTimetoBuyandSellStockIIIKotlin123.kt: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array 2 | 3 | class BestTimetoBuyandSellStockIIIKotlin123 { 4 | fun maxProfit(prices: IntArray): Int { 5 | if (prices.isEmpty()) { 6 | return 0 7 | } 8 | var firstBuy = Int.MIN_VALUE 9 | var firstSell = 0 10 | var secondBuy = Int.MIN_VALUE 11 | var secondSell = 0 12 | prices.forEach { 13 | firstBuy = maxOf(firstBuy, -it) 14 | firstSell = maxOf(firstSell, firstBuy + it) 15 | secondBuy = maxOf(secondBuy, firstSell - it) 16 | secondSell = maxOf(secondSell, secondBuy + it) 17 | } 18 | return secondSell 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/top_interview_easy/array/BestTimetoBuyandSellStockIIKotlin122.kt: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array 2 | 3 | class BestTimetoBuyandSellStockIIKotlin122 { 4 | fun maxProfit(prices: IntArray): Int { 5 | var result = 0 6 | for (index in 1 until prices.size) { 7 | result += if (prices[index] > prices[index - 1]) prices[index] - prices[index - 1] else 0 8 | } 9 | return result 10 | } 11 | } -------------------------------------------------------------------------------- /src/main/kotlin/top_interview_easy/array/BestTimetoBuyandSellStockKotlin121.kt: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array 2 | 3 | class BestTimetoBuyandSellStockKotlin121 { 4 | fun maxProfit(prices: IntArray): Int { 5 | var minPrice = Int.MAX_VALUE 6 | var result = 0 7 | for (price in prices) { 8 | minPrice = minOf(minPrice, price) 9 | result = maxOf(result, price - minPrice) 10 | } 11 | return result 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/top_interview_easy/array/ContainsDuplicateIIIKotlin220.kt: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array 2 | 3 | class ContainsDuplicateIIIKotlin220 { 4 | fun containsNearbyAlmostDuplicate(nums: IntArray, k: Int, t: Int): Boolean { 5 | if (nums.isEmpty() || k == 0) { 6 | return false 7 | } 8 | var start = 0 9 | var end = 0 10 | while (start < nums.size - 1) { 11 | if (end - start == k || end == nums.size - 1) { 12 | end = ++start 13 | continue 14 | } 15 | ++end 16 | if (Math.abs(nums[start].toLong() - nums[end].toLong()) <= t) { 17 | return true 18 | } 19 | } 20 | return false 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/top_interview_easy/array/ContainsDuplicateIIKotlin219.kt: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array 2 | 3 | import java.util.HashMap 4 | 5 | class ContainsDuplicateIIKotlin219 { 6 | fun containsNearbyDuplicate(nums: IntArray, k: Int): Boolean { 7 | val map: MutableMap = HashMap() 8 | for (index in nums.indices) { 9 | if (map.containsKey(nums[index])) { 10 | val old = map[nums[index]]!! 11 | if (index - old <= k) { 12 | return true 13 | } 14 | } 15 | map[nums[index]] = index 16 | } 17 | return false 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/top_interview_easy/array/ContainsDuplicateKotlin217.kt: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array 2 | 3 | import java.util.HashSet 4 | 5 | class ContainsDuplicateKotlin217 { 6 | fun containsDuplicate(nums: IntArray): Boolean { 7 | val set: MutableSet = HashSet() 8 | for (n in nums) { 9 | if (set.contains(n)) { 10 | return true 11 | } 12 | set.add(n) 13 | } 14 | return false 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/top_interview_easy/array/MoveZeroesKotlin283.kt: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array 2 | 3 | class MoveZeroesKotlin283 { 4 | fun moveZeroes(nums: IntArray) { 5 | var lastNonZeroIndex = 0 6 | for (index in nums.indices) { 7 | if (nums[index] != 0) { 8 | if (index != lastNonZeroIndex) { 9 | val temp = nums[index] 10 | nums[index] = nums[lastNonZeroIndex] 11 | nums[lastNonZeroIndex] = temp 12 | } 13 | ++lastNonZeroIndex 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /src/main/kotlin/top_interview_easy/array/RemoveDuplicatesfromSortedArrayKotlin26.kt: -------------------------------------------------------------------------------- 1 | package top_interview_easy.array 2 | 3 | class RemoveDuplicatesfromSortedArrayKotlin26 { 4 | fun removeDuplicates(nums: IntArray): Int { 5 | if (nums.isEmpty()) { 6 | return 0 7 | } 8 | var current = 0 9 | for (index in 1 until nums.size) { 10 | if (nums[current] != nums[index]) { 11 | ++current 12 | nums[current] = nums[index] 13 | } 14 | } 15 | return current + 1 16 | } 17 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/BinaryTreeMaximumPathSumKotlin124.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class BinaryTreeMaximumPathSumKotlin124 { 4 | private var result = Int.MIN_VALUE 5 | 6 | fun maxPathSum(root: TreeNode?): Int { 7 | result = Int.MIN_VALUE 8 | dfs(root) 9 | return result 10 | } 11 | 12 | private fun dfs(root: TreeNode?): Int { 13 | if (root == null) { 14 | return 0 15 | } 16 | val leftResult = maxOf(0, dfs(root.left)) 17 | val rightResult = maxOf(0, dfs(root.right)) 18 | result = maxOf(result, leftResult + rightResult + root.`val`) 19 | return maxOf(leftResult, rightResult) + root.`val` 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/BinaryTreePruningKotlin814.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class BinaryTreePruningKotlin814 { 4 | fun pruneTree(root: TreeNode?): TreeNode? { 5 | if (root == null) { 6 | return null 7 | } 8 | return if (prune(root)) root else null 9 | } 10 | 11 | private fun prune(root: TreeNode?): Boolean { 12 | if (root == null) { 13 | return false 14 | } 15 | val leftResult = prune(root.left) 16 | val rightResult = prune(root.right) 17 | if (!leftResult) { 18 | root.left = null 19 | } 20 | if (!rightResult) { 21 | root.right = null 22 | } 23 | return root.`val` == 1 || leftResult || rightResult 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/BinaryTreeTiltKotlin563.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class BinaryTreeTiltKotlin563 { 4 | private var sum = 0 5 | 6 | fun findTilt(root: TreeNode?): Int { 7 | dfs(root) 8 | return sum 9 | } 10 | 11 | private fun dfs(root: TreeNode?): Int { 12 | if (root == null) { 13 | return 0 14 | } 15 | val leftVal = dfs(root.left) 16 | val rightVal = dfs(root.right) 17 | sum += Math.abs(leftVal - rightVal) 18 | return leftVal + rightVal + root.`val` 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/ConstructStringfromBinaryTreeKotlin606.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class ConstructStringfromBinaryTreeKotlin606 { 4 | fun tree2str(t: TreeNode?): String = when { 5 | t == null -> "" 6 | t.left == null && t.right == null -> t.`val`.toString() + "" 7 | t.right == null -> t.`val`.toString() + "(" + tree2str(t.left) + ")" 8 | else -> t.`val`.toString() + "(" + tree2str(t.left) + ")(" + tree2str(t.right) + ")" 9 | } 10 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/ConvertBSTtoGreaterTreeKotlin538.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class ConvertBSTtoGreaterTreeKotlin538 { 4 | private var sum = 0 5 | 6 | fun convertBST(root: TreeNode?): TreeNode? { 7 | sum = 0 8 | inorder(root) 9 | return root 10 | } 11 | 12 | // reversed inorder !! 13 | private fun inorder(root: TreeNode?) { 14 | if (root == null) { 15 | return 16 | } 17 | // preorder here 18 | inorder(root.right) 19 | // inorder here 20 | sum += root.`val` 21 | root.`val` = sum 22 | inorder(root.left) 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/ConvertSortedArraytoBinarySearchTreeKotlin108.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class ConvertSortedArraytoBinarySearchTreeKotlin108 { 4 | fun sortedArrayToBST(nums: IntArray): TreeNode? { 5 | return helper(nums, 0, nums.size - 1) 6 | } 7 | 8 | private fun helper(nums: IntArray, start: Int, end: Int): TreeNode? { 9 | if (start > end) { 10 | return null 11 | } 12 | if (start == end) { 13 | return TreeNode(nums[start]) 14 | } 15 | val mid = start + (end - start shr 1) 16 | val root = TreeNode(nums[mid]) 17 | root.left = helper(nums, start, mid - 1) 18 | root.right = helper(nums, mid + 1, end) 19 | return root 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/DeepestLeavesSumKotlin1302.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | import java.util.* 4 | 5 | class DeepestLeavesSumKotlin1302 { 6 | fun deepestLeavesSum(root: TreeNode?): Int { 7 | if (root == null) { 8 | return 0 9 | } 10 | val queue: Queue = LinkedList() 11 | queue.offer(root) 12 | var sum = 0 13 | while (queue.isNotEmpty()) { 14 | var currentSum = 0; 15 | for (i in queue.indices) { 16 | val node = queue.poll() 17 | currentSum += node.`val` 18 | node.left?.let { queue.offer(it) } 19 | node.right?.let { queue.offer(it) } 20 | } 21 | sum = currentSum 22 | } 23 | return sum 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/DiameterofBinaryTreeKotlin543.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class DiameterofBinaryTreeKotlin543 { 4 | private var max = 0 5 | 6 | fun diameterOfBinaryTree(root: TreeNode?): Int { 7 | dfs(root) 8 | return if (max == 0) 0 else max - 1 9 | } 10 | 11 | private fun dfs(root: TreeNode?): Int { 12 | if (root == null) { 13 | return 0 14 | } 15 | val leftResult = dfs(root.left) 16 | val rightResult = dfs(root.right) 17 | max = maxOf(max, leftResult + rightResult + 1) 18 | return maxOf(leftResult, rightResult) + 1 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/DistributeCoinsinBinaryTreeKotlin979.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class DistributeCoinsinBinaryTreeKotlin979 { 4 | var result = 0 5 | 6 | fun distributeCoins(root: TreeNode?): Int { 7 | result = 0 8 | dfs(root) 9 | return result 10 | } 11 | 12 | private fun dfs(node: TreeNode?): Int { 13 | if (node == null) { 14 | return 0 15 | } 16 | val leftResult = dfs(node.left) 17 | val rightResult = dfs(node.right) 18 | result += Math.abs(leftResult) + Math.abs(rightResult) 19 | return node.`val` + leftResult + rightResult - 1 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/FlipEquivalentBinaryTreesKotlin951.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class FlipEquivalentBinaryTreesKotlin951 { 4 | fun flipEquiv(root1: TreeNode?, root2: TreeNode?): Boolean { 5 | if (root1 === root2) { 6 | return true 7 | } 8 | return if (root1 == null || root2 == null || root1.`val` != root2.`val`) { 9 | false 10 | } else flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) || 11 | flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left) 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/InsertintoaBinarySearchTreeKotlin701.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class InsertintoaBinarySearchTreeKotlin701 { 4 | fun insertIntoBST(root: TreeNode?, `val`: Int): TreeNode { 5 | if (root == null) { 6 | return TreeNode(`val`) 7 | } 8 | if (`val` > root.`val`) { 9 | root.right = insertIntoBST(root.right, `val`) 10 | } else { 11 | root.left = insertIntoBST(root.left, `val`) 12 | } 13 | return root 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/MaximumBinaryTreeIIKotlin998.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class MaximumBinaryTreeIIKotlin998 { 4 | fun insertIntoMaxTree(root: TreeNode?, `val`: Int): TreeNode? { 5 | if (root == null || `val` > root.`val`) { 6 | val newRoot = TreeNode(`val`) 7 | newRoot.left = root 8 | return newRoot 9 | } 10 | root.right = insertIntoMaxTree(root.right, `val`) 11 | return root 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/MaximumDepthofBinaryTreeKotlin104.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | import java.util.* 4 | 5 | class MaximumDepthofBinaryTreeKotlin104 { 6 | fun maxDepth(root: TreeNode?): Int { 7 | if (root == null) { 8 | return 0 9 | } 10 | val queue: Queue = LinkedList() 11 | queue.offer(root) 12 | var level = 0 13 | while (queue.isNotEmpty()) { 14 | for (size in queue.indices) { 15 | val current = queue.poll() 16 | current.left?.let { queue.offer(it) } 17 | current.right?.let { queue.offer(it) } 18 | } 19 | ++level 20 | } 21 | return level 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/MergeTwoBinaryTreesKotlin617.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class MergeTwoBinaryTreesKotlin617 { 4 | fun mergeTrees(t1: TreeNode?, t2: TreeNode?): TreeNode? { 5 | if (t1 == null) { 6 | return t2 7 | } 8 | if (t2 == null) { 9 | return t1 10 | } 11 | t1.`val` += t2.`val` 12 | t1.left = mergeTrees(t1.left, t2.left) 13 | t1.right = mergeTrees(t1.right, t2.right) 14 | return t1 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/MinimumAbsoluteDifferenceinBSTKotlin530.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class MinimumAbsoluteDifferenceinBSTKotlin530 { 4 | var min = Int.MAX_VALUE 5 | var previous: TreeNode? = null 6 | 7 | fun getMinimumDifference(root: TreeNode?): Int { 8 | min = Int.MAX_VALUE 9 | inorder(root) 10 | return min 11 | } 12 | 13 | private fun inorder(root: TreeNode?) { 14 | if (root == null) { 15 | return 16 | } 17 | // preorder here 18 | inorder(root.left) 19 | // inorder here 20 | if (previous != null) { 21 | min = Math.min(min, root.`val` - previous!!.`val`) 22 | } 23 | previous = root 24 | inorder(root.right) 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/NaryTreePostorderTraversalKotlin590.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | import java.util.* 4 | 5 | class NaryTreePostorderTraversalKotlin590 { 6 | class Node(var `val`: Int) { 7 | var children: List = listOf() 8 | } 9 | 10 | fun postorder(root: Node?): List { 11 | val results: MutableList = LinkedList() 12 | if (root == null) { 13 | return results 14 | } 15 | for (child in root.children) { 16 | results.addAll(postorder(child)) 17 | } 18 | results.add(root.`val`) 19 | return results 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/PathSumKotlin112.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class PathSumKotlin112 { 4 | fun hasPathSum(root: TreeNode?, sum: Int): Boolean { 5 | return helper(root, 0, sum) 6 | } 7 | 8 | private fun helper(root: TreeNode?, current: Int, sum: Int): Boolean = when { 9 | root == null -> false 10 | root.left == null && root.right == null -> current + root.`val` == sum 11 | else -> helper(root.left, current + root.`val`, sum) || 12 | helper(root.right, current + root.`val`, sum) 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/SameTreeKotlin100.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class SameTreeKotlin100 { 4 | fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean = when { 5 | p == null && q == null -> true 6 | p == null || q == null || p.`val` != q.`val` -> false 7 | else -> isSameTree(p.left, q.left) && 8 | isSameTree(p.right, q.right) 9 | } 10 | 11 | class TreeNode(var `val`: Int) { 12 | var left: TreeNode? = null 13 | var right: TreeNode? = null 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/kotlin/tree/SecondMinimumNodeInaBinaryTreeKotlin671.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class SecondMinimumNodeInaBinaryTreeKotlin671 { 4 | var min1 = 0 5 | var ans = Long.MAX_VALUE 6 | 7 | fun dfs(root: TreeNode?) { 8 | if (root != null) { 9 | if (root.`val` in (min1 + 1) until ans) { 10 | ans = root.`val`.toLong() 11 | } else if (min1 == root.`val`) { 12 | dfs(root.left) 13 | dfs(root.right) 14 | } 15 | } 16 | } 17 | 18 | fun findSecondMinimumValue(root: TreeNode): Int { 19 | min1 = root.`val` 20 | dfs(root) 21 | return if (ans < Long.MAX_VALUE) ans.toInt() else -1 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/kotlin/tree/TrimaBinarySearchTreeKotlin699.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class TrimaBinarySearchTreeKotlin699 { 4 | fun trimBST(root: TreeNode?, low: Int, high: Int): TreeNode? { 5 | if (root == null) { 6 | return null 7 | } 8 | if (root.`val` < low) { 9 | return trimBST(root.right, low, high) 10 | } 11 | if (root.`val` > high) { 12 | return trimBST(root.left, low, high) 13 | } 14 | root.left = trimBST(root.left, low, high) 15 | root.right = trimBST(root.right, low, high) 16 | return root 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/kotlin/tree/ValidateBinarySearchTreeKotlin98.kt: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | class ValidateBinarySearchTreeKotlin98 { 4 | fun isValidBST(root: TreeNode?): Boolean { 5 | return helper(root, null, null) 6 | } 7 | 8 | private fun helper(root: TreeNode?, min: Int?, max: Int?): Boolean = when { 9 | root == null -> true 10 | min != null && root.`val` <= min -> false 11 | max != null && root.`val` >= max -> false 12 | else -> helper(root.left, min, root.`val`) && 13 | helper(root.right, root.`val`, max) 14 | } 15 | } --------------------------------------------------------------------------------