├── .gitignore ├── README.md ├── src ├── AlphabetBoardPath.py ├── AsFarFromLandAsPossible.py ├── BinaryTreeColoringGame.py ├── BraceExpansionII.java ├── Can_Make_Palindrome_from_Substring.py ├── CarPooling.java ├── Compare_Strings_by_Frequency_of_the_Smallest_Character.py ├── Count-Negative-Numbers-in-a-Sorted-Matrix.py ├── Count_Vowels_Permutation.py ├── Critical_Connections_in_a_Network.py ├── DayOfTheYear.py ├── Day_of_the_Week.py ├── DecreaseElementsToMakeArrayZigzag.py ├── Diet_Plan_Performance.py ├── DinnerPlateStacks.java ├── Distance_Between_Bus_Stops.py ├── DistributeCandiesToPeople.java ├── DuplicateZeros.java ├── FillingBookcaseShelves.java ├── FindInMountainArray.java ├── Find_Words_That_Can_Be_Formed_by_Characters.py ├── Get_Equal_Substrings_Within_Budget.py ├── Interval.java ├── Invalid_Transactions.py ├── K_Concatenation_Maximum_Sum.py ├── Largest1BorderedSquare.py ├── LargestValuesFromLabels.java ├── LastSubstringInLexicographicalOrder.java ├── LetterTilePossibilities.py ├── ListNode.java ├── LongestChunkedPalindromeDecomposition.py ├── LongestWellPerformingInterval.java ├── Longest_Arithmetic_Subsequence_of_Given_Difference.py ├── LowestCommonAncestorOfDeepestLeaves.py ├── Make_Array_Strictly_Increasing.py ├── Master.java ├── MaximumOfAbsoluteValueExpression.java ├── Maximum_Level_Sum_of_a_Binary_Tree.py ├── Maximum_Number_of_Balloons.py ├── Maximum_Subarray_Sum_with_One_Deletion.py ├── MinimumCostTreeFromLeafValues.py ├── Minimum_Absolute_Difference.py ├── Minimum_Moves_to_Reach_Target_with_Rotations.py ├── MountainArray.java ├── NestedInteger.java ├── NthTribonacciNumber.py ├── NumberOfDiceRollsWithTargetSum.py ├── NumberOfEquivalentDominoPairs.java ├── Number_of_Valid_Words_for_Each_Puzzle.py ├── OccurrencesAfterBigram.py ├── OnlineMajorityElementInSubarray.py ├── ParsingABooleanExpression.java ├── PathInZigzagLabelledBinaryTree.java ├── Path_with_Maximum_Gold.py ├── Play_with_Chips.py ├── Point.java ├── Prime_Arrangements.py ├── Product-of-the-Last-K-Numbers.py ├── Reader4.java ├── Relation.java ├── RelativeSortArray.py ├── Remove_All_Adjacent_Duplicates_in_String_II.py ├── Remove_Zero_Sum_Consecutive_Nodes_from_Linked_List.py ├── Reverse_Substrings_Between_Each_Pair_of_Parentheses.py ├── ShortestCommonSupersequence.java ├── ShortestPathInBinaryMatrix.java ├── ShortestPathWithAlternatingColors.java ├── SmallestSubsequenceofDistinctCharacters.py ├── SmallestSufficientTeam.java ├── Smallest_String_With_Swaps.py ├── SnapshotArray.py ├── Sort_Items_by_Groups_Respecting_Dependencies.py ├── StatisticsFromALargeSample.java ├── StoneGameII.py ├── SwapForLongestRepeatedCharacterSubstring.py ├── TreeNode.java ├── Ugly_Number_III.py ├── Unique_Number_of_Occurrences.py ├── _1.java ├── _10.java ├── _1000.py ├── _1001.py ├── _1002.java ├── _1002.py ├── _1003.java ├── _1003.py ├── _1004.java ├── _1005.java ├── _1006.java ├── _1007.java ├── _1008.py ├── _1009.java ├── _1010.java ├── _1011.java ├── _1012.java ├── _1012.py ├── _1013.java ├── _1014.java ├── _1015.py ├── _1016.java ├── _1017.java ├── _1018.java ├── _1019.java ├── _1020.java ├── _1021.java ├── _1022.py ├── _1023.py ├── _1024.py ├── _1025.java ├── _1026.java ├── _1027.py ├── _1028.py ├── _1029.py ├── _1030.py ├── _1031.java ├── _1032.java ├── _1033.java ├── _1034.java ├── _1035.py ├── _1036.py ├── _1037.java ├── _1038.java ├── _1039.java ├── _1040.java ├── _1041.py ├── _1042.java ├── _1043.java ├── _1044.java ├── _1046.java ├── _1047.java ├── _1048.java ├── _1049.java ├── _1051.java ├── _1052.java ├── _1053.java ├── _1054.java ├── _1064.java ├── _1065.java ├── _1066.java ├── _1071.java ├── _1072.py ├── _1073.java ├── _1074.java ├── _127.java ├── _128.java ├── _136.java ├── _136_1.java ├── _139.java ├── _139_1.java ├── _140.java ├── _146.java ├── _151.java ├── _151_1.c ├── _152.py ├── _155.java ├── _155_1.java ├── _156.java ├── _157.java ├── _158.java ├── _159.java ├── _161.java ├── _163.java ├── _165.java ├── _167.java ├── _170.java ├── _175.sql ├── _176.sql ├── _177.sql ├── _178.sql ├── _180.sql ├── _181.sql ├── _182.sql ├── _183.sql ├── _184.sql ├── _186.java ├── _196.sql ├── _197.sql ├── _1_1.java ├── _2.java ├── _206.java ├── _212.java ├── _214.java ├── _214_1.java ├── _218.cpp ├── _218.java ├── _22.java ├── _22_1.java ├── _244.java ├── _245.java ├── _246.java ├── _249.java ├── _250.java ├── _251.java ├── _252.java ├── _253.java ├── _2535 Difference Between Element Sum and Digit Sum of an Array.cpp ├── _2536 Increment Submatrices by One.cpp ├── _2537 Count the Number of Good Subarrays.cpp ├── _254.java ├── _2540_Minimum_Common_Value.py ├── _2542_Maximum_Subsequence_Score.cpp ├── _2543_Check_if_Point_Is_Reachable.cpp ├── _2544_Alternating_Digit_Sum.cpp ├── _2545_Sort_the_Students_by_Their_Kth_Score.py ├── _2546_Apply_Bitwise_Operations_to_Make_Strings_Equal.cpp ├── _2547_Minimum_Cost_to_Split_an_Array.cpp ├── _2549.py ├── _2549_1.py ├── _255.java ├── _2550.py ├── _2551.py ├── _2552.cpp ├── _2553.py ├── _2554.cpp ├── _2555.cpp ├── _2556.cpp ├── _2558.py ├── _2559.cpp ├── _255_1.java ├── _256.java ├── _2560.cpp ├── _2561.py ├── _2562.py ├── _2563.py ├── _2564.py ├── _2565.py ├── _259.java ├── _261.java ├── _262.sql ├── _265.java ├── _266.java ├── _267.java ├── _269.java ├── _269_1.java ├── _269_2.java ├── _270.java ├── _271.java ├── _271_1.java ├── _272.java ├── _274.java ├── _276.java ├── _277.java ├── _280.java ├── _281.java ├── _283.java ├── _283_1.java ├── _285.java ├── _285_1.java ├── _286.java ├── _288.java ├── _289.java ├── _289_1.java ├── _291.java ├── _291_1.java ├── _293.java ├── _294.java ├── _297.java ├── _298.java ├── _298_1.java ├── _298_2.java ├── _2_1.java ├── _301.java ├── _301_1.java ├── _302.java ├── _303.java ├── _304.java ├── _305.java ├── _306.java ├── _307.java ├── _307_1.java ├── _307_2.java ├── _308.java ├── _308_1.java ├── _309.java ├── _309_1.java ├── _310.java ├── _310_1.java ├── _312.java ├── _313.java ├── _314.java ├── _314_1.java ├── _315.java ├── _315_1.java ├── _316.java ├── _316_1.java ├── _317.java ├── _318.java ├── _319.java ├── _320.java ├── _321.java ├── _322.java ├── _323.java ├── _324.java ├── _325.java ├── _326.java ├── _327.java ├── _328.java ├── _329.java ├── _330.java ├── _331.java ├── _331_1.java ├── _332.java ├── _333.java ├── _334.java ├── _335.java ├── _336.java ├── _337.java ├── _338.java ├── _339.java ├── _340.java ├── _340_1.java ├── _340_2.java ├── _340_3.java ├── _341.java ├── _341_1.java ├── _342.java ├── _343.java ├── _344.java ├── _345.java ├── _346.java ├── _347.java ├── _347_1.java ├── _348.java ├── _349.java ├── _350.java ├── _352.java ├── _353.java ├── _354.java ├── _354_1.java ├── _355.java ├── _356.java ├── _357.java ├── _358.java ├── _359.java ├── _359_1.java ├── _36.java ├── _360.java ├── _361.java ├── _362.java ├── _363.java ├── _365.java ├── _366.java ├── _367.java ├── _368.java ├── _37.java ├── _370.java ├── _370_1.java ├── _370_2.java ├── _370_3.java ├── _371.java ├── _372.java ├── _372_1.java ├── _373.java ├── _373_1.java ├── _374.java ├── _375.java ├── _376.java ├── _376_1.java ├── _377.java ├── _378.java ├── _379.java ├── _37_1.java ├── _381.java ├── _383.java ├── _384.java ├── _385.java ├── _385_1.java ├── _386.java ├── _386_1.java ├── _387.java ├── _388.java ├── _388_1.java ├── _389.java ├── _39.java ├── _390.java ├── _391.java ├── _391_1.java ├── _392.java ├── _393.java ├── _394.java ├── _395.java ├── _395_1.java ├── _396.java ├── _397.java ├── _398.java ├── _398_1.java ├── _398_2.java ├── _399.java ├── _399_1.java ├── _4.java ├── _40.java ├── _400.java ├── _401.java ├── _401_1.java ├── _402.java ├── _403.java ├── _404.java ├── _405.java ├── _406.java ├── _407.java ├── _407_1.java ├── _407_2.java ├── _408.java ├── _409.java ├── _410.java ├── _411.java ├── _412.java ├── _413.java ├── _413_1.java ├── _414.java ├── _415.java ├── _416.java ├── _417.java ├── _417_1.java ├── _418.java ├── _419.java ├── _420.java ├── _421.java ├── _422.java ├── _423.java ├── _424.java ├── _424_1.java ├── _425.java ├── _425_1.java ├── _432.java ├── _433.java ├── _434.java ├── _435.java ├── _435_1.java ├── _436.java ├── _437.java ├── _437_1.java ├── _437_2.java ├── _438.java ├── _439.java ├── _44.java ├── _440.java ├── _441.java ├── _442.java ├── _443.py ├── _444.java ├── _446.java ├── _446_1.java ├── _447.java ├── _448.java ├── _449.java ├── _449_1.java ├── _44_1.java ├── _450.java ├── _450_1.java ├── _451.java ├── _452.java ├── _453.java ├── _454.java ├── _455.java ├── _456.java ├── _459.java ├── _459_1.java ├── _459_2.java ├── _459_3.java ├── _459_4.java ├── _461.java ├── _462.java ├── _463.java ├── _464.java ├── _465.java ├── _466.java ├── _467.java ├── _468.java ├── _469.java ├── _47.java ├── _471.java ├── _472.java ├── _473.java ├── _474.java ├── _475.java ├── _475_1.java ├── _476.java ├── _477.java ├── _480.java ├── _481.java ├── _482.java ├── _483.java ├── _484.java ├── _484_1.java ├── _485.java ├── _486.java ├── _486_1.java ├── _487.java ├── _488.java ├── _490.java ├── _491.java ├── _492.java ├── _493.java ├── _493_1.java ├── _493_2.java ├── _494.java ├── _495.java ├── _496.java ├── _498.java ├── _498_1.java ├── _499.java ├── _499_1.java ├── _500.java ├── _501.java ├── _501_1.java ├── _502.java ├── _503.java ├── _504.java ├── _504_1.java ├── _505.java ├── _505_1.java ├── _505_2.java ├── _506.java ├── _507.java ├── _508.java ├── _513.java ├── _514.java ├── _514_1.java ├── _515.java ├── _516.java ├── _517.java ├── _520.java ├── _521.java ├── _522.java ├── _523.java ├── _524.java ├── _525.java ├── _525_1.java ├── _526.java ├── _527.java ├── _529.java ├── _530.java ├── _531.java ├── _532.java ├── _532_1.java ├── _533.java ├── _536.java ├── _537.java ├── _538.java ├── _539.java ├── _540.java ├── _541.java ├── _542.java ├── _543.java ├── _544.java ├── _544_1.java ├── _545.java ├── _546.java ├── _547.java ├── _548.java ├── _549.java ├── _551.java ├── _552.java ├── _552_1.java ├── _552_2.java ├── _552_3.java ├── _553.java ├── _554.java ├── _555.java ├── _556.java ├── _557.java ├── _560.java ├── _561.java ├── _562.java ├── _563.java ├── _564.java ├── _565.java ├── _566.java ├── _567.java ├── _568.java ├── _572.java ├── _572_1.java ├── _572_2.java ├── _573.java ├── _575.java ├── _576.java ├── _581.java ├── _582.java ├── _582_1.java ├── _583.java ├── _588.java ├── _591.java ├── _592.java ├── _593.java ├── _594.java ├── _598.java ├── _599.java ├── _600.java ├── _600_1.java ├── _604.java ├── _605.java ├── _606.java ├── _609.java ├── _611.java ├── _616.java ├── _617.java ├── _621.java ├── _623.java ├── _624.java ├── _625.java ├── _625_1.java ├── _628.java ├── _629.java ├── _630.java ├── _631.java ├── _632.java ├── _633.java ├── _633_1.java ├── _634.java ├── _635.java ├── _636.java ├── _637.java ├── _638.java ├── _638_1.java ├── _639.java ├── _640.java ├── _642.java ├── _642_1.java ├── _643.java ├── _644.java ├── _645.java ├── _646.java ├── _647.java ├── _648.java ├── _649.java ├── _650.java ├── _651.java ├── _652.java ├── _652_1.java ├── _653.java ├── _654.java ├── _655.java ├── _656.java ├── _660.java ├── _661.java ├── _662.java ├── _662_1.java ├── _663.java ├── _664.java ├── _665.java ├── _666.java ├── _667.java ├── _668.java ├── _669.java ├── _670.java ├── _671.java ├── _672.java ├── _673.java ├── _673_1.java ├── _674.java ├── _675.java ├── _676.java ├── _676_1.java ├── _677.java ├── _678.java ├── _679.java ├── _680.java ├── _681.java ├── _682.java ├── _683.java ├── _685.java ├── _686.java ├── _686_1.java ├── _687.py ├── _688.java ├── _689.java ├── _691.java ├── _693.java ├── _694.py ├── _695.py ├── _696.java ├── _696.py ├── _697.py ├── _698.java ├── _699.java ├── _699.py ├── _712.java ├── _713.java ├── _714.java ├── _715.java ├── _717.py ├── _718.java ├── _718_1.java ├── _719.java ├── _72.java ├── _720.py ├── _721.py ├── _722.py ├── _723.py ├── _724.py ├── _725.py ├── _726.java ├── _726.py ├── _726_1.py ├── _727.java ├── _728.py ├── _729.java ├── _729_1.java ├── _730.java ├── _731.java ├── _731_1.java ├── _733.py ├── _734.py ├── _735.py ├── _736.py ├── _737.py ├── _738.java ├── _739.py ├── _740.py ├── _741.java ├── _742.py ├── _743.py ├── _743_1.py ├── _744.py ├── _745.py ├── _745_1.py ├── _746.java ├── _747.java ├── _748.py ├── _749.java ├── _750.java ├── _751.java ├── _752.py ├── _753.java ├── _754.java ├── _755.java ├── _756.java ├── _757.java ├── _758.java ├── _759.java ├── _76.java ├── _760.java ├── _761.java ├── _766.java ├── _767.java ├── _768.java ├── _768_1.java ├── _769.java ├── _771.java ├── _773.java ├── _774.java ├── _775.java ├── _776.java ├── _777.java ├── _778.java ├── _778_1.java ├── _779.java ├── _780.java ├── _781.java ├── _783.java ├── _784.java ├── _785.java ├── _786.java ├── _786_1.java ├── _787.java ├── _788.java ├── _789.java ├── _79.java ├── _790.java ├── _791.java ├── _791_1.java ├── _792.java ├── _793.java ├── _794.java ├── _795.java ├── _795_1.java ├── _796.java ├── _797.java ├── _798.java ├── _799.java ├── _804.java ├── _805.java ├── _805_1.java ├── _806.java ├── _807.java ├── _808.java ├── _809.java ├── _810.java ├── _811.java ├── _812.java ├── _813.java ├── _814.java ├── _815.java ├── _820.java ├── _821.java ├── _821_1.java ├── _822.java ├── _823.java ├── _824.py ├── _825.py ├── _826.py ├── _826_1.py ├── _827.py ├── _828.java ├── _829.java ├── _830.java ├── _831.java ├── _832.py ├── _833.py ├── _834.py ├── _835.py ├── _836.java ├── _837.java ├── _838.java ├── _840.java ├── _841.java ├── _842.java ├── _843.java ├── _844.java ├── _845.java ├── _846.java ├── _847.java ├── _848.java ├── _849.java ├── _850.java ├── _850_1.java ├── _851.java ├── _852.java ├── _853.java ├── _855.java ├── _856.java ├── _859.java ├── _860.java ├── _861.java ├── _862.java ├── _863.java ├── _864.java ├── _865.java ├── _866.java ├── _867.java ├── _868.java ├── _869.java ├── _870.java ├── _871.java ├── _872.java ├── _873.java ├── _874.java ├── _875.java ├── _876.java ├── _877.java ├── _878.java ├── _879.java ├── _880.java ├── _881.java ├── _882.java ├── _883.java ├── _884.java ├── _885.java ├── _886.java ├── _887.java ├── _888.java ├── _889.java ├── _889_1.java ├── _890.java ├── _891.java ├── _896.java ├── _897.java ├── _898.java ├── _898_1.java ├── _899.java ├── _900.java ├── _901.java ├── _902.java ├── _903.java ├── _904.java ├── _905.java ├── _906.java ├── _907.java ├── _907_1.java ├── _908.java ├── _909.java ├── _910.java ├── _911.java ├── _913.java ├── _914.java ├── _915.java ├── _916.java ├── _917.java ├── _918.java ├── _918_1.java ├── _918_2.java ├── _919.java ├── _920.java ├── _921.java ├── _922.java ├── _923.java ├── _923_1.java ├── _924.java ├── _933.java ├── _934.java ├── _935.java ├── _936.java ├── _937.java ├── _938.java ├── _939.java ├── _940.java ├── _941.java ├── _942.java ├── _943.java ├── _944.java ├── _945.java ├── _946.java ├── _947.py ├── _948.java ├── _949.py ├── _950.java ├── _951.java ├── _952.java ├── _953.java ├── _954.java ├── _955.java ├── _955_1.java ├── _956.java ├── _957.java ├── _958.java ├── _959.java ├── _959.py ├── _96.java ├── _960.java ├── _961.java ├── _962.java ├── _962_1.java ├── _962_2.java ├── _963.java ├── _964.java ├── _965.java ├── _966.java ├── _967.java ├── _968.java ├── _968_1.java ├── _973.java ├── _974.java ├── _975.java ├── _976.java ├── _977.java ├── _977_1.java ├── _978.java ├── _979.java ├── _979_1.java ├── _980.java ├── _981.java ├── _982.java ├── _983.java ├── _984.java ├── _985.java ├── _986.java ├── _987.java ├── _988.java ├── _989.java ├── _990.java ├── _991.java ├── _992.java ├── _993.py ├── _994.py ├── _995.java ├── _996.java ├── _997.py ├── _998.py ├── _999.py ├── balance-a-binary-search-tree.py ├── closest-divisors.py ├── construct-target-array-with-multiple-sums.py ├── design-a-stack-with-increment-operation.py ├── how-many-numbers-are-smaller-than-the-current-number.py ├── largest-multiple-of-three.py ├── linked-list-in-binary-tree.py ├── lucky-numbers-in-a-matrix.py ├── maximum-number-of-events-that-can-be-attended.py ├── maximum-performance-of-a-team.py ├── minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py ├── number-of-days-between-two-dates.py ├── rank-teams-by-votes.py └── validate-binary-tree-nodes.py └── tests ├── Deserializer.java ├── _140Test.java ├── _155Test.java ├── _155_1Test.java ├── _161Test.java ├── _165Test.java ├── _206Test.java ├── _265Test.java ├── _269Test.java ├── _270Test.java ├── _288Test.java ├── _291Test.java ├── _305Test.java ├── _314_1Test.java ├── _333Test.java ├── _358Test.java ├── _37Test.java ├── _37_1Test.java ├── _396Test.java ├── _397Test.java ├── _398Test.java ├── _399Test.java ├── _39Test.java ├── _400Test.java ├── _401Test.java ├── _402Test.java ├── _403Test.java ├── _404Test.java ├── _405Test.java ├── _406Test.java ├── _407Test.java ├── _408Test.java ├── _409Test.java ├── _40Test.java ├── _410Test.java ├── _411Test.java ├── _44Test.java ├── _47Test.java └── _96Test.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | .mtj.tmp/ 4 | .mypy_cache/ 5 | .vscode 6 | 7 | # Package Files # 8 | *.jar 9 | *.war 10 | *.ear 11 | 12 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 13 | hs_err_pid* 14 | 15 | .idea/ 16 | LeetCode.iml 17 | bin/ 18 | out/ 19 | venv/ 20 | src/Solution.java 21 | src/Solution* 22 | *.in 23 | *.out 24 | tests/SolutionTest.java 25 | tests/Solution* 26 | .DS_Store 27 | a.cpp 28 | in.txt 29 | out.txt 30 | -------------------------------------------------------------------------------- /src/Compare_Strings_by_Frequency_of_the_Smallest_Character.py: -------------------------------------------------------------------------------- 1 | """ 2 | Compare Strings by Frequency of the Smallest Character 3 | 4 | Binary Search 5 | """ 6 | from typing import * 7 | from collections import * 8 | from bisect import * 9 | 10 | 11 | class Solution: 12 | def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: 13 | freq = [Counter(s)[min(s)] for s in words] 14 | freq.sort() 15 | # bisect_left or bisect_right returns the index of the target element AFTER insertion, where the length of the 16 | # "inserted" list will be one more than its original length. 17 | return [len(words) - bisect_right(freq, Counter(q)[min(q)]) for q in queries] 18 | -------------------------------------------------------------------------------- /src/Count-Negative-Numbers-in-a-Sorted-Matrix.py: -------------------------------------------------------------------------------- 1 | """Count Negative Numbers in a Sorted Matrix 2 | 3 | Young Tableau""" 4 | 5 | class Solution: 6 | def countNegatives(self, grid: List[List[int]]) -> int: 7 | r, c = len(grid), len(grid[0]) 8 | i, j = 0, c - 1 9 | ans = 0 10 | while i < r and j >= 0: 11 | if grid[i][j] < 0: 12 | ans += r - i 13 | j -= 1 14 | else: 15 | i += 1 16 | return ans 17 | -------------------------------------------------------------------------------- /src/Count_Vowels_Permutation.py: -------------------------------------------------------------------------------- 1 | """Count Vowels Permutation 2 | 3 | Counting""" 4 | 5 | from typing import * 6 | from collections import defaultdict 7 | 8 | 9 | class Solution: 10 | def longestSubsequence(self, arr: List[int], difference: int) -> int: 11 | d = defaultdict(int) 12 | for i in arr: 13 | d[i] = d[i - difference] + 1 14 | return max(d.values()) 15 | -------------------------------------------------------------------------------- /src/DayOfTheYear.py: -------------------------------------------------------------------------------- 1 | """ 2 | Day of the Year 3 | 4 | Math 5 | """ 6 | 7 | from typing import * 8 | 9 | 10 | class Solution: 11 | def dayOfYear(self, date: str) -> int: 12 | def is_leap_year(year: int) -> bool: 13 | if year % 100 == 0: 14 | return year % 400 == 0 15 | else: 16 | return year % 4 == 0 17 | 18 | y, m, d = date.split("-") 19 | days = [0, 31, 28 if not is_leap_year(int(y)) else 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 20 | return sum(days[i] for i in range(1, int(m))) + int(d) 21 | -------------------------------------------------------------------------------- /src/Day_of_the_Week.py: -------------------------------------------------------------------------------- 1 | """Day of the Week""" 2 | 3 | import datetime 4 | 5 | 6 | class Solution: 7 | def dayOfTheWeek(self, day: int, month: int, year: int) -> str: 8 | return ["Monday", 9 | "Tuesday", 10 | "Wednesday", 11 | "Thursday", 12 | "Friday", 13 | "Saturday", 14 | "Sunday"][datetime.date(year, month, day).weekday()] 15 | -------------------------------------------------------------------------------- /src/Diet_Plan_Performance.py: -------------------------------------------------------------------------------- 1 | """Diet Plan Performance 2 | 3 | Sliding Window 4 | """ 5 | from typing import * 6 | 7 | 8 | class Solution: 9 | def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int: 10 | sum = ans = 0 11 | for i in range(len(calories)): 12 | sum += calories[i] 13 | if i - k >= 0: 14 | sum -= calories[i - k] 15 | if i >= k - 1: 16 | if sum < lower: 17 | ans -= 1 18 | elif sum > upper: 19 | ans += 1 20 | else: 21 | pass 22 | return ans 23 | -------------------------------------------------------------------------------- /src/Distance_Between_Bus_Stops.py: -------------------------------------------------------------------------------- 1 | """Distance Between Bus Stops""" 2 | 3 | from typing import * 4 | 5 | 6 | class Solution: 7 | def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: 8 | start, destination = min(start, destination), max(start, destination) 9 | tmp = sum(distance[start:destination]) 10 | return min(tmp, sum(distance) - tmp) 11 | -------------------------------------------------------------------------------- /src/DistributeCandiesToPeople.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Distribute Candies to People 3 | * 4 | * Brute-force 5 | * Only need sqrt(n) time 6 | */ 7 | public class DistributeCandiesToPeople { 8 | 9 | public int[] distributeCandies(int candies, int num_people) { 10 | int[] res = new int[num_people]; 11 | for (int i = 1; candies > 0; i++) { 12 | int take = Math.min(i, candies); 13 | res[(i - 1) % num_people] += take; 14 | candies -= take; 15 | } 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Find_Words_That_Can_Be_Formed_by_Characters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find Words That Can Be Formed by Characters 3 | 4 | Brute-force 5 | """ 6 | 7 | from typing import * 8 | 9 | 10 | class Solution: 11 | def countCharacters(self, words: List[str], chars: str) -> int: 12 | counter = Counter(chars) 13 | sum = 0 14 | for word in words: 15 | counter1 = Counter(word) 16 | good = True 17 | for ch, val in counter1.items(): 18 | if ch not in counter or val > counter[ch]: 19 | good = False 20 | break 21 | if good: 22 | sum += len(word) 23 | 24 | return sum 25 | -------------------------------------------------------------------------------- /src/Get_Equal_Substrings_Within_Budget.py: -------------------------------------------------------------------------------- 1 | """ Get Equal Substrings Within Budget 2 | 3 | Sliding Window""" 4 | 5 | 6 | class Solution: 7 | def equalSubstring(self, s: str, t: str, max_cost: int) -> int: 8 | max_len = 0 9 | l = 0 10 | cost = 0 11 | for r in range(len(s)): 12 | cost += abs(ord(s[r]) - ord(t[r])) 13 | while l <= r and cost > max_cost: 14 | cost -= abs(ord(s[l]) - ord(t[l])) 15 | l += 1 16 | max_len = max(max_len, r - l + 1) 17 | 18 | return max_len 19 | -------------------------------------------------------------------------------- /src/Interval.java: -------------------------------------------------------------------------------- 1 | public class Interval { 2 | int start; 3 | int end; 4 | 5 | Interval() { 6 | start = 0; 7 | end = 0; 8 | } 9 | 10 | Interval(int s, int e) { 11 | start = s; 12 | end = e; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Invalid_Transactions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Invalid Transactions 3 | 4 | Brute-force 5 | """ 6 | from typing import * 7 | import collections 8 | 9 | 10 | class Solution: 11 | def invalidTransactions(self, transactions: List[str]) -> List[str]: 12 | Trans = collections.namedtuple("Trans", ["str", "name", "time", "amount", "city"]) 13 | transactions = [Trans(t, *t.split(",")) for t in transactions] 14 | return [t.str for t in transactions 15 | if int(t.amount) > 1000 16 | or any(True for tt in transactions if 17 | t.name == tt.name and t.city != tt.city and abs(int(t.time) - int(tt.time)) <= 60)] 18 | -------------------------------------------------------------------------------- /src/LetterTilePossibilities.py: -------------------------------------------------------------------------------- 1 | """ 2 | Counting 3 | """ 4 | 5 | 6 | class Solution: 7 | def numTilePossibilities(self, tiles: str) -> int: 8 | 9 | memo = {} 10 | 11 | def f(s: str): 12 | if s == '': 13 | return 1 14 | if s in memo: 15 | return memo[s] 16 | ans = 1 17 | for ch in set(s): 18 | ans += f(''.join(sorted(s.replace(ch, '', 1)))) 19 | memo[s] = ans 20 | return ans 21 | 22 | return f(''.join(sorted(tiles))) - 1 # exclude the empty string 23 | -------------------------------------------------------------------------------- /src/ListNode.java: -------------------------------------------------------------------------------- 1 | public class ListNode { 2 | int val; 3 | ListNode next; 4 | 5 | public ListNode(int val) { 6 | this.val = val; 7 | next = null; 8 | } 9 | } -------------------------------------------------------------------------------- /src/LongestChunkedPalindromeDecomposition.py: -------------------------------------------------------------------------------- 1 | """ 2 | Longest Chunked Palindrome Decomposition 3 | 4 | DP 5 | 6 | Couldn't understand why this problem is marked as hard... 7 | """ 8 | 9 | 10 | class Solution: 11 | def longestDecomposition(self, text: str) -> int: 12 | 13 | def f(s, memo): 14 | if len(s) <= 1: 15 | return len(s) 16 | if s in memo: 17 | return memo[s] 18 | ans = 1 19 | for i in range(1, len(s)): 20 | if s[0:i] == s[len(s) - i:len(s)]: 21 | ans = max(ans, 2 + f(s[i:len(s) - i], memo)) 22 | memo[s] = ans 23 | return ans 24 | 25 | return f(text, {}) 26 | -------------------------------------------------------------------------------- /src/Longest_Arithmetic_Subsequence_of_Given_Difference.py: -------------------------------------------------------------------------------- 1 | """Longest Arithmetic Subsequence of Given Difference 2 | 3 | DP""" 4 | 5 | from typing import * 6 | from collections import defaultdict 7 | 8 | 9 | class Solution: 10 | def longestSubsequence(self, arr: List[int], difference: int) -> int: 11 | d = defaultdict(int) 12 | for i in arr: 13 | d[i] = d[i - difference] + 1 14 | return max(d.values()) 15 | -------------------------------------------------------------------------------- /src/Master.java: -------------------------------------------------------------------------------- 1 | interface Master { 2 | int guess(String word); 3 | } -------------------------------------------------------------------------------- /src/Maximum_Level_Sum_of_a_Binary_Tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Maximum Level Sum of a Binary Tree 3 | 4 | DFS 5 | """ 6 | 7 | from collections import * 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def maxLevelSum(self, root: TreeNode) -> int: 19 | level_sum = defaultdict(int) 20 | 21 | def dfs(root: TreeNode, level: int): 22 | if not root: 23 | return 24 | level_sum[level] += root.val 25 | dfs(root.left, level + 1) 26 | dfs(root.right, level + 1) 27 | 28 | dfs(root, 1) 29 | return -max([(sum, -level) for level, sum in level_sum.items()])[1] 30 | -------------------------------------------------------------------------------- /src/Maximum_Number_of_Balloons.py: -------------------------------------------------------------------------------- 1 | """Maximum Number of Balloons""" 2 | from typing import * 3 | from collections import * 4 | 5 | 6 | class Solution: 7 | def maxNumberOfBalloons(self, text: str) -> int: 8 | counter = Counter(text) 9 | balloon = Counter("balloon") 10 | ans = 1 << 29 11 | for k, v in balloon.items(): 12 | ans = min(ans, counter[k] // v) 13 | return ans 14 | -------------------------------------------------------------------------------- /src/Maximum_Subarray_Sum_with_One_Deletion.py: -------------------------------------------------------------------------------- 1 | """Maximum Subarray Sum with One Deletion 2 | 3 | DP 4 | Time = O(n) 5 | Space = O(1) 6 | """ 7 | 8 | from typing import * 9 | 10 | 11 | class Solution: 12 | def maximumSum(self, arr: List[int]) -> int: 13 | inf = 1 << 31 14 | delete_0 = arr[0] 15 | delete_1 = -inf 16 | ans = delete_0 17 | 18 | for i in range(1, len(arr)): 19 | new_delete_0 = max(delete_0 + arr[i], arr[i]) 20 | new_delete_1 = max(delete_0, delete_1 + arr[i]) 21 | delete_0, delete_1 = new_delete_0, new_delete_1 22 | ans = max(ans, delete_0, delete_1) 23 | 24 | return ans 25 | -------------------------------------------------------------------------------- /src/MinimumCostTreeFromLeafValues.py: -------------------------------------------------------------------------------- 1 | """ 2 | Minimum Cost Tree From Leaf Values 3 | 4 | DP 5 | """ 6 | 7 | from typing import * 8 | 9 | 10 | class Solution: 11 | memo = {} 12 | 13 | def mctFromLeafValues(self, arr: List[int]) -> int: 14 | if len(arr) == 1: 15 | return 0 16 | 17 | key = tuple(arr) 18 | if key in self.memo: 19 | return self.memo[key] 20 | ans = 1 << 31 21 | for i in range(1, len(arr)): 22 | left, right = arr[:i], arr[i:] 23 | ans = min(ans, self.mctFromLeafValues(left) + self.mctFromLeafValues(right) + max(left) * max(right)) 24 | self.memo[key] = ans 25 | return ans 26 | -------------------------------------------------------------------------------- /src/Minimum_Absolute_Difference.py: -------------------------------------------------------------------------------- 1 | """Minimum Absolute Difference""" 2 | from typing import * 3 | 4 | 5 | class Solution: 6 | def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: 7 | arr.sort() 8 | min_diff = min(arr[i] - arr[i - 1] for i in range(1, len(arr))) 9 | return [[arr[i - 1], arr[i]] for i in range(1, len(arr)) if arr[i] - arr[i - 1] == min_diff] 10 | -------------------------------------------------------------------------------- /src/MountainArray.java: -------------------------------------------------------------------------------- 1 | interface MountainArray { 2 | int get(int index); 3 | 4 | int length(); 5 | } 6 | -------------------------------------------------------------------------------- /src/NestedInteger.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public interface NestedInteger { 4 | 5 | // @return true if this NestedInteger holds a single integer, rather than a nested list. 6 | boolean isInteger(); 7 | 8 | // @return the single integer that this NestedInteger holds, if it holds a single integer 9 | // Return null if this NestedInteger holds a nested list 10 | Integer getInteger(); 11 | 12 | // @return the nested list that this NestedInteger holds, if it holds a nested list 13 | // Return null if this NestedInteger holds a single integer 14 | List getList(); 15 | } -------------------------------------------------------------------------------- /src/NthTribonacciNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | N-th Tribonacci Number 3 | """ 4 | 5 | 6 | class Solution: 7 | def tribonacci(self, n: int) -> int: 8 | T = [0] * 40 9 | T[0] = 0 10 | T[1] = 1 11 | T[2] = 1 12 | for i in range(3, len(T)): 13 | T[i] = T[i - 1] + T[i - 2] + T[i - 3] 14 | return T[n] 15 | -------------------------------------------------------------------------------- /src/NumberOfEquivalentDominoPairs.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.HashMap; 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | 7 | /** 8 | * Number of Equivalent Domino Pairs 9 | * 10 | * Counting 11 | */ 12 | public class NumberOfEquivalentDominoPairs { 13 | 14 | public int numEquivDominoPairs(int[][] dominoes) { 15 | Map, Integer> set = new HashMap<>(); 16 | int ans = 0; 17 | for (int[] pair : dominoes) { 18 | List key = Arrays.asList(Math.min(pair[0], pair[1]), Math.max(pair[0], pair[1])); 19 | ans += set.getOrDefault(key, 0); 20 | set.put(key, set.getOrDefault(key, 0) + 1); 21 | } 22 | return ans; 23 | } 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/OccurrencesAfterBigram.py: -------------------------------------------------------------------------------- 1 | from typing import * 2 | 3 | 4 | class Solution: 5 | def findOcurrences(self, text: str, first: str, second: str) -> List[str]: 6 | ans = [] 7 | a, b, c = '', '', '' 8 | for i in text.split(' '): 9 | a, b, c = b, c, i 10 | if a == first and b == second: 11 | ans.append(c) 12 | return ans 13 | -------------------------------------------------------------------------------- /src/Play_with_Chips.py: -------------------------------------------------------------------------------- 1 | """Play with Chips 2 | 3 | Math""" 4 | 5 | from typing import * 6 | from collections import * 7 | 8 | 9 | class Solution: 10 | def minCostToMoveChips(self, chips: List[int]) -> int: 11 | return len(chips) - max(Counter(i % 2 for i in chips).values()) 12 | -------------------------------------------------------------------------------- /src/Point.java: -------------------------------------------------------------------------------- 1 | public class Point { 2 | int x; 3 | int y; 4 | 5 | Point() { 6 | x = 0; 7 | y = 0; 8 | } 9 | 10 | Point(int a, int b) { 11 | x = a; 12 | y = b; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return "(" + x + "," + y + ")"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Prime_Arrangements.py: -------------------------------------------------------------------------------- 1 | """Prime Arrangements 2 | 3 | Math 4 | """ 5 | from math import * 6 | 7 | 8 | class Solution: 9 | def numPrimeArrangements(self, n: int) -> int: 10 | def is_prime(x: int) -> bool: 11 | if x < 2: 12 | return False 13 | return all(x % i != 0 for i in range(2, min(int(sqrt(x)) + 10, x))) 14 | 15 | mod = 10 ** 9 + 7 16 | 17 | def fac(x: int) -> int: 18 | return 1 if x <= 1 else x * fac(x - 1) % mod 19 | 20 | cnt = sum(1 for i in range(1, n + 1) if is_prime(i)) 21 | return fac(cnt) * fac(n - cnt) % mod 22 | -------------------------------------------------------------------------------- /src/Reader4.java: -------------------------------------------------------------------------------- 1 | public class Reader4 { 2 | // A dummy implementation 3 | public int read4(char[] buf) { 4 | return 0; 5 | } 6 | } -------------------------------------------------------------------------------- /src/Relation.java: -------------------------------------------------------------------------------- 1 | public class Relation { 2 | public boolean knows(int a, int b) { 3 | return true; 4 | } 5 | } -------------------------------------------------------------------------------- /src/RelativeSortArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Relative Sort Array 3 | """ 4 | 5 | from typing import * 6 | 7 | 8 | class Solution: 9 | def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: 10 | index = dict(zip(arr2, range(len(arr2)))) 11 | pairs = [(index[i] if i in index else 1 << 29, i) for i in arr1] 12 | return [val for _, val in sorted(pairs)] 13 | -------------------------------------------------------------------------------- /src/Remove_All_Adjacent_Duplicates_in_String_II.py: -------------------------------------------------------------------------------- 1 | """Remove All Adjacent Duplicates in String II 2 | 3 | Stack 4 | """ 5 | 6 | from typing import * 7 | from collections import * 8 | 9 | 10 | class Solution: 11 | def removeDuplicates(self, s: str, k: int) -> str: 12 | ans = [] 13 | for ch in s: 14 | cnt = ans[-1][1] + 1 if ans and ans[-1][0] == ch else 1 15 | ans.append([ch, cnt]) 16 | 17 | if ans[-1][1] >= k: 18 | for _ in range(k): 19 | ans.pop() 20 | 21 | return "".join(ch for ch, _ in ans) 22 | -------------------------------------------------------------------------------- /src/Remove_Zero_Sum_Consecutive_Nodes_from_Linked_List.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove Zero Sum Consecutive Nodes from Linked List 3 | 4 | Prefix Sum 5 | """ 6 | 7 | class ListNode: 8 | def __init__(self, x): 9 | self.val = x 10 | self.next = None 11 | 12 | 13 | class Solution: 14 | def removeZeroSumSublists(self, head: ListNode) -> ListNode: 15 | dummy = ListNode(0) 16 | dummy.next = head 17 | map = {0: dummy} 18 | sum = 0 19 | 20 | i = dummy 21 | while i.next: 22 | i = i.next 23 | 24 | sum += i.val 25 | if sum in map: 26 | map[sum].next = i.next 27 | else: 28 | map[sum] = i 29 | 30 | return dummy.next 31 | 32 | -------------------------------------------------------------------------------- /src/Reverse_Substrings_Between_Each_Pair_of_Parentheses.py: -------------------------------------------------------------------------------- 1 | """Reverse Substrings Between Each Pair of Parentheses 2 | 3 | Simulation via a stack 4 | """ 5 | class Solution: 6 | def reverseParentheses(self, s: str) -> str: 7 | stack = [""] 8 | for ch in s: 9 | if ch == "(": 10 | stack.append("") 11 | elif ch == ")": 12 | token = stack.pop(-1) 13 | stack[-1] += "".join(reversed(token)) 14 | else: 15 | stack[-1] += ch 16 | return stack[0] 17 | -------------------------------------------------------------------------------- /src/TreeNode.java: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | TreeNode(int x) { 7 | val = x; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Unique_Number_of_Occurrences.py: -------------------------------------------------------------------------------- 1 | """Unique Number of Occurrences""" 2 | 3 | from typing import * 4 | from collections import * 5 | 6 | 7 | class Solution: 8 | def uniqueOccurrences(self, arr: List[int]) -> bool: 9 | values = Counter(arr).values() 10 | return len(values) == len(set(values)) 11 | -------------------------------------------------------------------------------- /src/_1.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 1 - Two Sum 5 | * 6 | * O(n log n) - using two pointers 7 | */ 8 | public class _1 { 9 | public int[] twoSum(int[] nums, int target) { 10 | Integer[] sorted = new Integer[nums.length]; 11 | for (int i = 0; i < sorted.length; i++) sorted[i] = i; 12 | Arrays.sort(sorted, (u, v) -> Integer.compare(nums[u], nums[v])); 13 | for (int i = 0, j = nums.length - 1; i < j; ) 14 | if (nums[sorted[i]] + nums[sorted[j]] == target) return new int[]{sorted[i], sorted[j]}; 15 | else if (nums[sorted[i]] + nums[sorted[j]] > target) j--; 16 | else i++; 17 | return null; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/_1002.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 1002 - Find Common Characters 3 | """ 4 | from sys import * 5 | from typing import * 6 | from collections import * 7 | import string 8 | 9 | 10 | class Solution: 11 | def commonChars(self, A: List[str]) -> List[str]: 12 | counter = Counter(A[0]) 13 | for i in range(1, len(A)): 14 | counter &= Counter(A[i]) 15 | return counter.elements() 16 | -------------------------------------------------------------------------------- /src/_1003.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 1002 - Check If Word Is Valid After Substitutions 3 | """ 4 | from sys import * 5 | from typing import * 6 | from collections import * 7 | from string import * 8 | 9 | 10 | class Solution: 11 | def isValid(self, S: str) -> bool: 12 | s = [] 13 | for ch in S: 14 | if ch == 'a': 15 | s += ch 16 | elif ch == 'b': 17 | if not s or s[-1] != 'a': 18 | return False 19 | s += ch 20 | else: 21 | if not s or s[-1] != 'b': 22 | return False 23 | s.pop(-1) 24 | s.pop(-1) 25 | return not s -------------------------------------------------------------------------------- /src/_1005.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.stream.IntStream; 3 | 4 | /** 5 | * LeetCode 1005 - Maximize Sum of Array After K Negations 6 | * 7 | * Greedy 8 | */ 9 | public class _1005 { 10 | 11 | public int largestSumAfterKNegations(int[] A, int K) { 12 | Arrays.sort(A); 13 | for (int i = 0; i < A.length && A[i] < 0 && K > 0; i++) { 14 | A[i] = -A[i]; 15 | } 16 | int ans = IntStream.of(A).sum(); 17 | if (K % 2 == 1) { 18 | ans -= IntStream.of(A).min().getAsInt() * 2; 19 | } 20 | return ans; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/_1008.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 1008 - Construct Binary Search Tree from Preorder Traversal 3 | 4 | DFS 5 | """ 6 | 7 | from typing import * 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def bstFromPreorder(self, preorder: List[int]) -> TreeNode: 19 | if not preorder: 20 | return None 21 | root = TreeNode(preorder[0]) 22 | root.left = self.bstFromPreorder([i for i in preorder if i < root.val]) 23 | root.right = self.bstFromPreorder([i for i in preorder if i > root.val]) 24 | return root 25 | -------------------------------------------------------------------------------- /src/_1009.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1012 - Complement of Base 10 Integer 3 | * 4 | * Bit Manipulation 5 | */ 6 | public class _1009 { 7 | 8 | public int bitwiseComplement(int N) { 9 | if (N == 0) { 10 | return 1; 11 | } 12 | return (int)(((Long.highestOneBit(N) << 1) - 1) ^ N); 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/_1010.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1010 - Pairs of Songs With Total Durations Divisible by 60 3 | * 4 | * Counting 5 | */ 6 | public class _1010 { 7 | 8 | public int numPairsDivisibleBy60(int[] time) { 9 | int ans = 0; 10 | int[] cnt = new int[60]; 11 | for (int i : time) { 12 | ans += cnt[(60 - (i % 60)) % 60]; 13 | cnt[i % 60]++; 14 | } 15 | return ans; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/_1012.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1015 - Numbers With Repeated Digits 3 | * 4 | * Bracktracking 5 | */ 6 | public class _1012 { 7 | 8 | public int numDupDigitsAtMostN(int N) { 9 | return N - dfs(N, 0, 0); 10 | } 11 | 12 | int dfs(int N, int mask, long cur) { 13 | if (cur > N) { 14 | return 0; 15 | } 16 | int cnt = cur > 0 ? 1 : 0; 17 | for (int i = 0; i < 10; i++) { 18 | if (i == 0 && cur == 0) { 19 | continue; 20 | } 21 | if ((mask & (1 << i)) == 0) { 22 | cnt += dfs(N, mask | (1 << i), cur * 10 + i); 23 | } 24 | } 25 | return cnt; 26 | } 27 | } -------------------------------------------------------------------------------- /src/_1014.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1014 - Smallest Integer Divisible by K 3 | * 4 | * Math 5 | */ 6 | public class _1014 { 7 | 8 | public int smallestRepunitDivByK(int K) { 9 | int cnt = 1, g = 1 % K; 10 | boolean[] visited = new boolean[K]; 11 | while (g != 0) { 12 | cnt++; 13 | visited[g] = true; 14 | g = (g * 10 + 1) % K; 15 | if (visited[g]) { 16 | return -1; 17 | } 18 | } 19 | return cnt; 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/_1015.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 1015 - Smallest Integer Divisible by K 3 | 4 | Math 5 | I'm being lazy here. Ideally, we could return -1 if seeing a visited modulo. 6 | """ 7 | 8 | 9 | class Solution: 10 | def smallestRepunitDivByK(self, K: int) -> int: 11 | n = 1 12 | for i in range(1, K + 10): 13 | if n % K == 0: 14 | return i 15 | n = (n * 10 + 1) % K 16 | return -1 17 | -------------------------------------------------------------------------------- /src/_1017.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1017 - Convert to Base -2 3 | * 4 | * Math 5 | * Be careful when N == 0 6 | */ 7 | public class _1017 { 8 | 9 | public String baseNeg2(int N) { 10 | if (N == 0) { 11 | return "0"; 12 | } 13 | StringBuilder builder = new StringBuilder(); 14 | int cnt = 0; 15 | while (N != 0) { 16 | if (N % 2 == 0) { 17 | builder.append(0); 18 | } else { 19 | builder.append(1); 20 | N += cnt % 2 == 0 ? (-1) : 1; 21 | } 22 | N /= 2; 23 | cnt++; 24 | } 25 | return builder.reverse().toString(); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/_1018.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 1018 - Binary Prefix Divisible By 5 6 | * 7 | * Math 8 | */ 9 | public class _1018 { 10 | 11 | public List prefixesDivBy5(int[] A) { 12 | List res = new ArrayList<>(A.length); 13 | int sum = 0; 14 | for (int bit : A) { 15 | sum = (sum * 2 + bit) % 5; 16 | res.add(sum == 0); 17 | } 18 | return res; 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/_1021.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1021 - Best Sightseeing Pair 3 | * 4 | * Greedy 5 | * O(n)-time solution 6 | */ 7 | public class _1021 { 8 | 9 | public int maxScoreSightseeingPair(int[] A) { 10 | int ans = Integer.MIN_VALUE; 11 | int max = A[0] + 0; 12 | for (int j = 1; j < A.length; j++) { 13 | ans = Math.max(ans, max + A[j] - j); 14 | max = Math.max(max, A[j] + j); 15 | } 16 | return ans; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/_1023.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 1023 - Camelcase Matching 3 | 4 | Brute-force 5 | """ 6 | 7 | from typing import * 8 | 9 | 10 | class Solution: 11 | def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: 12 | ans = [] 13 | for query in queries: 14 | i = j = 0 15 | while True: 16 | if i < len(query) and j < len(pattern) and query[i] == pattern[j]: 17 | i += 1 18 | j += 1 19 | elif i < len(query) and query[i].islower(): 20 | i += 1 21 | else: 22 | break 23 | ans.append(i == len(query) and j == len(pattern)) 24 | return ans 25 | -------------------------------------------------------------------------------- /src/_1024.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 1024 - Video Stitching 3 | 4 | DP 5 | """ 6 | 7 | from typing import * 8 | 9 | 10 | class Solution: 11 | def videoStitching(self, clips: List[List[int]], T: int) -> int: 12 | if T == 0: 13 | return 1 if [1 for clip in clips if clip[0] == 0] else -1 14 | 15 | inf = 1 << 29 16 | f = [inf] * (T + 1) 17 | f[0] = 0 18 | 19 | for i in range(1, T + 1): 20 | for begin, end in clips: 21 | if begin < i <= end: 22 | f[i] = min(f[i], 1 + f[begin]) 23 | 24 | return f[T] if f[T] < inf else -1 25 | -------------------------------------------------------------------------------- /src/_1025.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode - Divisor Game 3 | * 4 | * Game Theory 5 | */ 6 | public class _1025 { 7 | 8 | public boolean divisorGame(int N) { 9 | boolean[] f = new boolean[N + 1]; 10 | for (int i = 1; i <= N; i++) { 11 | f[i] = false; 12 | for (int j = 1; j < i; j++) { 13 | if (i % j == 0 && !f[i - j]) { 14 | f[i] = true; 15 | break; 16 | } 17 | } 18 | } 19 | return f[N]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/_1027.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 1027 - Longest Arithmetic Sequence 3 | 4 | O(n^2)-time DP 5 | """ 6 | 7 | from typing import * 8 | 9 | 10 | class Solution: 11 | def longestArithSeqLength(self, A: List[int]) -> int: 12 | ans = 2 13 | f = {} 14 | for i in range(1, len(A)): 15 | for j in range(0, i): 16 | diff = A[i] - A[j] 17 | length = 1 + f[j, diff] if (j, diff) in f else 2 18 | f[i, diff] = length # Technically, we need to f[i, diff] = max(f[i, diff], length), but this works. 19 | ans = max(ans, length) 20 | return ans 21 | -------------------------------------------------------------------------------- /src/_1033.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 1033 - Moving Stones Until Consecutive 5 | * 6 | * Min = 1 case is tricky. 7 | */ 8 | public class _1033 { 9 | 10 | public int[] numMovesStones(int a, int b, int c) { 11 | int[] arr = {a, b, c}; 12 | Arrays.sort(arr); 13 | int max = arr[2] - arr[0] - 2; 14 | int min = 2; 15 | if (arr[1] - arr[0] == 1 || arr[2] - arr[1] == 1) { 16 | min = 1; 17 | } 18 | if (arr[1] - arr[0] == 2 || arr[2] - arr[1] == 2) { 19 | min = Math.min(min, 1); 20 | } 21 | if (arr[1] - arr[0] == 1 && arr[2] - arr[1] == 1) { 22 | min = 0; 23 | } 24 | return new int[]{min, max}; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/_1035.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 1035 - Uncrossed Lines 3 | 4 | DP 5 | Quite similar to LCS problem 6 | """ 7 | 8 | from typing import * 9 | 10 | 11 | class Solution: 12 | def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: 13 | def dfs(i, j, memo): 14 | if i < 0 or j < 0: 15 | return 0 16 | if (i, j) in memo: 17 | return memo[i, j] 18 | if A[i] == B[j]: 19 | ans = dfs(i - 1, j - 1, memo) + 1 20 | else: 21 | ans = max(dfs(i, j - 1, memo), dfs(i - 1, j, memo)) 22 | memo[i, j] = ans 23 | return ans 24 | 25 | return dfs(len(A) - 1, len(B) - 1, {}) 26 | -------------------------------------------------------------------------------- /src/_1037.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1037 - Valid Boomerang 3 | * 4 | * Cross-product 5 | */ 6 | public class _1037 { 7 | 8 | public boolean isBoomerang(int[][] points) { 9 | long x1 = points[0][0] - points[1][0]; 10 | long y1 = points[0][1] - points[1][1]; 11 | long x2 = points[0][0] - points[2][0]; 12 | long y2 = points[0][1] - points[2][1]; 13 | return x1 * y2 - x2 * y1 != 0; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/_1038.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1038 - Binary Search Tree to Greater Sum Tree 3 | * 4 | * In-order traversal (right -> root -> left) 5 | */ 6 | public class _1038 { 7 | 8 | int sum = 0; 9 | 10 | public TreeNode bstToGst(TreeNode root) { 11 | int sum = 0; 12 | dfs(root); 13 | return root; 14 | } 15 | 16 | void dfs(TreeNode root) { 17 | if (root == null) { 18 | return; 19 | } 20 | dfs(root.right); 21 | sum += root.val; 22 | root.val = sum; 23 | dfs(root.left); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/_1046.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.PriorityQueue; 3 | 4 | /** 5 | * LeetCode 1046 - Last Stone Weight 6 | * 7 | * Heap 8 | */ 9 | public class _1046 { 10 | 11 | public int lastStoneWeight(int[] stones) { 12 | PriorityQueue a = new PriorityQueue<>(Comparator.comparingInt(i -> i).reversed()); 13 | for (int i : stones) { 14 | a.add(i); 15 | } 16 | while (a.size() > 1) { 17 | int y = a.poll(); 18 | int x = a.poll(); 19 | if (x < y) { 20 | a.add(y - x); 21 | } 22 | } 23 | return a.isEmpty() ? 0 : a.poll(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/_1047.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * LeetCode 1047 - Remove All Adjacent Duplicates In String 5 | * 6 | * Brute-force 7 | */ 8 | public class _1047 { 9 | 10 | public String removeDuplicates(String S) { 11 | Stack stack = new Stack<>(); 12 | for (char ch : S.toCharArray()) { 13 | if (!stack.isEmpty() && stack.peek() == ch) { 14 | stack.pop(); 15 | } else { 16 | stack.push(ch); 17 | } 18 | } 19 | StringBuilder builder = new StringBuilder(""); 20 | for (char ch : stack) { 21 | builder.append(ch); 22 | } 23 | return builder.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/_1051.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | 4 | /** 5 | * LeetCode 1051 - Height Checker 6 | * 7 | * Sorting 8 | * 9 | * Problem description is pretty bad. 10 | */ 11 | public class _1051 { 12 | 13 | public int heightChecker(int[] heights) { 14 | int[] sorted = IntStream.of(heights).sorted().toArray(); 15 | int cnt = 0; 16 | for (int i = 0; i < heights.length; i++) { 17 | if (sorted[i] != heights[i]) { 18 | cnt++; 19 | } 20 | } 21 | return cnt; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/_1064.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 1064 - Fixed Point 3 | */ 4 | public class _1064 { 5 | 6 | public int fixedPoint(int[] A) { 7 | for (int i=0; i wordDict) { 11 | boolean[] f = new boolean[s.length() + 1]; 12 | f[f.length - 1] = true; 13 | for (int i = s.length() - 1; i >= 0; i--) 14 | for (int j = i + 1; j <= s.length(); j++) 15 | if (wordDict.contains(s.substring(i, j))) 16 | f[i] = f[i] || f[j]; 17 | return f[0]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/_151.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 151 - Reverse Words in a String 3 | */ 4 | public class _151 { 5 | public String reverseWords(String s) { 6 | String[] tokens = s.trim().split("[ ]+"); 7 | for (int i = 0, j = tokens.length - 1; i < j; i++, j--) { 8 | String str = tokens[i]; 9 | tokens[i] = tokens[j]; 10 | tokens[j] = str; 11 | } 12 | return String.join(" ", tokens); 13 | } 14 | } -------------------------------------------------------------------------------- /src/_155.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * LeetCode 155 - Min Stack 5 | * 6 | * Use slightly more memory for shorter code. 7 | */ 8 | public class _155 { 9 | 10 | Stack stack; 11 | Stack min; 12 | 13 | public _155() { 14 | stack = new Stack<>(); 15 | min = new Stack<>(); 16 | min.push(Integer.MAX_VALUE); 17 | } 18 | 19 | public void push(int x) { 20 | stack.push(x); 21 | min.push(Math.min(min.peek(), x)); 22 | } 23 | 24 | public void pop() { 25 | stack.pop(); 26 | min.pop(); 27 | } 28 | 29 | public int top() { 30 | return stack.peek(); 31 | } 32 | 33 | public int getMin() { 34 | return min.peek(); 35 | } 36 | } -------------------------------------------------------------------------------- /src/_159.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 159 - Longest Substring with At Most Two Distinct Characters 3 | *

4 | * Sliding-window 5 | */ 6 | public class _159 { 7 | public int lengthOfLongestSubstringTwoDistinct(String s) { 8 | int ans = 0, distinct = 0; 9 | int[] cnt = new int[128]; 10 | for (int r = 0, l = 0; r < s.length(); r++) { 11 | if (cnt[s.charAt(r)]++ == 0) distinct++; 12 | while (l < r && distinct > 2) 13 | if (--cnt[s.charAt(l++)] == 0) distinct--; 14 | ans = Math.max(ans, r - l + 1); 15 | } 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_161.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 161 - One Edit Distance 3 | * 4 | * Short Java code 5 | */ 6 | public class _161 { 7 | public boolean isOneEditDistance(String s, String t) { 8 | if (s.length() > t.length()) return isOneEditDistance(t, s); 9 | for (int i = 0; i < s.length(); i++) 10 | if (s.charAt(i) != t.charAt(i)) 11 | return i + 1 <= t.length() && s.substring(s.length() < t.length() ? i : i + 1).equals(t.substring(i + 1)); 12 | return t.length() - s.length() == 1; 13 | } 14 | } -------------------------------------------------------------------------------- /src/_165.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 165 - Compare Version Numbers 3 | * 4 | * Note that if the version is not specified, it is 0 by default, i.e., 5 | * 1 == 1.0.0 6 | */ 7 | public class _165 { 8 | public int compareVersion(String version1, String version2) { 9 | String[] a = version1.split("\\."); 10 | String[] b = version2.split("\\."); 11 | for (int i = 0; i < a.length || i < b.length; i++) { 12 | int first = i < a.length ? Integer.parseInt(a[i]) : 0; 13 | int second = i < b.length ? Integer.parseInt(b[i]) : 0; 14 | if (first != second) return Integer.compare(first, second); 15 | } 16 | return 0; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_167.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 167 - Two Sum II - Input array is sorted 5 | *

6 | * Two-pointer method 7 | */ 8 | public class _167 { 9 | public int[] twoSum(int[] numbers, int target) { 10 | for (int i = 0, j = numbers.length - 1; i < j; ) 11 | if (numbers[i] + numbers[j] < target) i++; 12 | else if (numbers[i] + numbers[j] > target) j--; 13 | else return new int[]{i + 1, j + 1}; 14 | throw new RuntimeException("No solution exists for array " + Arrays.toString(numbers) + ", and target = " + target); 15 | } 16 | } -------------------------------------------------------------------------------- /src/_175.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 175 - Combine Two Tables 2 | 3 | SELECT 4 | FirstName, 5 | LastName, 6 | City, 7 | State 8 | FROM 9 | Person a 10 | LEFT OUTER JOIN 11 | Address b 12 | ON 13 | a.PersonId = b.PersonId -------------------------------------------------------------------------------- /src/_176.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 176 - Second Highest Salary 2 | SELECT ( 3 | SELECT DISTINCT 4 | Salary 5 | FROM 6 | Employee 7 | ORDER BY 8 | Salary DESC 9 | LIMIT 1 OFFSET 1 10 | ) AS SecondHighestSalary -------------------------------------------------------------------------------- /src/_177.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 177 - Nth Highest Salary 2 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 3 | BEGIN 4 | DECLARE M INT; 5 | SET M = N - 1; 6 | RETURN ( 7 | SELECT DISTINCT Salary 8 | FROM Employee 9 | ORDER BY Salary DESC 10 | LIMIT 1 OFFSET M 11 | ); 12 | END -------------------------------------------------------------------------------- /src/_178.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 178 - Rank Scores 2 | SELECT 3 | Score, 4 | (SELECT COUNT(DISTINCT b.score) FROM (SELECT DISTINCT Score FROM Scores) AS b WHERE b.Score >= a.Score) AS Rank 5 | FROM Scores AS a 6 | ORDER BY Rank -------------------------------------------------------------------------------- /src/_180.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 180 - Consecutive Numbers 2 | SELECT DISTINCT 3 | a.Num AS ConsecutiveNums 4 | FROM 5 | Logs a 6 | INNER JOIN ( 7 | SELECT 8 | Id + 1 AS Id, Num 9 | FROM 10 | Logs 11 | ) b 12 | ON 13 | a.Id = b.Id AND a.Num = b.Num 14 | INNER JOIN ( 15 | SELECT 16 | Id + 2 AS Id, Num 17 | FROM 18 | Logs 19 | ) c 20 | ON 21 | a.Id = c.Id AND a.Num = c.Num 22 | -------------------------------------------------------------------------------- /src/_181.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 181 - Employees Earning More Than Their Managers 2 | SELECT 3 | a.Name AS Employee 4 | FROM 5 | Employee a 6 | INNER JOIN 7 | Employee b 8 | ON 9 | a.ManagerId = b.Id 10 | WHERE 11 | a.Salary > b.Salary 12 | -------------------------------------------------------------------------------- /src/_182.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 182 - Duplicate Emails 2 | 3 | SELECT 4 | Email 5 | FROM 6 | Person 7 | GROUP BY 8 | Email 9 | HAVING 10 | COUNT(Id) > 1 -------------------------------------------------------------------------------- /src/_183.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 183 - Customers Who Never Orders 2 | SELECT 3 | a.Name AS Customers 4 | FROM 5 | Customers a 6 | LEFT OUTER JOIN 7 | Orders b 8 | ON 9 | a.Id = b.CustomerId 10 | WHERE 11 | b.CustomerId IS NULL -------------------------------------------------------------------------------- /src/_184.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 184 - Department Highest Salary 2 | SELECT d.Name AS Department, e.Name AS Employee, e.Salary AS Salary 3 | FROM ( 4 | SELECT Name, DepartmentId, Salary 5 | FROM Employee a 6 | WHERE NOT EXISTS (SELECT * FROM Employee b WHERE a.DepartmentId = b.DepartmentId AND a.Salary < b.Salary) 7 | ) e 8 | INNER JOIN Department d 9 | ON e.DepartmentId = d.Id -------------------------------------------------------------------------------- /src/_186.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 186 - Reverse Words in a String II 3 | *

4 | * In-place solution 5 | */ 6 | public class _186 { 7 | private void reverse(char[] s, int i, int j) { 8 | for (; i < j; i++, j--) { 9 | char tmp = s[i]; 10 | s[i] = s[j]; 11 | s[j] = tmp; 12 | } 13 | } 14 | 15 | public void reverseWords(char[] s) { 16 | for (int i = 0, j = 0; i < s.length; ) 17 | if (s[i] == ' ') i++; 18 | else { 19 | for (j = i + 1; j < s.length && s[j] != ' '; j++) ; 20 | reverse(s, i, j - 1); 21 | i = j; 22 | } 23 | reverse(s, 0, s.length - 1); 24 | } 25 | } -------------------------------------------------------------------------------- /src/_196.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 196 - Delete Duplicate Emails 2 | -- Cannot Delete/Update and Select the same table at a time 3 | DELETE FROM 4 | Person 5 | WHERE 6 | Id NOT IN ( 7 | SELECT 8 | Id 9 | FROM ( 10 | SELECT 11 | MIN(Id) AS Id, 12 | Email 13 | FROM 14 | Person 15 | GROUP BY 16 | Email 17 | ) b 18 | ) -------------------------------------------------------------------------------- /src/_197.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 197 - Rising Temperature 2 | SELECT 3 | today.Id 4 | FROM 5 | Weather today 6 | INNER JOIN 7 | Weather yesterday 8 | ON 9 | today.Date = DATE_ADD(yesterday.Date, INTERVAL 1 DAY) 10 | WHERE 11 | today.Temperature > yesterday.Temperature -------------------------------------------------------------------------------- /src/_1_1.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.HashMap; 3 | import java.util.Map; 4 | 5 | /** 6 | * LeetCode 1 - Two Sum 7 | *

8 | * O(n) - using Hash Table 9 | * Beat 98.70% 10 | */ 11 | public class _1_1 { 12 | public int[] twoSum(int[] nums, int target) { 13 | Map map = new HashMap<>(); 14 | for (int i = 0; i < nums.length; i++) { 15 | Integer hehe = map.get(target - nums[i]); 16 | if (hehe != null) return new int[]{hehe, i}; 17 | map.put(nums[i], i); 18 | } 19 | return null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/_206.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 206 - Reverse Linked List 3 | */ 4 | public class _206 { 5 | public ListNode reverseList(ListNode head) { 6 | ListNode dummy = new ListNode(0); 7 | while (head != null) { 8 | ListNode i = head; 9 | head = head.next; 10 | i.next = dummy.next; 11 | dummy.next = i; 12 | } 13 | return dummy.next; 14 | } 15 | } -------------------------------------------------------------------------------- /src/_22_1.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * LeetCode 22 - Generate Parentheses 8 | *

9 | * Recursion 10 | */ 11 | public class _22_1 { 12 | 13 | void dfs(int balance, String s, int n, List list) { 14 | if (balance < 0) return; 15 | if (s.length() == 2 * n) { 16 | if (balance == 0) list.add(s); 17 | } else { 18 | dfs(balance + 1, s + "(", n, list); 19 | dfs(balance - 1, s + ")", n, list); 20 | } 21 | } 22 | 23 | public List generateParenthesis(int n) { 24 | List res = new ArrayList<>(); 25 | dfs(0, "", n, res); 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/_246.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 246 - Strobogrammatic Number 3 | *

4 | * Brute-force 5 | */ 6 | public class _246 { 7 | private char map(char ch) { 8 | if (ch == '6') return '9'; 9 | else if (ch == '9') return '6'; 10 | else if (ch == '1') return '1'; 11 | else if (ch == '8') return '8'; 12 | else if (ch == '0') return '0'; 13 | else return 0; 14 | } 15 | 16 | public boolean isStrobogrammatic(String num) { 17 | char[] s = num.toCharArray(); 18 | for (char ch : s) if (map(ch) == 0) return false; 19 | for (int i = 0, j = s.length - 1; i <= j; i++, j--) 20 | if (map(s[i]) != s[j]) return false; 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /src/_252.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 252 - Meeting Rooms 5 | *

6 | * Sweepline method 7 | */ 8 | public class _252 { 9 | public boolean canAttendMeetings(Interval[] intervals) { 10 | Arrays.sort(intervals, (u, v) -> Integer.compare(u.start, v.start)); 11 | int rightBoundary = Integer.MIN_VALUE; 12 | for (Interval interval : intervals) { 13 | if (rightBoundary > interval.start) return false; 14 | rightBoundary = Math.max(rightBoundary, interval.end); 15 | } 16 | return true; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_2535 Difference Between Element Sum and Digit Sum of an Array.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 2535 - Difference Between Element Sum and Digit Sum of an Array 3 | */ 4 | class Solution { 5 | public: 6 | int differenceOfSum(vector &nums) { 7 | int element_sum = 0, digit_sum = 0; 8 | for (int num: nums) { 9 | element_sum += num; 10 | while (num) { 11 | digit_sum += num % 10; 12 | num /= 10; 13 | } 14 | } 15 | return abs(element_sum - digit_sum); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /src/_2540_Minimum_Common_Value.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 2540 - Minimum Common Value 3 | """ 4 | class Solution: 5 | def getCommon(self, nums1: List[int], nums2: List[int]) -> int: 6 | intersection = set(nums1) & set(nums2) 7 | return min(intersection) if intersection else -1 8 | -------------------------------------------------------------------------------- /src/_2544_Alternating_Digit_Sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 2544. Alternating Digit Sum 3 | */ 4 | class Solution { 5 | public: 6 | int alternateDigitSum(int n) { 7 | string s = to_string(n); 8 | int ans = 0, sign = 1; 9 | for (char ch: s) { 10 | ans += sign * (ch - '0'); 11 | sign = -sign; 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /src/_2545_Sort_the_Students_by_Their_Kth_Score.py: -------------------------------------------------------------------------------- 1 | """ 2 | 2545. Sort the Students by Their Kth Score 3 | """ 4 | class Solution: 5 | def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]: 6 | return sorted(score, key=lambda row: -row[k]) 7 | -------------------------------------------------------------------------------- /src/_2549.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 2549 - Count Distinct Numbers on Board 3 | 4 | Simulation approach 5 | """ 6 | class Solution: 7 | def distinctIntegers(self, n: int) -> int: 8 | nums = {n} 9 | while True: 10 | new_nums = set(nums) 11 | for x in nums: 12 | for i in range(1, n + 1): 13 | if x % i == 1: 14 | new_nums.add(i) 15 | if len(new_nums) > len(nums): 16 | nums = new_nums 17 | else: 18 | break 19 | return len(nums) 20 | 21 | -------------------------------------------------------------------------------- /src/_2549_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 2549 - Count Distinct Numbers on Board 3 | 4 | Math 5 | 6 | It is easy to see x % (x - 1) is always equal to 1, when x >= 2. 7 | In fact, x = (x - 1) + 1 = 1 mod (x - 1). 8 | 9 | Therefore, when n >= 2, all integers from 2 to n will eventually 10 | be written on the board, and 1 will never be there since 11 | n % 1 = n >= 2. 12 | 13 | Spacial case happens when n = 1, and it's easy to see the answer is 1. 14 | """ 15 | class Solution: 16 | def distinctIntegers(self, n: int) -> int: 17 | return 1 if n == 1 else n - 1 18 | -------------------------------------------------------------------------------- /src/_2550.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 2550 - Count Collisions of Monkeys on a Polygon 3 | """ 4 | class Solution: 5 | def monkeyMove(self, n: int) -> int: 6 | mod = 1000000007 7 | 8 | def pow(a: int, n: int) -> int: 9 | ans = 1 10 | while n > 0: 11 | if n % 2 == 1: 12 | ans = ans * a % mod 13 | a = a * a % mod 14 | n //= 2 15 | return ans 16 | 17 | ans = (pow(2, n) + mod - 2) % mod 18 | return ans 19 | -------------------------------------------------------------------------------- /src/_2553.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 2553 - Separate the Digits in an Array 3 | 4 | 1-liner solution 5 | """ 6 | class Solution: 7 | def separateDigits(self, nums: List[int]) -> List[int]: 8 | return [int(digit) for num in nums for digit in str(num)] -------------------------------------------------------------------------------- /src/_2554.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 2554 - Maximum Number of Integers to Choose From a Range I 3 | * 4 | * Simulation 5 | */ 6 | class Solution { 7 | public: 8 | int maxCount(vector& banned, int n, int maxSum) { 9 | int ans = 0; 10 | unordered_set ban(banned.begin(), banned.end()); 11 | for (int i=1; i<=n; i++) { 12 | if (ban.count(i)) continue; 13 | maxSum -= i; 14 | if (maxSum >= 0) { 15 | ans++; 16 | } else { 17 | break; 18 | } 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /src/_2558.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 2558 - Take Gifts From the Richest Pile 3 | 4 | Simulation using Heap 5 | 6 | Time complexity: O(n log n) 7 | Space complexity: O(n) 8 | """ 9 | from sortedcontainers import SortedList 10 | 11 | class Solution: 12 | def pickGifts(self, gifts: List[int], k: int) -> int: 13 | gifts = SortedList(gifts) 14 | for _ in range(k): 15 | g = gifts.pop() 16 | sqrt = (int)(g**(0.5)) 17 | if (sqrt+1)*(sqrt+1) <= g: 18 | sqrt += 1 19 | gifts.add(sqrt) 20 | return sum(gifts) 21 | -------------------------------------------------------------------------------- /src/_2562.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCod3 2562 - Find the Array Concatenation Value 3 | 4 | Simulation 5 | """ 6 | class Solution: 7 | def findTheArrayConcVal(self, nums: List[int]) -> int: 8 | i = 0 9 | j = len(nums) - 1 10 | ans = 0 11 | while i <= j: 12 | if i < j: 13 | ans += int(str(nums[i]) + str(nums[j])) 14 | else: 15 | ans += nums[i] 16 | i += 1 17 | j -= 1 18 | return ans 19 | -------------------------------------------------------------------------------- /src/_259.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 259 - 3Sum Smaller 5 | *

6 | * Two-pointer method 7 | */ 8 | public class _259 { 9 | public int threeSumSmaller(int[] nums, int target) { 10 | int ans = 0; 11 | Arrays.sort(nums); 12 | for (int i = 0; i < nums.length; i++) 13 | for (int j = i + 1, k = nums.length - 1; j < k; ) 14 | if (nums[i] + nums[j] + nums[k] < target) ans += k - (j++); 15 | else k--; 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_262.sql: -------------------------------------------------------------------------------- 1 | -- LeetCode 262 - Trips and Users 2 | SELECT 3 | t.Request_at AS Day, 4 | ROUND(sum(case when t.Status like 'cancelled_%' then 1 else 0 end)/count(*), 2) AS 'Cancellation Rate' 5 | FROM Trips t 6 | INNER JOIN Users u 7 | ON t.Client_Id = u.Users_Id AND u.Banned = 'No' 8 | WHERE t.Request_at BETWEEN '2013-10-01' AND '2013-10-03' 9 | GROUP BY t.Request_at -------------------------------------------------------------------------------- /src/_266.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 266 - Palindrome Permutation 3 | *

4 | * Counting 5 | */ 6 | public class _266 { 7 | public boolean canPermutePalindrome(String s) { 8 | int[] cnt = new int[128]; 9 | for (char ch : s.toCharArray()) cnt[ch]++; 10 | int odd = 0; 11 | for (int i : cnt) if (i % 2 == 1) odd++; 12 | return odd <= 1; 13 | } 14 | } -------------------------------------------------------------------------------- /src/_270.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 270 - Closest Binary Search Tree Value 3 | * 4 | * Path Traversal in BST 5 | */ 6 | public class _270 { 7 | public int closestValue(TreeNode root, double target) { 8 | int ans = root.val; 9 | while (root != null) { 10 | if (Double.compare(Math.abs(target - root.val), Math.abs(target - ans)) < 0) ans = root.val; 11 | if (target < root.val) root = root.left; 12 | else root = root.right; 13 | } 14 | return ans; 15 | } 16 | } -------------------------------------------------------------------------------- /src/_274.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 274 - H-Index 3 | * 4 | * O(n) Counting Sort 5 | */ 6 | public class _274 { 7 | public int hIndex(int[] citations) { 8 | int[] cnt = new int[citations.length + 1]; 9 | for (int i : citations) cnt[Math.min(i, cnt.length - 1)]++; 10 | for (int i = cnt.length - 1, sum = 0; i >= 0; i--) { 11 | sum += cnt[i]; 12 | if (sum >= i) return i; 13 | } 14 | return 0; 15 | } 16 | } -------------------------------------------------------------------------------- /src/_277.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 277 - Find the Celebrity 3 | * 4 | * O(n) solution using adjacent matrix 5 | */ 6 | public class _277 extends Relation { 7 | public int findCelebrity(int n) { 8 | int cand = 0; 9 | for (int i = 1; i < n; i++) 10 | if (knows(cand, i)) cand = i; 11 | for (int i = 0; i < n; i++) 12 | if (i != cand && (knows(cand, i) || !knows(i, cand))) return -1; 13 | return cand; 14 | } 15 | } -------------------------------------------------------------------------------- /src/_280.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 280 - Wiggle Sort 3 | *

4 | * One-pass Solution 5 | */ 6 | public class _280 { 7 | public void wiggleSort(int[] nums) { 8 | boolean isLe = true; 9 | for (int i = 0; i + 1 < nums.length; i++, isLe = !isLe) { 10 | if ((isLe && nums[i] > nums[i + 1]) || (!isLe && nums[i] < nums[i + 1])) { 11 | int tmp = nums[i]; 12 | nums[i] = nums[i + 1]; 13 | nums[i + 1] = tmp; 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /src/_283.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 283 - Move Zeroes 3 | * 4 | * Similar ideas as Partition in Quicksort 5 | */ 6 | public class _283 { 7 | public void moveZeroes(int[] nums) { 8 | for (int l = 0, r = 0; r < nums.length; r++) 9 | if (nums[r] != 0) { 10 | int tmp = nums[l]; 11 | nums[l] = nums[r]; 12 | nums[r] = tmp; 13 | l++; 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/_283_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 283 - Move Zeroes 3 | * 4 | * A "cheating" method 5 | */ 6 | public class _283_1 { 7 | public void moveZeroes(int[] nums) { 8 | int l = 0; 9 | for (int r = 0; r < nums.length; r++) 10 | if (nums[r] != 0) nums[l++] = nums[r]; 11 | for (int i = l; i < nums.length; i++) nums[i] = 0; 12 | } 13 | } -------------------------------------------------------------------------------- /src/_285.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 285 - Inorder Successor in BST 3 | * 4 | * Top-down approach 5 | */ 6 | public class _285 { 7 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 8 | TreeNode ans = null; 9 | while (root != null) { 10 | if (root.val > p.val) { 11 | ans = root; 12 | root = root.left; 13 | } else root = root.right; 14 | } 15 | return ans; 16 | } 17 | } -------------------------------------------------------------------------------- /src/_293.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 293 - Flip Game 6 | *

7 | * Brute-force 8 | */ 9 | public class _293 { 10 | public List generatePossibleNextMoves(String s) { 11 | List list = new ArrayList<>(); 12 | char[] str = s.toCharArray(); 13 | for (int i = 0; i < str.length - 1; i++) 14 | if (str[i] == '+' && str[i + 1] == '+') { 15 | str[i] = str[i + 1] = '-'; 16 | list.add(String.copyValueOf(str)); 17 | str[i] = str[i + 1] = '+'; 18 | } 19 | return list; 20 | } 21 | } -------------------------------------------------------------------------------- /src/_298_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 298 - Binary Tree Longest Consecutive Sequence 3 | * 4 | * A in-place DFS solution 5 | */ 6 | public class _298_1 { 7 | int ans; 8 | private void dfs(TreeNode root, int len) { 9 | ans = Math.max(ans, len); 10 | for (TreeNode child : new TreeNode[]{root.left, root.right}) 11 | if (child != null) { 12 | if (root.val + 1 == child.val) dfs(child, len + 1); 13 | else dfs(child, 1); 14 | } 15 | } 16 | 17 | public int longestConsecutive(TreeNode root) { 18 | ans = 0; 19 | if (root != null) dfs(root, 1); 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/_298_2.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 298 - Binary Tree Longest Consecutive Sequence 3 | *

4 | * Yet another DFS solution 5 | */ 6 | public class _298_2 { 7 | 8 | int ans = 0; 9 | 10 | private void dfs(TreeNode root, TreeNode parent, int size) { 11 | if (root == null) return; 12 | int newSize = parent == null || root.val - 1 == parent.val ? size + 1 : 1; 13 | ans = Math.max(ans, newSize); 14 | dfs(root.left, root, newSize); 15 | dfs(root.right, root, newSize); 16 | } 17 | 18 | public int longestConsecutive(TreeNode root) { 19 | ans = 0; 20 | dfs(root, null, 0); 21 | return ans; 22 | } 23 | } -------------------------------------------------------------------------------- /src/_303.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 303 - Range Sum Query - Immutable 3 | * 4 | * O(n) preprocessing 5 | * O(1) query 6 | * 7 | * Simple prefix sum trick 8 | */ 9 | public class _303 { 10 | 11 | private int[] sum; 12 | 13 | public _303(int[] nums) { 14 | sum = new int[nums.length]; 15 | for (int i=0; i 7 | * O(n) solution using prefixSum and hash table 8 | */ 9 | public class _325 { 10 | public int maxSubArrayLen(int[] nums, int k) { 11 | int ans = 0, prefixSum = 0; 12 | Map map = new HashMap<>(); 13 | map.put(0, -1); 14 | for (int i = 0; i < nums.length; i++) { 15 | prefixSum += nums[i]; 16 | if (map.containsKey(prefixSum - k)) ans = Math.max(ans, i - map.get(prefixSum - k)); 17 | map.putIfAbsent(prefixSum, i); 18 | } 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /src/_326.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 326 - Power of Three 3 | * 4 | * O(log log n) 5 | * 6 | * See below for an interesting discussion about this topic. 7 | * https://leetcode.com/discuss/78698/let-us-discuss-when-is-unbounded-and-can-be-arbitrarily-large 8 | */ 9 | public class _326 { 10 | public boolean isPowerOfThree(int n) { 11 | long a = 3; 12 | for (; a < n; a *= a); 13 | return n > 0 && a % n == 0; 14 | } 15 | } -------------------------------------------------------------------------------- /src/_328.java: -------------------------------------------------------------------------------- 1 | /** 2 | * ListCode 328 - Odd Even Linked List 3 | * 4 | * O(n) in-place solution 5 | */ 6 | public class _328 { 7 | public ListNode oddEvenList(ListNode head) { 8 | ListNode odd = head, even = odd == null ? null : odd.next, oddTail = odd; 9 | for (ListNode i = odd, j = even; i != null && j != null; ) 10 | if (i.next == j) { 11 | i.next = j.next; 12 | i = j.next; 13 | if (i != null) oddTail = i; 14 | } else { 15 | j.next = i.next; 16 | j = i.next; 17 | } 18 | if (oddTail != null) oddTail.next = even; 19 | return odd; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/_338.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 338 - Counting Bits 3 | * 4 | * A simple counting problem. 5 | */ 6 | public class _338 { 7 | public int[] countBits(int num) { 8 | int[] f = new int[num + 1]; 9 | for (int i=1; i<=num; i++) f[i] = f[i >> 1] + (i & 1); 10 | return f; 11 | } 12 | } -------------------------------------------------------------------------------- /src/_339.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | /** 4 | * LeetCode 339 - Nested List Weight Sum 5 | *

6 | * DFS 7 | */ 8 | public class _339 { 9 | private int dfs(int weight, NestedInteger nested) { 10 | if (nested.isInteger()) return weight * nested.getInteger(); 11 | else { 12 | int sum = 0; 13 | for (NestedInteger i : nested.getList()) sum += dfs(weight + 1, i); 14 | return sum; 15 | } 16 | } 17 | 18 | public int depthSum(List nestedList) { 19 | int sum = 0; 20 | for (NestedInteger nested : nestedList) sum += dfs(1, nested); 21 | return sum; 22 | } 23 | } -------------------------------------------------------------------------------- /src/_340_2.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 340 - Longest Substring with At Most K Distinct Characters 3 | * 4 | * O(n) sliding window 5 | */ 6 | public class _340_2 { 7 | public int lengthOfLongestSubstringKDistinct(String s, int k) { 8 | int max = 0, distinct = 0; 9 | int[] cnt = new int[128]; 10 | for (int l = 0, r = 0; r < s.length(); r++) { 11 | if (cnt[s.charAt(r)]++ == 0) distinct++; 12 | while (distinct > k) 13 | if (--cnt[s.charAt(l++)] == 0) distinct--; 14 | max = Math.max(max, r - l + 1); 15 | } 16 | return max; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/_342.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 342 - Power of Four 3 | * 4 | * Bit Manipulation 5 | * Basically, if a number is power of four, it is firstly a power of two, and then its only one bit can only appear at even positions. 6 | * 7 | * So, 0xAAAAAAAA is the mask of all banned positions, 8 | * and 0x55555555 is the mask of all feasible positions. 9 | */ 10 | public class _342 { 11 | public boolean isPowerOfFour(int num) { 12 | return num > 0 && (num & (num - 1)) == 0 && (num & 0xAAAAAAAA) == 0; 13 | } 14 | } -------------------------------------------------------------------------------- /src/_344.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 344 - Reverse String 3 | * 4 | * A boring problem 5 | */ 6 | public class _344 { 7 | public String reverseString(String s) { 8 | return new StringBuilder(s).reverse().toString(); 9 | } 10 | } -------------------------------------------------------------------------------- /src/_345.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 345 - Reverse Vowels of a String 3 | * 4 | * Two pointers technique 5 | */ 6 | public class _345 { 7 | boolean isVowel(char ch) { 8 | if (ch >= 'A' && ch <= 'Z') ch = (char)(ch + 'a' - 'A'); 9 | return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'; 10 | } 11 | 12 | public String reverseVowels(String s) { 13 | char[] ch = s.toCharArray(); 14 | for (int i=0, j=s.length()-1; i= 0 && !isVowel(ch[j])) j--; 16 | if (isVowel(ch[i]) && i < j) { 17 | char tmp = ch[i]; ch[i] = ch[j]; ch[j] = tmp; 18 | j--; 19 | } 20 | } 21 | return String.valueOf(ch); 22 | } 23 | } -------------------------------------------------------------------------------- /src/_346.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Queue; 3 | 4 | /** 5 | * LeetCode 346 - Moving Average from Data Stream 6 | *

7 | * Sliding window 8 | */ 9 | public class _346 { 10 | 11 | Queue queue; 12 | int size; 13 | long sum; 14 | 15 | /** 16 | * Initialize your data structure here. 17 | */ 18 | public _346(int size) { 19 | this.size = size; 20 | queue = new ArrayDeque<>(); 21 | sum = 0; 22 | } 23 | 24 | public double next(int val) { 25 | if (queue.size() >= size) sum -= queue.poll(); 26 | queue.add(val); 27 | sum += val; 28 | return (double) sum / queue.size(); 29 | } 30 | } -------------------------------------------------------------------------------- /src/_349.java: -------------------------------------------------------------------------------- 1 | import java.util.Set; 2 | import java.util.stream.Collectors; 3 | import java.util.stream.IntStream; 4 | 5 | /** 6 | * LeetCode 349 - Intersection of Two Arrays 7 | * 8 | * Easy problem... 9 | */ 10 | public class _349 { 11 | 12 | public int[] intersection(int[] nums1, int[] nums2) { 13 | Set set = IntStream.of(nums1).boxed().collect(Collectors.toSet()); 14 | return IntStream.of(nums2).filter(u -> set.contains(u)).distinct().toArray(); 15 | } 16 | } -------------------------------------------------------------------------------- /src/_354.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 354 - Russian Doll Envelopes 5 | * 6 | * O(n^2) DP 7 | * Longest Path in a DAG 8 | */ 9 | public class _354 { 10 | 11 | static int[] f; 12 | 13 | private int F(int u, int[][] g) { 14 | if (f[u] > 0) return f[u]; 15 | f[u] = 1; 16 | for (int v = 0; v < g.length; v++) 17 | if (g[u][0] < g[v][0] && g[u][1] < g[v][1]) f[u] = Math.max(f[u], 1 + F(v, g)); 18 | return f[u]; 19 | } 20 | 21 | public int maxEnvelopes(int[][] g) { 22 | f = new int[g.length]; 23 | return IntStream.range(0, g.length).map(i -> F(i, g)).max().orElse(0); 24 | } 25 | } -------------------------------------------------------------------------------- /src/_365.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 365 - Water and Jug Problem 3 | *

4 | * Math 5 | *

6 | * Be care to the case where x, y, or z is equal to zero. 7 | * Also pay attention to the statement "one or both buckets by the end". 8 | */ 9 | public class _365 { 10 | private int gcd(int a, int b) { 11 | return b == 0 ? a : gcd(b, a % b); 12 | } 13 | 14 | public boolean canMeasureWater(int x, int y, int z) { 15 | if (z == 0) return true; 16 | if (x == 0) return y == z; 17 | if (y == 0) return x == z; 18 | return (long) x + y >= z && z % gcd(x, y) == 0; 19 | } 20 | } -------------------------------------------------------------------------------- /src/_366.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 366 - Find Leaves of Binary Tree 6 | *

7 | * Computing Tree Height 8 | */ 9 | public class _366 { 10 | List> ans; 11 | 12 | private int dfs(TreeNode root) { 13 | if (root == null) return -1; 14 | int height = Math.max(dfs(root.left), dfs(root.right)) + 1; 15 | if (ans.size() < height + 1) ans.add(new ArrayList<>()); 16 | ans.get(height).add(root.val); 17 | return height; 18 | } 19 | 20 | public List> findLeaves(TreeNode root) { 21 | ans = new ArrayList<>(); 22 | dfs(root); 23 | return ans; 24 | } 25 | } -------------------------------------------------------------------------------- /src/_367.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 367 - Valid Perfect Square 3 | * 4 | * Binary Search 5 | */ 6 | public class _367 { 7 | public boolean isPerfectSquare(int num) { 8 | long l = 0, r = num; 9 | while (l <= r) { 10 | long mid = (l + r) / 2; 11 | if (mid * mid > num) r = mid - 1; 12 | else if (mid * mid < num) l = mid + 1; 13 | else return true; 14 | } 15 | return false; 16 | } 17 | } -------------------------------------------------------------------------------- /src/_370_2.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 370 Range Addition 5 | * 6 | * O(n) Prefix Trick 7 | */ 8 | public class _370_2 { 9 | 10 | public int[] getModifiedArray(int length, int[][] updates) { 11 | int[] ans = new int[length]; 12 | for (int[] update : updates) { 13 | ans[update[1]] += update[2]; 14 | if (update[0] > 0) ans[update[0] - 1] -= update[2]; 15 | } 16 | for (int i = ans.length - 2; i >= 0; i--) ans[i] += ans[i + 1]; 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /src/_371.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 371 - Sum of Two Integers 3 | * 4 | * Bit Manipulation 5 | * 6 | * Elegant step: (a & b) << 1 computes all the carries. 7 | */ 8 | public class _371 { 9 | public int getSum(int a, int b) { 10 | int withoutCarry = a ^ b; 11 | int carry = a & b; 12 | return carry == 0 ? withoutCarry : getSum(withoutCarry, carry << 1); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/_372.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 372 - Super Pow 3 | *

4 | * Most significant bit -> Least significant bit 5 | */ 6 | public class _372 { 7 | public int superPow(int a, int[] b) { 8 | final int MOD = 1337; 9 | a %= MOD; 10 | int ans = 1; 11 | for (int i = 0; i < b.length; i++) { 12 | for (int tmp = ans, j = 0; j < 9; j++) ans = ans * tmp % MOD; 13 | for (int j = 0; j < b[i]; j++) ans = ans * a % MOD; 14 | } 15 | return ans; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/_372_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 372 - Super Pow 3 | *

4 | * Least significant bit -> most significant bit 5 | */ 6 | public class _372_1 { 7 | public int superPow(int a, int[] b) { 8 | final int MOD = 1337; 9 | int ans = 1; 10 | a %= MOD; 11 | for (int i = b.length - 1; i >= 0; i--) { 12 | for (int j = 0; j < b[i]; j++) ans = ans * a % MOD; 13 | for (int j = 0, aa = a; j < 9; j++) a = a * aa % MOD; 14 | } 15 | return ans; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/_374.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * LeetCode 374 - Guess Number Higher or Lower 5 | * 6 | * Binary Search 7 | */ 8 | public class _374 { 9 | public int guessNumber(int n) { 10 | int left = 1, right = n; 11 | while(left <= right) { 12 | int mid = left + (right - left) / 2; 13 | int cmp = guess(mid); 14 | if (cmp < 0) right = mid - 1; 15 | else if (cmp > 0) left = mid + 1; 16 | else return mid; 17 | } 18 | return -1; // Will never get here 19 | } 20 | 21 | /** 22 | * Dummy... 23 | */ 24 | private int guess(int x) { 25 | return -1; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/_375.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 375 - Guess Number Higher or Lower II 3 | *

4 | * O(n^3) DP 5 | */ 6 | public class _375 { 7 | public int getMoneyAmount(int n) { 8 | int[][] f = new int[n + 2][n + 2]; 9 | // dp on f[1..n][1..n] 10 | // but will refer to f[X][0] and f[n+1][X] 11 | for (int d = 1; d < n; d++) 12 | for (int i = 1; i <= n; i++) { 13 | int j = i + d; 14 | if (j > n) break; 15 | f[i][j] = Integer.MAX_VALUE; 16 | for (int k = i; k <= j; k++) 17 | f[i][j] = Math.min(f[i][j], k + Math.max(f[i][k - 1], f[k + 1][j])); 18 | } 19 | return f[1][n]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/_376_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 376 - Wiggle Subsequence 3 | * 4 | * O(n) In-place Maximal/Minimal Finding 5 | */ 6 | public class _376_1 { 7 | public int wiggleMaxLength(int[] nums) { 8 | int len = 0, i = 0, j = 0, ans = 0; 9 | for (i = 0; i < nums.length; i = j + 1) { 10 | nums[len++] = nums[i]; 11 | for (j = i; j + 1 < nums.length && nums[i] == nums[j + 1]; j++) ; 12 | } 13 | for (i = 0; i < len; i++) { 14 | int left = i - 1 < 0 ? 0 : Integer.compare(nums[i], nums[i - 1]); 15 | int right = i + 1 >= len ? 0 : Integer.compare(nums[i], nums[i + 1]); 16 | if (left * right >= 0) ans++; 17 | } 18 | return ans; 19 | } 20 | } -------------------------------------------------------------------------------- /src/_377.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 377 - Combination Sum IV 3 | * 4 | * 5 | * DP 6 | * f[i] means the number of different combinations that add up to i 7 | */ 8 | public class _377 { 9 | public int combinationSum4(int[] nums, int target) { 10 | int[] f = new int[target + 1]; 11 | f[0] = 1; 12 | for (int i = 1; i <= target; i++) 13 | for (int num : nums) 14 | if (num <= i) f[i] += f[i - num]; 15 | return f[target]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/_383.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 383 - Ransom Note 5 | * 6 | * Simple solution 7 | */ 8 | public class _383 { 9 | public boolean canConstruct(String ransomNote, String magazine) { 10 | int[] cnt = new int[128]; 11 | for (int i = 0; i < magazine.length(); i++) cnt[magazine.charAt(i)]++; 12 | for (int i = 0; i < ransomNote.length(); i++) 13 | if (--cnt[ransomNote.charAt(i)] < 0) return false; 14 | return true; 15 | } 16 | } -------------------------------------------------------------------------------- /src/_386_1.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 386 - Lexicographical Numbers 6 | *

7 | * Recursive Solution 8 | */ 9 | public class _386_1 { 10 | 11 | List ans; 12 | 13 | private void dfs(int current, int n) { 14 | if (current > n) return; 15 | ans.add(current); 16 | for (int i = 0; i <= 9; i++) dfs(current * 10 + i, n); 17 | } 18 | 19 | public List lexicalOrder(int n) { 20 | ans = new ArrayList<>(n); 21 | for (int i = 1; i <= 9; i++) dfs(i, n); 22 | return ans; 23 | } 24 | } -------------------------------------------------------------------------------- /src/_387.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 387 - First Unique Character in a String 3 | * 4 | * Brute-force 5 | */ 6 | public class _387 { 7 | public int firstUniqChar(String s) { 8 | int[] cnt = new int[128]; 9 | for (char ch : s.toCharArray()) cnt[ch]++; 10 | for (int i = 0; i < s.length(); i++) 11 | if (cnt[s.charAt(i)] == 1) return i; 12 | return -1; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/_389.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 389 - Find the Difference 3 | * 4 | * Easy problem 5 | */ 6 | public class _389 { 7 | public char findTheDifference(String s, String t) { 8 | int[] cnt = new int[128]; 9 | for (char ch : t.toCharArray()) cnt[ch]++; 10 | for (char ch : s.toCharArray()) cnt[ch]--; 11 | for (char ch = 0; ch < 128; ch++) if (cnt[ch] > 0) return ch; 12 | return 0; 13 | } 14 | } -------------------------------------------------------------------------------- /src/_390.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Elimination Game 3 | * 4 | * Math - O(log n) 5 | */ 6 | public class _390 { 7 | 8 | private int f(int n, int dir) { 9 | if (n == 1) return 1; 10 | if (n % 2 == 0) { 11 | if (dir == 0) return 2 * f(n / 2, 1 - dir); 12 | else return 2 * f(n / 2, 1 - dir) - 1; 13 | } else { 14 | return 2 * f(n / 2, 1 - dir); 15 | } 16 | } 17 | 18 | public int lastRemaining(int n) { 19 | return f(n, 0); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/_392.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 392 - Is Subsequence 3 | * 4 | * Simple solution 5 | */ 6 | public class _392 { 7 | public boolean isSubsequence(String s, String t) { 8 | int i = 0, j = 0; 9 | while (i < s.length() && j < t.length()) 10 | if (s.charAt(i) == t.charAt(j)) { 11 | i++; 12 | j++; 13 | } else j++; 14 | return i == s.length(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/_393.java: -------------------------------------------------------------------------------- 1 | public class _393 { 2 | public boolean validUtf8(int[] data) { 3 | for (int i = 0; i < data.length; ) { 4 | int prefixOne = 0; 5 | for (int bit = 7; bit >= 0; bit--) 6 | if ((data[i] & (1 << bit)) != 0) prefixOne++; 7 | else break; 8 | if (prefixOne == 1 || prefixOne > 4 || i + prefixOne > data.length) return false; 9 | if (prefixOne == 0) i++; 10 | else { 11 | for (int j = i + 1; j < i + prefixOne; j++) 12 | if ((data[j] >> 6) != 0b10) return false; 13 | i += prefixOne; 14 | } 15 | } 16 | return true; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_396.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 396 - Rotate Function 3 | * 4 | * Just pay attention to the difference between two consecutive windows 5 | */ 6 | public class _396 { 7 | public int maxRotateFunction(int[] A) { 8 | long ans = Long.MIN_VALUE, sum = 0, current = 0; 9 | for (int i = 0; i < A.length; i++) { 10 | sum += A[i]; 11 | current += i * A[i]; 12 | } 13 | for (int i = 0; i < A.length; i++) { 14 | current = current - sum + A.length * A[i]; 15 | ans = Math.max(ans, current); 16 | } 17 | return (int) ans; 18 | } 19 | } -------------------------------------------------------------------------------- /src/_398_1.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | /** 4 | * LeetCode 398 - Random Pick Index 5 | * 6 | * O(1) build time 7 | * O(n) query time using reservoir sampling 8 | */ 9 | public class _398_1 { 10 | Random rand; 11 | int[] nums; 12 | 13 | public _398_1(int[] nums) { 14 | rand = new Random(); 15 | this.nums = nums; 16 | } 17 | 18 | public int pick(int target) { 19 | int res = -1, cnt = 1; 20 | for (int i = 0; i < nums.length; i++) 21 | if (nums[i] == target && rand.nextInt(cnt++) == 0) res = i; 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /src/_398_2.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | /** 4 | * LeetCode 398 - Random Pick Index 5 | *

6 | * O(1) build time 7 | * O(n) expected query time using random sampling 8 | * It turns out that the expected runtime of this method is even faster than reservoir sampling. 9 | */ 10 | public class _398_2 { 11 | Random rand; 12 | int[] nums; 13 | 14 | public _398_2(int[] nums) { 15 | rand = new Random(); 16 | this.nums = nums; 17 | } 18 | 19 | public int pick(int target) { 20 | int i = rand.nextInt(nums.length); 21 | while (nums[i] != target) i = rand.nextInt(nums.length); 22 | return i; 23 | } 24 | } -------------------------------------------------------------------------------- /src/_400.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 400 - Nth Digit 3 | * 4 | * Counting + Bisect 5 | */ 6 | public class _400 { 7 | private long f(int x) { 8 | long ans = 0, pow = 1, len = 1; 9 | while (x >= 10 * pow) { 10 | ans += 9 * pow * len; 11 | pow *= 10; 12 | len++; 13 | } 14 | return ans + len * (x - pow + 1); 15 | } 16 | 17 | public int findNthDigit(int n) { 18 | int left = 0, right = n; 19 | while (left + 1 < right) { 20 | int mid = (left + right) / 2; 21 | if (f(mid) < n) left = mid; 22 | else right = mid; 23 | } 24 | return ("" + (left + 1)).charAt((int) (n - f(left) - 1)) - '0'; 25 | } 26 | } -------------------------------------------------------------------------------- /src/_401.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 401 - Binary Watch 6 | * 7 | * Brute-force 8 | */ 9 | public class _401 { 10 | public List readBinaryWatch(int num) { 11 | List ans = new ArrayList<>(); 12 | for (int bit = 0; bit < (1 << 10); bit++) { 13 | if (Integer.bitCount(bit) != num) continue; 14 | int hour = bit >> 6, min = bit & 0b111111; 15 | if (hour < 12 && min < 60) ans.add(String.format("%d:%02d", hour, min)); 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /src/_401_1.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 401 Binary Watch 6 | * 7 | * Brute-force 8 | */ 9 | public class _401_1 { 10 | public List readBinaryWatch(int num) { 11 | List ans = new ArrayList<>(); 12 | for (int hour = 0; hour < 12; hour++) 13 | for (int min = 0; min < 60; min++) 14 | if (Integer.bitCount(hour) + Integer.bitCount(min) == num) 15 | ans.add(String.format("%d:%02d", hour, min)); 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_404.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 404 - Sum of Left Leaves 3 | *

4 | * Simple DFS approach. 5 | * Note: A single node is NOT considered as a left leaf. 6 | */ 7 | public class _404 { 8 | public int sumOfLeftLeaves(TreeNode root) { 9 | int ans = 0; 10 | if (root != null) { 11 | ans += sumOfLeftLeaves(root.left); 12 | ans += sumOfLeftLeaves(root.right); 13 | if (root.left != null && root.left.left == null && root.left.right == null) ans += root.left.val; 14 | } 15 | return ans; 16 | } 17 | } -------------------------------------------------------------------------------- /src/_405.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 405 - Convert a Number to Hexadecimal 3 | *

4 | * Bit manipulation 5 | *

6 | * Pay extreme attention to the difference between 7 | * num >> k and num >>> k, when num is positive and negative. 8 | *

9 | * >> will pad the sign bit. 10 | * >>> will always pad zeros. 11 | */ 12 | public class _405 { 13 | public String toHex(int num) { 14 | if (num == 0) return "0"; 15 | else { 16 | StringBuilder builder = new StringBuilder(); 17 | while (num != 0) { 18 | builder.append("0123456789abcdef".charAt(num & 0b1111)); 19 | num >>>= 4; 20 | } 21 | return builder.reverse().toString(); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /src/_408.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 408 - Valid Word Abbreviation 3 | * 4 | * Brute-force 5 | */ 6 | public class _408 { 7 | public boolean validWordAbbreviation(String word, String abbr) { 8 | int i = 0, j = 0; 9 | while (i < word.length() && j < abbr.length()) 10 | if (Character.isDigit(abbr.charAt(j))) { 11 | if (abbr.charAt(j) == '0') return false; 12 | int num = 0; 13 | while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) num = num * 10 + abbr.charAt(j++) - '0'; 14 | i += num; 15 | } else { 16 | if (word.charAt(i++) != abbr.charAt(j++)) return false; 17 | } 18 | return i == word.length() && j == abbr.length(); 19 | } 20 | } -------------------------------------------------------------------------------- /src/_409.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 409 - Longest Palindrome 3 | * 4 | * Counting 5 | */ 6 | public class _409 { 7 | public int longestPalindrome(String s) { 8 | int[] cnt = new int[128]; 9 | for (char ch : s.toCharArray()) cnt[ch]++; 10 | int ans = 0, odd = 0; 11 | for (int i : cnt) { 12 | if (i % 2 == 1) odd++; 13 | ans += i / 2 * 2; 14 | } 15 | return ans + Math.min(odd, 1); 16 | } 17 | } -------------------------------------------------------------------------------- /src/_412.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 412 Fizz Buzz 6 | * 7 | * Brute-force 8 | */ 9 | public class _412 { 10 | public List fizzBuzz(int n) { 11 | List ans = new ArrayList<>(); 12 | for (int i=1; i<=n; i++) 13 | if (i % 15 == 0) ans.add("FizzBuzz"); 14 | else if (i % 3 == 0) ans.add("Fizz"); 15 | else if (i % 5 == 0) ans.add("Buzz"); 16 | else ans.add(String.format("%d", i)); 17 | return ans; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/_413_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 413 - Arithmetic Slices 3 | *

4 | * An in-place solution 5 | */ 6 | public class _413_1 { 7 | public int numberOfArithmeticSlices(int[] A) { 8 | int ans = 0, cnt = 0; 9 | Integer diff = null; 10 | for (int i = 1; i < A.length; i++) 11 | if (A[i] - A[i - 1] == diff) cnt++; 12 | else { 13 | ans += (cnt + 1) * cnt / 2 - cnt; 14 | cnt = 1; 15 | diff = A[i] - A[i - 1]; 16 | } 17 | return ans + (cnt + 1) * cnt / 2 - cnt; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/_416.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 416 - Partition Equal Subset Sum 5 | *

6 | * 0/1-Knapsack 7 | */ 8 | public class _416 { 9 | public boolean canPartition(int[] nums) { 10 | int sum = IntStream.of(nums).sum(); 11 | if (sum % 2 != 0) return false; 12 | boolean[] f = new boolean[sum / 2 + 1]; 13 | f[0] = true; 14 | for (int i : nums) 15 | for (int j = sum / 2; j - i >= 0; j--) 16 | f[j] = f[j] || f[j - i]; 17 | return f[sum / 2]; 18 | } 19 | } -------------------------------------------------------------------------------- /src/_434.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 434 - Number of Segments in a String 3 | *

4 | * See the following from Java Doc. 5 | * If the expression does not match any part of the input then the resulting array has just one element, namely this string. 6 | */ 7 | public class _434 { 8 | public int countSegments(String s) { 9 | s = s.trim(); 10 | if (s.length() <= 0) return 0; 11 | else return s.split("[ ]+").length; 12 | } 13 | } -------------------------------------------------------------------------------- /src/_436.java: -------------------------------------------------------------------------------- 1 | import java.util.TreeMap; 2 | 3 | /** 4 | * LeetCode 436 - Find Right Interval 5 | *

6 | * TreeMap 7 | */ 8 | public class _436 { 9 | public int[] findRightInterval(Interval[] intervals) { 10 | int[] ans = new int[intervals.length]; 11 | TreeMap tree = new TreeMap<>(); 12 | for (int i = 0; i < intervals.length; i++) tree.put(intervals[i].start, i); 13 | for (int i = 0; i < intervals.length; i++) { 14 | Integer key = tree.ceilingKey(intervals[i].end); 15 | if (key == null) ans[i] = -1; 16 | else ans[i] = tree.get(key); 17 | } 18 | return ans; 19 | } 20 | } -------------------------------------------------------------------------------- /src/_437_2.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 437 - Path Sum III 3 | *

4 | * Two-dfs approach 5 | */ 6 | public class _437_2 { 7 | int ans = 0; 8 | 9 | private void dfs2(TreeNode root, int sum) { 10 | if (root == null) return; 11 | if (sum - root.val == 0) ans++; 12 | dfs2(root.left, sum - root.val); 13 | dfs2(root.right, sum - root.val); 14 | } 15 | 16 | private void dfs1(TreeNode root, int sum) { 17 | if (root == null) return; 18 | dfs2(root, sum); 19 | dfs1(root.left, sum); 20 | dfs1(root.right, sum); 21 | } 22 | 23 | public int pathSum(TreeNode root, int sum) { 24 | ans = 0; 25 | dfs1(root, sum); 26 | return ans; 27 | } 28 | } -------------------------------------------------------------------------------- /src/_439.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 439 - Ternary Expression Parser 3 | *

4 | * Top-down approach 5 | */ 6 | public class _439 { 7 | 8 | int ptr; 9 | String exp; 10 | 11 | private char dfs() { 12 | char val = exp.charAt(ptr++); 13 | if (ptr >= exp.length() || exp.charAt(ptr) != '?') return val; 14 | 15 | ptr++; // skip ? 16 | char trueClause = dfs(); 17 | ptr++; // skip : 18 | char falseCluse = dfs(); 19 | return val == 'T' ? trueClause : falseCluse; 20 | } 21 | 22 | public String parseTernary(String expression) { 23 | exp = expression; 24 | ptr = 0; 25 | return "" + dfs(); 26 | } 27 | } -------------------------------------------------------------------------------- /src/_44.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 44 - Wildcard Matching 3 | * 4 | * O(nm) dp 5 | */ 6 | public class _44 { 7 | public boolean isMatch(String s, String p) { 8 | int r = s.length(), c = p.length(); 9 | boolean[][] f = new boolean[r + 1][c + 1]; 10 | 11 | f[0][0] = true; 12 | for (int j=1; j<=c; j++) f[0][j] = f[0][j - 1] && p.charAt(j - 1) == '*'; 13 | 14 | for (int i=1; i<=r; i++) 15 | for (int j=1; j<=c; j++) 16 | if (p.charAt(j - 1) == '*') f[i][j] = f[i - 1][j] || f[i][j - 1]; 17 | else f[i][j] = f[i - 1][j - 1] && (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1)); 18 | 19 | return f[r][c]; 20 | } 21 | } -------------------------------------------------------------------------------- /src/_441.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 441 - Arranging Coins 3 | *

4 | * O(1) Brute-force 5 | */ 6 | public class _441 { 7 | public int arrangeCoins(int n) { 8 | for (long k = (long) Math.sqrt(2.0 * n) + 5; k >= 0; k--) 9 | if (k * (k + 1) / 2 <= n) return (int) k; 10 | throw new RuntimeException("Failed..."); 11 | } 12 | } -------------------------------------------------------------------------------- /src/_443.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 443 - String Compression 3 | 4 | This problem is indeed broken. 5 | For instance, how to expand the compressed string "c22"? 6 | The decryption is not unique... 7 | """ 8 | 9 | 10 | class Solution: 11 | def compress(self, chars): 12 | """ 13 | :type chars: List[str] 14 | :rtype: int 15 | """ 16 | size = 0 17 | i = 0 18 | while i < len(chars): 19 | j = next(j for j in range(i, len(chars) + 1) if j >= len(chars) or chars[i] != chars[j]) 20 | cnt = j - i 21 | s = chars[i] if cnt == 1 else '{ch}{cnt}'.format(ch=chars[i], cnt=cnt) 22 | chars[size:size + len(s)] = s 23 | size += len(s) 24 | i = j 25 | return size 26 | -------------------------------------------------------------------------------- /src/_452.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 452 - Minimum Number of Arrows to Burst Balloons 5 | * 6 | * O(n log n) greedy algorithm via sweepline 7 | */ 8 | public class _452 { 9 | 10 | public int findMinArrowShots(int[][] a) { 11 | if (a == null || a.length <= 0) return 0; 12 | Arrays.sort(a, (u, v) -> Integer.compare(u[1], v[1])); // sort by end point 13 | int ans = 1, end = a[0][1]; 14 | for (int i = 1; i < a.length; i++) { 15 | if (a[i][0] <= end) continue; // using the arrow at coordinate end 16 | else { 17 | ans++; 18 | end = a[i][1]; 19 | } 20 | } 21 | return ans; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/_453.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 453 - Minimum Moves to Equal Array Elements 3 | *

4 | * Incrementing n - 1 elements by 1 is equivalent to decrementing the remaining element by 1. 5 | */ 6 | public class _453 { 7 | public int minMoves(int[] nums) { 8 | if (nums == null || nums.length <= 1) return 0; 9 | int ans = 0, min = Integer.MAX_VALUE; 10 | for (int i : nums) min = Math.min(min, i); 11 | for (int i : nums) ans += i - min; 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /src/_454.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * LeetCode 454 - 4Sum II 6 | *

7 | * O(n^2) solution using HashMap 8 | */ 9 | public class _454 { 10 | public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { 11 | int ans = 0; 12 | Map map = new HashMap<>(); 13 | for (int a : A) 14 | for (int b : B) 15 | map.put(a + b, map.getOrDefault(a + b, 0) + 1); 16 | for (int c : C) 17 | for (int d : D) 18 | ans += map.getOrDefault(-c - d, 0); 19 | return ans; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/_455.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 455 - Assign Cookies 5 | * 6 | * Greedy 7 | */ 8 | public class _455 { 9 | public int findContentChildren(int[] g, int[] s) { 10 | int ans = 0; 11 | Arrays.sort(g); 12 | Arrays.sort(s); 13 | for (int i = 0, j = 0; i < g.length && j < s.length; ) 14 | if (g[i] <= s[j]) { 15 | ans++; 16 | i++; 17 | j++; 18 | } else { 19 | j++; 20 | } 21 | return ans; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/_459_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 459 - Repeated Substring Pattern 3 | *

4 | * 1-Liner 5 | *

6 | * But still has an O(n^2) worst-case runtime. 7 | */ 8 | public class _459_1 { 9 | public boolean repeatedSubstringPattern(String s) { 10 | return s.length() > 0 && (s.substring(1) + s.substring(0, s.length() - 1)).contains(s); 11 | } 12 | } -------------------------------------------------------------------------------- /src/_459_2.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 459 - Repeated Substring Pattern 3 | *

4 | * 1-Liner via Regex 5 | */ 6 | public class _459_2 { 7 | public boolean repeatedSubstringPattern(String s) { 8 | return s.matches("(.+)\\1+"); 9 | } 10 | } -------------------------------------------------------------------------------- /src/_459_3.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 459 - Repeated Substring Pattern 3 | *

4 | * O(n)-time solution via Miller-Rabin 5 | */ 6 | public class _459_3 { 7 | public boolean repeatedSubstringPattern(String s) { 8 | long B = 29, M = 1_000_000_009, target = 0, pow = 1; 9 | for (int i = 0; i < s.length(); i++) target = (target * B + s.charAt(i) - 'a' + 1) % M; 10 | for (int i = 0; i < s.length() - 1; i++) pow = pow * B % M; 11 | 12 | long current = target; 13 | for (int i = 0; i < s.length() - 1; i++) { 14 | int ch = s.charAt(i) - 'a' + 1; 15 | current = ((current - ch * pow % M + M) * B + ch) % M; 16 | if (target == current) return true; 17 | } 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /src/_461.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 461 - Hamming Distance 3 | *

4 | * Brute-force 5 | */ 6 | public class _461 { 7 | public int hammingDistance(int x, int y) { 8 | return Integer.bitCount(x ^ y); 9 | } 10 | } -------------------------------------------------------------------------------- /src/_476.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 476 - Number Complement 3 | * 4 | * Bit manipulation 5 | */ 6 | public class _476 { 7 | public int findComplement(int num) { 8 | return num ^ (Integer.highestOneBit(num) | Integer.highestOneBit(num) - 1); 9 | } 10 | } -------------------------------------------------------------------------------- /src/_477.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 477 - Total Hamming Distance 3 | *

4 | * Bit-by-bit Counting 5 | */ 6 | public class _477 { 7 | public int totalHammingDistance(int[] nums) { 8 | int ans = 0; 9 | for (int i = 0; i < 32; i++) { 10 | int a = 0, b = 0; 11 | for (int num : nums) 12 | if (((1 << i) & num) == 0) a++; 13 | else b++; 14 | ans += a * b; 15 | } 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_481.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 481 - Magical String 3 | *

4 | * Use BFS to generate the string 5 | */ 6 | public class _481 { 7 | public int magicalString(int n) { 8 | int[] a = new int[n + 5]; 9 | a[0] = 1; 10 | a[1] = 2; 11 | a[2] = 2; 12 | for (int i = 2, j = 2; j < n; i++) { 13 | int nextValue = 3 - a[j]; 14 | a[++j] = nextValue; 15 | if (a[i] == 2) a[++j] = nextValue; 16 | } 17 | int oneCnt = 0; 18 | for (int i = 0; i < n; i++) 19 | if (a[i] == 1) oneCnt++; 20 | return oneCnt; 21 | } 22 | } -------------------------------------------------------------------------------- /src/_482.java: -------------------------------------------------------------------------------- 1 | import java.util.StringJoiner; 2 | 3 | /** 4 | * LeetCode 482 - License Key Formatting 5 | *

6 | * Short solution 7 | */ 8 | public class _482 { 9 | public String licenseKeyFormatting(String S, int K) { 10 | S = S.replaceAll("-", ""); 11 | StringJoiner joiner = new StringJoiner("-"); 12 | for (int i = S.length() - 1; i >= 0; ) { 13 | StringBuilder builder = new StringBuilder(); 14 | for (int j = i; j > i - K && j >= 0; j--) 15 | builder.append(Character.toUpperCase(S.charAt(j))); 16 | i -= K; 17 | joiner.add(builder.toString()); 18 | } 19 | return new StringBuilder(joiner.toString()).reverse().toString(); 20 | } 21 | } -------------------------------------------------------------------------------- /src/_485.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 485 - Max Consecutive Ones 3 | */ 4 | public class _485 { 5 | 6 | public int findMaxConsecutiveOnes(int[] nums) { 7 | int ans = 0; 8 | for (int i = 0, j = 0; i < nums.length; ) 9 | if (nums[i] == 1) { 10 | for (j = i + 1; j < nums.length && nums[j] == 1; j++) ; 11 | ans = Math.max(ans, j - i); 12 | i = j; 13 | } else { 14 | i++; 15 | } 16 | return ans; 17 | } 18 | 19 | public static void main(String[] args) throws Exception { 20 | _485 sol = new _485(); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/_486_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 486 - Predict the Winner 3 | *

4 | * Shorter DP 5 | */ 6 | public class _486_1 { 7 | 8 | Integer[][] f; 9 | int[] nums; 10 | 11 | private int F(int i, int j, int s) { 12 | if (i == j) return s; 13 | if (f[i][j] != null) return f[i][j]; 14 | f[i][j] = Math.max(s - F(i + 1, j, s - nums[i]), s - F(i, j - 1, s - nums[j])); 15 | return f[i][j]; 16 | } 17 | 18 | public boolean PredictTheWinner(int[] nums) { 19 | f = new Integer[nums.length][nums.length]; 20 | this.nums = nums; 21 | int sum = 0; 22 | for (int num : nums) sum += num; 23 | return F(0, nums.length - 1, sum) >= (sum + 1) / 2; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/_492.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 492 - Construct the Rectangle 3 | *

4 | * Brute-force 5 | */ 6 | public class _492 { 7 | 8 | public int[] constructRectangle(int area) { 9 | int[] ans = null; 10 | for (int i = 1; i * i <= area; i++) { 11 | if (area % i == 0) { 12 | ans = new int[]{area / i, i}; 13 | } 14 | } 15 | return ans; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/_495.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 495 - Teemo Attaching 3 | *

4 | * Sweepline algorithm 5 | */ 6 | public class _495 { 7 | public int findPosisonedDuration(int[] timeSeries, int duration) { 8 | if (timeSeries.length == 0 || duration == 0) return 0; 9 | int ans = duration, end = timeSeries[0] + duration - 1; 10 | for (int i = 1; i < timeSeries.length; i++) { 11 | int left = timeSeries[i], right = left + duration - 1; 12 | ans += Math.min(right - end, duration); 13 | end = right; 14 | } 15 | return ans; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/_500.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.Stream; 2 | 3 | /** 4 | * LeetCode 500 - Keyboard Row 5 | *

6 | * 1-Line solution 7 | */ 8 | public class _500 { 9 | 10 | public String[] findWords(String[] words) { 11 | return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")).toArray(String[]::new); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/_504.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 504 - Base 7 3 | *

4 | * 1-line solution 5 | */ 6 | public class _504 { 7 | 8 | public String convertTo7(int num) { 9 | return Integer.toString(num, 7); 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/_504_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 504 - Base 7 3 | *

4 | * Conventional method 5 | */ 6 | public class _504_1 { 7 | 8 | public String convertTo7(int num) { 9 | if (num == 0) return "0"; 10 | String sign = num < 0 ? "-" : ""; 11 | StringBuilder builder = new StringBuilder(); 12 | num = Math.abs(num); 13 | while (num > 0) { 14 | builder.append("" + (num % 7)); 15 | num /= 7; 16 | } 17 | return sign + builder.reverse().toString(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/_507.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 507 - Perfect Number 3 | *

4 | * An O(sqrt(n))-time solution is not difficult to come up with. 5 | * Just need to be careful to the following corner cases: 6 | * 1) n <= 0, 7 | * 2) n is a perfect square. 8 | */ 9 | public class _507 { 10 | public boolean checkPerfectNumber(int num) { 11 | if (num <= 1) return false; 12 | int ans = 0; 13 | for (long i = 1; i * i <= num; i++) 14 | if (num % i == 0) { 15 | if (i < num) ans += i; 16 | if (i != num / i && num / i < num) ans += num / i; 17 | } 18 | return ans == num; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/_513.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 513 - Find Bottom Left Tree Value 3 | *

4 | * DFS approach 5 | */ 6 | public class _513 { 7 | 8 | int maxD, ans; 9 | 10 | public int findLeftMostNode(TreeNode root) { 11 | ans = maxD = -1; 12 | dfs(root, 0); 13 | return ans; 14 | } 15 | 16 | private void dfs(TreeNode root, int d) { 17 | if (root == null) return; 18 | if (d > maxD) { 19 | maxD = d; 20 | ans = root.val; 21 | } 22 | dfs(root.left, d + 1); 23 | dfs(root.right, d + 1); 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /src/_515.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 515 - Find Largest Value in Each Tree Row 6 | *

7 | * DFS approach 8 | */ 9 | public class _515 { 10 | 11 | public int[] findValueMostElement(TreeNode root) { 12 | List list = new ArrayList<>(); 13 | dfs(root, 0, list); 14 | return list.stream().mapToInt(u -> u).toArray(); 15 | } 16 | 17 | private void dfs(TreeNode root, int d, List list) { 18 | if (root == null) return; 19 | if (d >= list.size()) list.add(root.val); 20 | else list.set(d, Math.max(list.get(d), root.val)); 21 | dfs(root.left, d + 1, list); 22 | dfs(root.right, d + 1, list); 23 | } 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/_516.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | 4 | /** 5 | * LeetCode 516 - Longest Palindromic Subsequence 6 | *

7 | * O(n^2) DP 8 | */ 9 | public class _516 { 10 | Integer[][] f; 11 | 12 | private int F(int i, int j, String s) { 13 | if (i > j) return 0; 14 | if (f[i][j] != null) return f[i][j]; 15 | int ans = Math.max(F(i + 1, j, s), F(i, j - 1, s)); 16 | if (s.charAt(i) == s.charAt(j)) ans = Math.max(ans, F(i + 1, j - 1, s) + (i == j ? 1 : 2)); 17 | f[i][j] = ans; 18 | return ans; 19 | } 20 | 21 | public int longestPalindromeSubseq(String s) { 22 | int n = s.length(); 23 | f = new Integer[n][n]; 24 | return F(0, s.length() - 1, s); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/_520.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 520 - Detect Capital 3 | *

4 | * 1-Line solution 5 | */ 6 | public class _520 { 7 | public boolean detectCapitalUse(String word) { 8 | return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+"); 9 | } 10 | } 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/_521.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 521 - Longest Uncommon Subsequence I 3 | *

4 | * A really interesting problem that best fits April 1. 5 | */ 6 | public class _521 { 7 | public int findLUSlength(String a, String b) { 8 | return a.equals(b) ? -1 : Math.max(a.length(), b.length()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/_524.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | import static java.util.Comparator.comparingInt; 4 | 5 | /** 6 | * LeetCode 524 - Longest Word in Dictionary through Deleting 7 | *

8 | * We can greedily test whether a string is a subsequence of another. 9 | */ 10 | public class _524 { 11 | 12 | public String findLongestWord(String s, List d) { 13 | return d.stream().filter(dd -> { 14 | int i = 0, j = 0; 15 | while (i < s.length() && j < dd.length()) { 16 | if (s.charAt(i) == dd.charAt(j)) j++; 17 | i++; 18 | } 19 | return j >= dd.length(); 20 | }).min(comparingInt((String u) -> u.length()).reversed().thenComparing(String::compareTo)).orElse(""); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/_526.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 526 - Beautiful Arrangement 3 | *

4 | * Permutation Generator 5 | */ 6 | public class _526 { 7 | 8 | private int dfs(int t, int N, boolean[] visited) { 9 | if (t > N) return 1; 10 | int ans = 0; 11 | for (int i = 1; i <= N; i++) 12 | if (!visited[i] && (i % t == 0 || t % i == 0)) { 13 | visited[i] = true; 14 | ans += dfs(t + 1, N, visited); 15 | visited[i] = false; 16 | } 17 | return ans; 18 | } 19 | 20 | public int countArrangement(int N) { 21 | return dfs(1, N, new boolean[20]); 22 | } 23 | } 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/_530.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 530 - Minimum Absolute Difference in BST 3 | *

4 | * DFS approach 5 | */ 6 | public class _530 { 7 | 8 | long previous; 9 | long minDiff; 10 | 11 | private void dfs(TreeNode root) { 12 | if (root == null) return; 13 | dfs(root.left); 14 | minDiff = Math.min(minDiff, root.val - previous); 15 | previous = root.val; 16 | dfs(root.right); 17 | } 18 | 19 | public int getMinimumDifference(TreeNode root) { 20 | previous = Integer.MIN_VALUE; 21 | minDiff = Integer.MAX_VALUE; 22 | dfs(root); 23 | return (int) minDiff; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/_532_1.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 532 - K-diff Pairs in an Array 5 | *

6 | * Two-pointer approach 7 | */ 8 | public class _532_1 { 9 | public int findPairs(int[] nums, int k) { 10 | int ans = 0; 11 | Arrays.sort(nums); 12 | for (int i = 0, j = 0; i < nums.length; i++) { 13 | for (j = Math.max(j, i + 1); j < nums.length && nums[j] - nums[i] < k; j++) ; 14 | if (j < nums.length && nums[j] - nums[i] == k) ans++; 15 | while (i + 1 < nums.length && nums[i] == nums[i + 1]) i++; 16 | } 17 | return ans; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/_537.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.Stream; 2 | 3 | /** 4 | * LeetCode 537 - Complex Number Multiplication 5 | *

6 | * Brute-force 7 | */ 8 | public class _537 { 9 | public String complexNumberMultiply(String a, String b) { 10 | int[] aa = Stream.of(a.split("[+i]")).mapToInt(Integer::parseInt).toArray(); 11 | int[] bb = Stream.of(b.split("[+i]")).mapToInt(Integer::parseInt).toArray(); 12 | return String.format("%d+%di", aa[0] * bb[0] - aa[1] * bb[1], +aa[0] * bb[1] + aa[1] * bb[0]); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/_538.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 538 - Convert BST to Greater Tree 3 | *

4 | * Right-root-left-traversal 5 | */ 6 | public class _538 { 7 | 8 | int sum = 0; 9 | 10 | public TreeNode convertBST(TreeNode root) { 11 | sum = 0; 12 | dfs(root); 13 | return root; 14 | } 15 | 16 | private void dfs(TreeNode root) { 17 | if (root == null) return; 18 | 19 | dfs(root.right); 20 | 21 | int tmpVal = root.val; 22 | root.val += sum; 23 | sum += tmpVal; 24 | 25 | dfs(root.left); 26 | } 27 | 28 | public static void main(String[] args) { 29 | _538 sol = new _538(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/_541.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 541 - Reverse String II 3 | *

4 | * Brute-force 5 | */ 6 | public class _541 { 7 | public String reverseStr(String s, int k) { 8 | StringBuilder builder = new StringBuilder(); 9 | for (int i = 0; i < s.length(); i += 2 * k) { 10 | builder.append(new StringBuilder(s.substring(i, Math.min(i + k, s.length()))).reverse().toString()); 11 | if (i + k < s.length()) { 12 | builder.append(new StringBuilder(s.substring(i + k, Math.min(s.length(), i + 2 * k)))); 13 | } 14 | } 15 | return builder.toString(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/_544.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 544 - Output Contest Matches 3 | *

4 | * Brute-force 5 | * Just need to understand the problem statement carefully. 6 | */ 7 | public class _544 { 8 | 9 | public String findContestMatch(int n) { 10 | String[] res = new String[n]; 11 | for (int i = 0; i < n; i++) res[i] = "" + (i + 1); 12 | for (; n > 1; n /= 2) 13 | for (int i = 0; i < n / 2; i++) 14 | res[i] = "(" + res[i] + "," + res[n - 1 - i] + ")"; 15 | return res[0]; 16 | } 17 | 18 | public static void main(String[] args) { 19 | _544 sol = new _544(); 20 | System.out.println(sol.findContestMatch(128)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/_551.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 551 - Student Attendance Record I 3 | * 4 | * 1-Liner 5 | */ 6 | public class _551 { 7 | public boolean checkRecord(String s) { 8 | return !s.matches(".*LLL.*|.*A.*A.*"); 9 | } 10 | } -------------------------------------------------------------------------------- /src/_557.java: -------------------------------------------------------------------------------- 1 | import java.util.StringJoiner; 2 | 3 | /** 4 | * LeetCode 557 - Reverse Words in a String III 5 | *

6 | * Brute-force 7 | */ 8 | public class _557 { 9 | 10 | public String reverseWords(String s) { 11 | StringJoiner join = new StringJoiner(" "); 12 | for (String str : s.split(" ")) 13 | join.add(new StringBuilder(str).reverse()); 14 | return join.toString(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/_560.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * LeetCode 560 - Subarray Sum Equals K 6 | *

7 | * Prefix-sum trick 8 | */ 9 | public class _560 { 10 | public int subarraySum(int[] nums, int k) { 11 | int ans = 0, prefix = 0; 12 | Map map = new HashMap<>(); 13 | map.put(0, 1); 14 | for (int num : nums) { 15 | prefix += num; 16 | ans += map.getOrDefault(prefix - k, 0); 17 | map.put(prefix, map.getOrDefault(prefix, 0) + 1); 18 | } 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /src/_561.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 561 - Array Partition I 5 | *

6 | * Greedy algorithm 7 | */ 8 | public class _561 { 9 | public int arrayPairSum(int[] nums) { 10 | int ans = 0; 11 | Arrays.sort(nums); 12 | for (int i = 0; i < nums.length; i += 2) 13 | ans += nums[i]; 14 | return ans; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/_563.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 563 - Binary Tree Tilt 3 | *

4 | * DFS approach 5 | */ 6 | public class _563 { 7 | int ans; 8 | 9 | private int dfs(TreeNode root) { 10 | if (root == null) return 0; 11 | int left = dfs(root.left); 12 | int right = dfs(root.right); 13 | ans += Math.abs(left - right); 14 | return left + right + root.val; 15 | } 16 | 17 | public int findTilt(TreeNode root) { 18 | ans = 0; 19 | dfs(root); 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/_566.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 566 - Reshape the Matrix 3 | *

4 | * Brute-force 5 | */ 6 | public class _566 { 7 | public int[][] matrixReshape(int[][] nums, int r, int c) { 8 | if (nums.length * nums[0].length != r * c) 9 | return nums; 10 | 11 | int[][] res = new int[r][c]; 12 | int ptr = 0; 13 | for (int[] row : nums) 14 | for (int num : row) { 15 | res[ptr / c][ptr % c] = num; 16 | ptr++; 17 | } 18 | 19 | return res; 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /src/_567.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 567 - Permutation in String 5 | *

6 | * Sliding-window 7 | */ 8 | public class _567 { 9 | public boolean checkInclusion(String s1, String s2) { 10 | int[] f = new int[128], g = new int[128]; 11 | for (char ch : s1.toCharArray()) 12 | f[ch]++; 13 | for (int i = 0; i < s2.length(); i++) { 14 | if (i >= s1.length()) 15 | g[s2.charAt(i - s1.length())]--; 16 | g[s2.charAt(i)]++; 17 | if (Arrays.equals(f, g)) return true; 18 | } 19 | return false; 20 | } 21 | } -------------------------------------------------------------------------------- /src/_572.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 572 - Subtree of Another Tree 3 | *

4 | * Brute-force O(n^2) runtime 5 | */ 6 | public class _572 { 7 | private boolean isSame(TreeNode a, TreeNode b) { 8 | if (a == null) 9 | return b == null; 10 | if (b == null) 11 | return a == null; 12 | return a.val == b.val && isSame(a.left, b.left) && isSame(a.right, b.right); 13 | } 14 | 15 | public boolean isSubtree(TreeNode s, TreeNode t) { 16 | if (isSame(s, t)) 17 | return true; 18 | if (s.left != null && isSubtree(s.left, t)) 19 | return true; 20 | if (s.right != null && isSubtree(s.right, t)) 21 | return true; 22 | return false; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/_573.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 573 - Squirrel Simulation 3 | *

4 | * Greedy 5 | */ 6 | public class _573 { 7 | public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) { 8 | int ans = Integer.MAX_VALUE; 9 | int sum = 0; 10 | for (int[] nut : nuts) 11 | sum += 2 * dist(nut, tree); 12 | for (int[] nut : nuts) 13 | ans = Math.min(ans, sum - dist(nut, tree) + dist(nut, squirrel)); 14 | return ans; 15 | } 16 | 17 | private int dist(int[] a, int[] b) { 18 | return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/_575.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 575 - Distribute Candies 5 | *

6 | * Greedy 7 | */ 8 | public class _575 { 9 | public int distributeCandies(int[] candies) { 10 | return Math.min((int) IntStream.of(candies).distinct().count(), candies.length / 2); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/_581.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 581 - Shortest Unsorted Continuous Subarray 5 | */ 6 | public class _581 { 7 | public int findUnsortedSubarray(int[] nums) { 8 | int[] sorted = IntStream.of(nums).sorted().toArray(); 9 | int left = 0, right = nums.length - 1; 10 | while (left <= right) 11 | if (nums[left] == sorted[left]) 12 | left++; 13 | else if (nums[right] == sorted[right]) 14 | right--; 15 | else break; 16 | return Math.max(right - left + 1, 0); 17 | } 18 | } -------------------------------------------------------------------------------- /src/_583.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 583 - Delete Operation for Two Strings 3 | *

4 | * LCS 5 | */ 6 | public class _583 { 7 | public int minDistance(String a, String b) { 8 | int[][] f = new int[a.length() + 1][b.length() + 1]; 9 | for (int i = 1; i <= a.length(); i++) 10 | for (int j = 1; j <= b.length(); j++) { 11 | if (a.charAt(i - 1) == b.charAt(j - 1)) 12 | f[i][j] = f[i - 1][j - 1] + 1; 13 | else 14 | f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); 15 | } 16 | return a.length() + b.length() - 2 * f[a.length()][b.length()]; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_594.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * LeetCode 594 - Longest Harmonious Subsequence 6 | *

7 | * Brute-force via HashMap 8 | */ 9 | public class _594 { 10 | public int findLHS(int[] nums) { 11 | int ans = 0; 12 | Map map = new HashMap<>(); 13 | for (int num : nums) 14 | map.put(num, map.getOrDefault(num, 0) + 1); 15 | for (int num : nums) 16 | if (map.containsKey(num + 1)) 17 | ans = Math.max(ans, map.get(num) + map.get(num + 1)); 18 | return ans; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/_598.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 598 - Range Addition II 3 | *

4 | * An interesting problem... 5 | */ 6 | public class _598 { 7 | public int maxCount(int m, int n, int[][] ops) { 8 | int ans = m * n; 9 | int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; 10 | for (int[] op : ops) { 11 | min1 = Math.min(min1, op[0]); 12 | min2 = Math.min(min2, op[1]); 13 | ans = Math.min(ans, min1 * min2); 14 | } 15 | return ans; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/_605.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 605 - Can Place Flowers 3 | *

4 | * Greedy 5 | */ 6 | public class _605 { 7 | public boolean canPlaceFlowers(int[] flowerbed, int n) { 8 | for (int i = 0; i < flowerbed.length; i++) 9 | if (flowerbed[i] == 0) { 10 | if ((i - 1 < 0 || flowerbed[i - 1] == 0) && (i + 1 >= flowerbed.length || flowerbed[i + 1] == 0)) { 11 | n--; 12 | flowerbed[i] = 1; 13 | } 14 | } 15 | return n <= 0; 16 | } 17 | } -------------------------------------------------------------------------------- /src/_611.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 611 - Valid Triangle Number 5 | *

6 | * Three-sum related problem 7 | */ 8 | public class _611 { 9 | public int triangleNumber(int[] nums) { 10 | int cnt = 0; 11 | Arrays.sort(nums); 12 | for (int k = 2; k < nums.length; k++) { 13 | int i = 0, j = k - 1; 14 | while (i < j) 15 | if (nums[i] + nums[j] > nums[k]) { 16 | cnt += j - i; 17 | j--; 18 | } else { 19 | i++; 20 | } 21 | } 22 | return cnt; 23 | } 24 | } -------------------------------------------------------------------------------- /src/_617.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 617 - Merge Two Binary Trees 3 | *

4 | * DFS approach 5 | */ 6 | public class _617 { 7 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 8 | if (t1 == null) 9 | return t2; 10 | if (t2 == null) 11 | return t1; 12 | TreeNode node = new TreeNode(t1.val + t2.val); 13 | node.left = mergeTrees(t1.left, t2.left); 14 | node.right = mergeTrees(t1.right, t2.right); 15 | return node; 16 | } 17 | } -------------------------------------------------------------------------------- /src/_625.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 625 - Minimum Factorization 3 | *

4 | * Greedy solution 5 | *

6 | * 1. Larger factors will make shorter results. 7 | * 2. Larger factors will force the remaining part smaller. 8 | */ 9 | public class _625 { 10 | public int smallestFactorization(int a) { 11 | if (a == 1) 12 | return 1; 13 | long res = 0, pow10 = 1; 14 | for (int i = 9; i >= 2; i--) { 15 | while (a % i == 0) { 16 | res += i * pow10; 17 | a /= i; 18 | pow10 *= 10; 19 | } 20 | } 21 | return a > 1 || res > Integer.MAX_VALUE ? 0 : (int) res; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/_628.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 628 - Maximum Product of Three Numbers 5 | *

6 | * It is not difficult to prove the largest product must be the product of a prefix and a suffix. 7 | */ 8 | public class _628 { 9 | public int maximumProduct(int[] nums) { 10 | Arrays.sort(nums); 11 | int ans = Integer.MIN_VALUE; 12 | int n = nums.length; 13 | ans = Math.max(ans, nums[0] * nums[1] * nums[2]); 14 | ans = Math.max(ans, nums[0] * nums[1] * nums[n - 1]); 15 | ans = Math.max(ans, nums[0] * nums[n - 2] * nums[n - 1]); 16 | ans = Math.max(ans, nums[n - 3] * nums[n - 2] * nums[n - 1]); 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /src/_630.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Comparator; 3 | import java.util.PriorityQueue; 4 | import java.util.Queue; 5 | 6 | /** 7 | * LeetCode 630 - Course Schedule III 8 | *

9 | * Sweep line + greedy 10 | */ 11 | public class _630 { 12 | public int scheduleCourse(int[][] courses) { 13 | Queue queue = new PriorityQueue<>(Comparator.reverseOrder()); 14 | Arrays.sort(courses, Comparator.comparingInt(u -> u[1])); 15 | int time = 0; 16 | for (int[] course : courses) { 17 | time += course[0]; 18 | queue.add(course[0]); 19 | if (time > course[1]) 20 | time -= queue.poll(); 21 | } 22 | return queue.size(); 23 | } 24 | } -------------------------------------------------------------------------------- /src/_633.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 633 - Sum of Square Numbers 3 | *

4 | * Just be careful of integer overflows 5 | */ 6 | public class _633 { 7 | public boolean judgeSquareSum(int c) { 8 | for (int i = 0; (long) i * i <= c; i++) 9 | if (isSquare(c - i * i)) 10 | return true; 11 | return false; 12 | } 13 | 14 | private boolean isSquare(int x) { 15 | long sqrt = (long) Math.sqrt(x); 16 | return sqrt * sqrt == x || (sqrt - 1) * (sqrt - 1) == x || (sqrt + 1) * (sqrt + 1) == x; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_633_1.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | /** 5 | * LeetCode 633 - Sum of Square Numbers 6 | *

7 | * Although using more space, this is still an intersting solution... 8 | */ 9 | public class _633_1 { 10 | public boolean judgeSquareSum(int c) { 11 | Set squares = new HashSet<>(); 12 | for (int i = 0; (long) i * i <= Integer.MAX_VALUE; i++) 13 | squares.add(i * i); 14 | for (int i = 0; (long) i * i <= c; i++) 15 | if (squares.contains(c - i * i)) 16 | return true; 17 | return false; 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /src/_634.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 634 - Find the Derangement of an Array 3 | *

4 | * Combinatorics 5 | */ 6 | public class _634 { 7 | public int findDerangement(int n) { 8 | final int mod = 1000000007; 9 | long[] f = new long[n + 10]; 10 | f[1] = 0; 11 | f[2] = 1; 12 | for (int i = 3; i <= n; i++) { 13 | f[i] = (f[i - 1] + f[i - 2]) % mod * (i - 1) % mod; 14 | } 15 | return (int) f[n]; 16 | } 17 | } -------------------------------------------------------------------------------- /src/_643.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 643 - Maximum Average Subarray I 3 | *

4 | * Simply sliding window problem 5 | */ 6 | public class _643 { 7 | public double findMaxAverage(int[] nums, int k) { 8 | long maxSum = Long.MIN_VALUE; 9 | long sum = 0; 10 | for (int i = 0; i < nums.length; i++) { 11 | sum += nums[i]; 12 | if (i >= k) sum -= nums[i - k]; 13 | if (i >= k - 1) maxSum = Math.max(maxSum, sum); 14 | } 15 | return maxSum * 1.0 / k; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/_645.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 645 - Set Mismatch 5 | *

6 | * Counting Sort 7 | */ 8 | public class _645 { 9 | public int[] findErrorNums(int[] nums) { 10 | int n = nums.length; 11 | int[] cnt = new int[n + 1]; 12 | for (int num : nums) 13 | cnt[num]++; 14 | int twice = IntStream.rangeClosed(1, n).filter(i -> cnt[i] == 2).findFirst().getAsInt(); 15 | int miss = IntStream.rangeClosed(1, n).filter(i -> cnt[i] == 0).findFirst().getAsInt(); 16 | return new int[]{twice, miss}; 17 | } 18 | } -------------------------------------------------------------------------------- /src/_646.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Comparator; 3 | 4 | /** 5 | * LeetCode 646 6 | *

7 | * Maximum Length of Pair Chain 8 | *

9 | * Sweepline algorithm 10 | */ 11 | public class _646 { 12 | public int findLongestChain(int[][] pairs) { 13 | Arrays.sort(pairs, Comparator.comparingInt(u -> u[1])); 14 | int ans = 1, end = pairs[0][1]; 15 | for (int[] pair : pairs) { 16 | if (pair[0] > end) { 17 | ans++; 18 | end = pair[1]; 19 | } 20 | } 21 | return ans; 22 | } 23 | } -------------------------------------------------------------------------------- /src/_647.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 647 - Palindromic Substrings 3 | *

4 | * DP 5 | */ 6 | public class _647 { 7 | Boolean[][] f; 8 | 9 | private boolean f(String s, int i, int j) { 10 | if (i >= j) return true; 11 | f[i][j] = s.charAt(i) == s.charAt(j) && f(s, i + 1, j - 1); 12 | return f[i][j]; 13 | } 14 | 15 | public int countSubstrings(String s) { 16 | int n = s.length(); 17 | f = new Boolean[n][n]; 18 | int ans = 0; 19 | for (int i = 0; i < n; i++) 20 | for (int j = i; j < n; j++) 21 | if (f(s, i, j)) 22 | ans++; 23 | return ans; 24 | } 25 | } -------------------------------------------------------------------------------- /src/_650.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 650 - 2 Keys Keyboard 5 | *

6 | * O(n log n)-time DP 7 | */ 8 | public class _650 { 9 | 10 | public int minSteps(int n) { 11 | int[] f = new int[n + 1]; 12 | Arrays.fill(f, Integer.MAX_VALUE / 2); 13 | f[1] = 0; 14 | for (int i = 1; i < n; i++) { 15 | int cnt = f[i] + 1; 16 | for (int j = i + i; j <= n; j += i) { 17 | cnt++; 18 | f[j] = Math.min(f[j], cnt); 19 | } 20 | } 21 | System.out.println(Arrays.toString(f)); 22 | return f[n]; 23 | } 24 | 25 | public static void main(String[] args) { 26 | new _650().minSteps(7); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/_651.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 651 - 4 Keys Keyboard 3 | *

4 | * O(n^2)-time DP 5 | */ 6 | public class _651 { 7 | public int maxA(int N) { 8 | int[] f = new int[N + 1]; 9 | f[0] = 0; 10 | for (int i = 0; i < N; i++) { 11 | f[i + 1] = Math.max(f[i + 1], f[i] + 1); 12 | for (int j = i + 3; j <= N; j++) { 13 | f[j] = Math.max(f[j], (j - i - 1) * f[i]); 14 | } 15 | } 16 | return f[N]; 17 | } 18 | 19 | public static void main(String[] args) { 20 | System.out.println(new _651().maxA(7)); 21 | } 22 | } -------------------------------------------------------------------------------- /src/_654.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 654 - Maximum Binary Tree 5 | *

6 | * DFS approach 7 | */ 8 | public class _654 { 9 | public TreeNode constructMaximumBinaryTree(int[] nums) { 10 | if (nums.length == 0) { 11 | return null; 12 | } 13 | int max = 0; 14 | for (int i = 1; i < nums.length; i++) { 15 | if (nums[i] > nums[max]) { 16 | max = i; 17 | } 18 | } 19 | TreeNode root = new TreeNode(nums[max]); 20 | root.left = constructMaximumBinaryTree(Arrays.copyOfRange(nums, 0, max)); 21 | root.right = constructMaximumBinaryTree(Arrays.copyOfRange(nums, max + 1, nums.length)); 22 | return root; 23 | } 24 | } -------------------------------------------------------------------------------- /src/_660.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 669 - Remove 9 3 | *

4 | * Base-9 5 | */ 6 | public class _660 { 7 | 8 | public int newInteger(int n) { 9 | return Integer.parseInt(Integer.toString(n, 9)); 10 | } 11 | } -------------------------------------------------------------------------------- /src/_669.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 669 - Trim a Binary Search Tree 3 | *

4 | * DFS approach 5 | */ 6 | class _669 { 7 | public TreeNode trimBST(TreeNode root, int L, int R) { 8 | if (root == null) { 9 | return null; 10 | } 11 | 12 | TreeNode left = trimBST(root.left, L, R); 13 | TreeNode right = trimBST(root.right, L, R); 14 | if (L <= root.val && root.val <= R) { 15 | root.left = left; 16 | root.right = right; 17 | return root; 18 | } else { 19 | // Since root.val is already out of range, at least one of left or right must be null. 20 | return left != null ? left : right; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/_674.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 674 - Longest Continuous Increasing Subsequence 3 | *

4 | * O(n)-time solution 5 | */ 6 | class _674 { 7 | public int findLengthOfLCIS(int[] nums) { 8 | int ans = 0; 9 | for (int i = 0, j; i < nums.length; i = j) { 10 | for (j = i + 1; j < nums.length && nums[j - 1] < nums[j]; j++) ; 11 | ans = Math.max(ans, j - i); 12 | } 13 | return ans; 14 | } 15 | } -------------------------------------------------------------------------------- /src/_680.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 680 - Valid Palindrome II 3 | *

4 | * Greedy 5 | */ 6 | class _680 { 7 | public boolean validPalindrome(String s) { 8 | for (int i = 0, j = s.length() - 1; i < j; i++, j--) { 9 | if (s.charAt(i) != s.charAt(j)) { 10 | return isPalindrome(s, i + 1, j) || isPalindrome(s, i, j - 1); 11 | } 12 | } 13 | return true; 14 | } 15 | 16 | private boolean isPalindrome(String s, int i, int j) { 17 | for (; i < j; i++, j--) { 18 | if (s.charAt(i) != s.charAt(j)) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /src/_693.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 693 - Binary Number with Alternating Bits 3 | */ 4 | public class _693 { 5 | public boolean hasAlternatingBits(int n) { 6 | String s = Integer.toBinaryString(n); 7 | for (int i = 1; i < s.length(); i++) 8 | if (s.charAt(i - 1) == s.charAt(i)) 9 | return false; 10 | return true; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/_697.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 697 - Degree of an Array 3 | """ 4 | from collections import defaultdict 5 | 6 | 7 | class Solution: 8 | def findShortestSubArray(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | map = defaultdict(list) 14 | for i in range(len(nums)): 15 | map[nums[i]].append(i) 16 | return min((-len(list), list[-1] - list[0] + 1) for list in map.values())[1] 17 | 18 | 19 | sol = Solution() 20 | print(sol.findShortestSubArray((1, 2, 2, 3, 1))) 21 | print(sol.findShortestSubArray((1, 2, 2, 3, 1, 4, 2))) 22 | -------------------------------------------------------------------------------- /src/_717.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 717 - 1-bit and 2-bit Characters 3 | 4 | """ 5 | class Solution: 6 | def isOneBitCharacter(self, bits): 7 | """ 8 | :type bits: List[int] 9 | :rtype: bool 10 | """ 11 | i = 0 12 | while i < len(bits): 13 | if bits[i] == 0: 14 | ans = True 15 | i += 1 16 | else: 17 | ans = False 18 | i += 2 19 | return ans 20 | -------------------------------------------------------------------------------- /src/_718.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 718 - Maximum Length of Repeated Subarray 3 | *

4 | * Simple O(AB)-time DP 5 | * The space complexity can be further optimized to O(min(A, B)), though. 6 | */ 7 | public class _718 { 8 | public int findLength(int[] A, int[] B) { 9 | int n = A.length, m = B.length; 10 | int ans = 0; 11 | 12 | int[][] f = new int[n + 1][m + 1]; 13 | for (int i = 1; i <= n; i++) 14 | for (int j = 1; j <= m; j++) { 15 | if (A[i - 1] == B[j - 1]) 16 | f[i][j] = f[i - 1][j - 1] + 1; 17 | else 18 | f[i][j] = 0; 19 | ans = Math.max(ans, f[i][j]); 20 | } 21 | 22 | return ans; 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/_72.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 72 - Edit Distance 3 | * 4 | * O(nm) DP 5 | */ 6 | public class _72 { 7 | public int minDistance(String a, String b) { 8 | int[][] f = new int[a.length() + 1][b.length() + 1]; 9 | for (int i = 0; i <= a.length(); i++) f[i][b.length()] = a.length() - i; 10 | for (int j = 0; j <= b.length(); j++) f[a.length()][j] = b.length() - j; 11 | for (int i = a.length() - 1; i >= 0; i--) 12 | for (int j = b.length() - 1; j >= 0; j--) 13 | if (a.charAt(i) == b.charAt(j)) f[i][j] = f[i + 1][j + 1]; 14 | else f[i][j] = Math.min(Math.min(f[i + 1][j], f[i][j + 1]), f[i + 1][j + 1]) + 1; 15 | return f[0][0]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/_720.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 720 - Longest Word in Dictionary 3 | 4 | Sorting + DP 5 | """ 6 | 7 | 8 | class Solution: 9 | def longestWord(self, words): 10 | """ 11 | :type words: List[str] 12 | :rtype: str 13 | """ 14 | valid = {""} 15 | for word in sorted(words): 16 | if word[:-1] in valid: 17 | valid.add(word) 18 | return min(((-len(s), s) for s in valid))[1] 19 | 20 | -------------------------------------------------------------------------------- /src/_724.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 724 - Find Pivot Index 3 | 4 | Just use prefix-sum 5 | """ 6 | class Solution: 7 | def pivotIndex(self, nums): 8 | """ 9 | :type nums: List[int] 10 | :rtype: int 11 | """ 12 | 13 | prefix_sum = [0] * len(nums) 14 | for i in range(len(nums)): 15 | prefix_sum[i] = prefix_sum[i - 1] + nums[i] 16 | for i in range(len(nums)): 17 | left = prefix_sum[i - 1] if i - 1 >= 0 else 0 18 | right = prefix_sum[-1] - prefix_sum[i] 19 | if left == right: 20 | return i 21 | return -1 22 | -------------------------------------------------------------------------------- /src/_728.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 728 - Self Dividing Numbers 3 | """ 4 | 5 | 6 | class Solution: 7 | def selfDividingNumbers(self, left, right): 8 | """ 9 | :type left: int 10 | :type right: int 11 | :rtype: List[int] 12 | """ 13 | 14 | def is_self_dividing(n): 15 | s = str(n) 16 | return '0' not in s and all(n % (ord(i) - ord('0')) == 0 for i in s) 17 | 18 | return [i for i in range(left, right + 1) if is_self_dividing(i)] 19 | -------------------------------------------------------------------------------- /src/_734.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | """ 5 | LeetCode 734 - Sentence Similarity 6 | """ 7 | class Solution: 8 | def areSentencesSimilar(self, words1, words2, pairs): 9 | """ 10 | :type words1: List[str] 11 | :type words2: List[str] 12 | :type pairs: List[List[str]] 13 | :rtype: bool 14 | """ 15 | if len(words1) != len(words2): 16 | return False 17 | 18 | similar = defaultdict(list) 19 | for a, b in pairs: 20 | similar[a].append(b) 21 | similar[b].append(a) 22 | 23 | for a, b in zip(words1, words2): 24 | if not (a == b or a in similar[b] or b in similar[a]): 25 | return False 26 | return True 27 | -------------------------------------------------------------------------------- /src/_739.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 739 - Daily Temperatures 3 | 4 | Using a stack 5 | """ 6 | class Solution: 7 | def dailyTemperatures(self, a): 8 | """ 9 | :type temperatures: List[int] 10 | :rtype: List[int] 11 | """ 12 | res = [0] * len(a) 13 | stack = [] 14 | for i in range(len(a)): 15 | while stack and a[i] > a[stack[-1]]: 16 | res[stack[-1]] = i - stack[-1] 17 | stack.pop() 18 | stack.append(i) 19 | return res 20 | 21 | -------------------------------------------------------------------------------- /src/_740.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 740 - Delete and Earn 3 | 4 | DP 5 | """ 6 | 7 | 8 | class Solution: 9 | def deleteAndEarn(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | n = 10001 15 | cnt, f = [0] * n, [0] * n 16 | for num in nums: 17 | cnt[num] += 1 18 | for i in range(n): 19 | f[i] = max(f[i - 1] if i - 1 >= 0 else 0, i * cnt[i] + (f[i - 2] if i - 2 >= 0 else 0)) 20 | return max(f) 21 | -------------------------------------------------------------------------------- /src/_744.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 744 - Find Smallest Letter Greater Than Target 3 | 4 | Stupid problem description... 5 | """ 6 | import itertools as it 7 | 8 | 9 | class Solution: 10 | def nextGreatestLetter(self, letters, target): 11 | """ 12 | :type letters: List[str] 13 | :type target: str 14 | :rtype: str 15 | """ 16 | cnt = [0] * 128 17 | for letter in letters: 18 | cnt[ord(letter[0])] += 1 19 | return chr(next(filter(lambda ch: cnt[ch] > 0, 20 | it.chain(range(ord(target[0]) + 1, ord('z') + 1), 21 | range(ord('a'), ord(target[0])))))) 22 | -------------------------------------------------------------------------------- /src/_746.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 746 - Min Cost Climbing Stairs 3 | *

4 | * DP 5 | */ 6 | public class _746 { 7 | public int minCostClimbingStairs(int[] cost) { 8 | for (int i = 2; i < cost.length; i++) 9 | cost[i] += Math.min(cost[i - 1], cost[i - 2]); 10 | return Math.min(cost[cost.length - 1], cost[cost.length - 2]); 11 | } 12 | } 13 | 14 | -------------------------------------------------------------------------------- /src/_747.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 747 - Largest Number Greater Than Twice of Others 3 | */ 4 | public class _747 { 5 | 6 | public int dominantIndex(int[] nums) { 7 | int idx = 0; 8 | for (int i = 0; i < nums.length; i++) 9 | if (nums[i] > nums[idx]) 10 | idx = i; 11 | for (int i = 0; i < nums.length; i++) 12 | if (i != idx && 2 * nums[i] > nums[idx]) return -1; 13 | return idx; 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/_750.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 750 - Number of Corner Rectangles 3 | *

4 | * Similar to max sub-rectangle sum 5 | */ 6 | public class _750 { 7 | public int countCornerRectangles(int[][] grid) { 8 | int ans = 0; 9 | for (int i = 0; i < grid.length; i++) 10 | for (int j = i + 1; j < grid.length; j++) { 11 | int cnt = 0; 12 | for (int k = 0; k < grid[i].length; k++) 13 | if (grid[i][k] == 1 && grid[j][k] == 1) 14 | cnt++; 15 | ans += cnt * (cnt - 1) / 2; 16 | } 17 | return ans; 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/_754.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 755 - Reach a Number 3 | *

4 | * Math 5 | * O(sqrt(n))-time 6 | */ 7 | public class _754 { 8 | 9 | public int reachNumber(int target) { 10 | target = Math.abs(target); 11 | long sum = 0; 12 | for (int i = 0; ; i++) { 13 | sum += i; 14 | // This is obviously a necessary condition, but it is not too difficult to show it is also sufficient. 15 | if (sum >= target && (sum - target) % 2 == 0) { 16 | return i; 17 | } 18 | } 19 | } 20 | } 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/_766.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 766 - Toeplitz Matrix 3 | */ 4 | public class _766 { 5 | 6 | public boolean isToeplitzMatrix(int[][] matrix) { 7 | for (int i = 0; i < matrix.length - 1; i++) { 8 | for (int j = 0; j < matrix[i].length - 1; j++) { 9 | if (matrix[i][j] != matrix[i + 1][j + 1]) { 10 | return false; 11 | } 12 | } 13 | } 14 | return true; 15 | } 16 | } 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/_771.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 771 - Jewels and Stones 3 | */ 4 | public class _771 { 5 | 6 | public int numJewelsInStones(String J, String S) { 7 | int ans = 0; 8 | boolean[] hash = new boolean[128]; 9 | for (char ch : J.toCharArray()) { 10 | hash[ch] = true; 11 | } 12 | for (char ch : S.toCharArray()) { 13 | if (hash[ch]) { 14 | ans++; 15 | } 16 | } 17 | return ans; 18 | } 19 | } 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/_781.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 781 - Rabbits in Forest 3 | *

4 | * Math 5 | */ 6 | public class _781 { 7 | 8 | public int numRabbits(int[] answers) { 9 | if (answers == null || answers.length == 0) { 10 | return 0; 11 | } 12 | 13 | int[] cnt = new int[1000]; 14 | for (int i : answers) { 15 | cnt[i]++; 16 | } 17 | 18 | int ans = 0; 19 | for (int i = 0; i < 1000; i++) { 20 | ans += (cnt[i] + i) / (i + 1) * (i + 1); 21 | } 22 | return ans; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/_783.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 783 - Minimum Distance Between BST Nodes 3 | *

4 | * In-order traversal 5 | */ 6 | public class _783 { 7 | 8 | Integer previous = null; 9 | int ans = 0; 10 | 11 | public int minDiffInBST(TreeNode root) { 12 | ans = Integer.MAX_VALUE; 13 | previous = null; 14 | dfs(root); 15 | return ans; 16 | } 17 | 18 | private void dfs(TreeNode root) { 19 | if (root == null) { 20 | return; 21 | } 22 | dfs(root.left); 23 | if (previous != null) { 24 | ans = Math.min(ans, root.val - previous); 25 | } 26 | previous = root.val; 27 | dfs(root.right); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/_788.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 788 - Rotated Digits 5 | */ 6 | public class _788 { 7 | 8 | public int rotatedDigits(int N) { 9 | return (int) IntStream.rangeClosed(1, N).filter(i -> is(i)).count(); 10 | } 11 | 12 | boolean is(int x) { 13 | final int[] map = {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; 14 | int rotated = 0, backup = x, base = 1; 15 | while (x > 0) { 16 | int d = x % 10; 17 | if (map[d] == -1) { 18 | return false; 19 | } else { 20 | rotated += map[d] * base; 21 | base *= 10; 22 | x /= 10; 23 | } 24 | } 25 | return backup != rotated; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/_789.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 789 - Escape the Ghosts 3 | *

4 | * Math 5 | */ 6 | public class _789 { 7 | 8 | public boolean escapeGhosts(int[][] ghosts, int[] target) { 9 | int mine = Math.abs(target[0]) + Math.abs(target[1]); 10 | for (int[] ghost : ghosts) { 11 | int other = Math.abs(ghost[0] - target[0]) + Math.abs(ghost[1] - target[1]); 12 | if (other <= mine) { 13 | return false; 14 | } 15 | } 16 | return true; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/_791.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | 3 | /** 4 | * LeetCode 791 - Custom Sort String 5 | */ 6 | public class _791 { 7 | 8 | 9 | public String customSortString(String S, String T) { 10 | StringBuilder builder = new StringBuilder(); 11 | T.chars().boxed().sorted(Comparator.comparingInt(ch -> S.indexOf(ch))).forEach(builder::appendCodePoint); 12 | return builder.toString(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/_791_1.java: -------------------------------------------------------------------------------- 1 | public class _791_1 { 2 | 3 | public String customSortString(String S, String T) { 4 | StringBuilder builder = new StringBuilder(); 5 | int[] cnt = new int[128]; 6 | 7 | for (char ch : T.toCharArray()) { 8 | cnt[ch]++; 9 | } 10 | for (char ch : S.toCharArray()) { 11 | while (cnt[ch]-- > 0) { 12 | builder.append(ch); 13 | } 14 | } 15 | for (char ch = 0; ch < 128; ch++) { 16 | while (cnt[ch]-- > 0) { 17 | builder.append(ch); 18 | } 19 | } 20 | return builder.toString(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/_795_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 795 - Number of Subarrays with Bounded Maximum 3 | *

4 | * O(n)-time solution, using O(1) space. 5 | */ 6 | public class _795_1 { 7 | 8 | public int numSubarrayBoundedMax(int[] A, int L, int R) { 9 | 10 | return count(A, R) - count(A, L - 1); 11 | } 12 | 13 | private int count(int[] A, int max) { 14 | int cnt = 0, acc = 0; 15 | for (int i : A) { 16 | if (i <= max) { 17 | acc++; 18 | cnt += acc; 19 | } else { 20 | acc = 0; 21 | } 22 | } 23 | return cnt; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/_796.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 796 - Rotate String 3 | */ 4 | public class _796 { 5 | 6 | public boolean rotateString(String A, String B) { 7 | return A.length() == B.length() && (A + A).contains(B); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/_799.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 799 - Champagne Tower 3 | */ 4 | public class _799 { 5 | 6 | public double champagneTower(int poured, int query_row, int query_glass) { 7 | int n = 100; 8 | double[][] f = new double[n + 1][n + 1]; 9 | 10 | f[0][0] = poured; 11 | for (int i = 0; i < n; i++) { 12 | for (int j = 0; j <= i; j++) { 13 | if (f[i][j] > 1) { 14 | double more = f[i][j] - 1; 15 | f[i][j] = 1; 16 | f[i + 1][j] += 0.5 * more; 17 | f[i + 1][j + 1] += 0.5 * more; 18 | } 19 | } 20 | } 21 | return f[query_row][query_glass]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/_806.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 806 - Number of Lines To Write String 3 | */ 4 | public class _806 { 5 | 6 | public int[] numberOfLines(int[] widths, String S) { 7 | int cnt = 0; 8 | int line = 0; 9 | 10 | for (char ch : S.toCharArray()) { 11 | int width = widths[ch - 'a']; 12 | if (line + width > 100) { 13 | cnt++; 14 | line = 0; 15 | } 16 | line += width; 17 | } 18 | if (line > 0) { 19 | cnt++; 20 | } 21 | return new int[]{cnt, line}; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/_824.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 824 - Goat Latin 3 | 4 | Just be careful for capital vowels. 5 | """ 6 | 7 | 8 | class Solution: 9 | def toGoatLatin(self, S): 10 | """ 11 | :type S: str 12 | :rtype: str 13 | """ 14 | 15 | def convert(S): 16 | if S[0].lower() in {'a', 'e', 'i', 'o', 'u'}: 17 | return S + 'ma' 18 | else: 19 | return S[1:] + S[0] + 'ma' 20 | 21 | return ' '.join( 22 | convert(s) + 'a' * (cnt + 1) 23 | for s, cnt in zip(S.split(' '), range(len(S.split(' ')))) 24 | ) 25 | -------------------------------------------------------------------------------- /src/_825.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 825 - Friends of Appropriate Ages 3 | """ 4 | 5 | 6 | class Solution: 7 | def numFriendRequests(self, ages): 8 | """ 9 | :type ages: List[int] 10 | :rtype: int 11 | """ 12 | cnt = [0] * 121 13 | for age in ages: 14 | cnt[age] += 1 15 | 16 | ans = 0 17 | for a in range(121): 18 | for b in range(121): 19 | if b <= 0.5 * a + 7 or b > a or (b > 100 and a < 100): 20 | continue 21 | ans += cnt[a] * cnt[b] if a != b else cnt[a] * (cnt[b] - 1) 22 | 23 | return ans 24 | -------------------------------------------------------------------------------- /src/_826.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 826 - Most Profit Assigning Work 3 | 4 | Greedy 5 | """ 6 | 7 | class Solution: 8 | def maxProfitAssignment(self, difficulty, profit, worker): 9 | """ 10 | :type difficulty: List[int] 11 | :type profit: List[int] 12 | :type worker: List[int] 13 | :rtype: int 14 | """ 15 | 16 | map = {} 17 | difficulty = difficulty + worker 18 | profit = profit + [0 for _ in worker] 19 | max_profit = 0 20 | for di, pr in sorted(zip(difficulty, profit)): 21 | max_profit = max(max_profit, pr) 22 | map[di] = max_profit 23 | 24 | return sum(map[each_worker] for each_worker in worker) 25 | -------------------------------------------------------------------------------- /src/_832.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 832 - Flipping an Image 3 | """ 4 | 5 | 6 | class Solution: 7 | def flipAndInvertImage(self, A): 8 | """ 9 | :type A: List[List[int]] 10 | :rtype: List[List[int]] 11 | """ 12 | return [[1 - i for i in reversed(a)] for a in A] 13 | -------------------------------------------------------------------------------- /src/_833.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 833 - Find and Replace in String 3 | 4 | """ 5 | 6 | 7 | class Solution: 8 | def findReplaceString(self, S, indexes, sources, targets): 9 | """ 10 | :type S: str 11 | :type indexes: List[int] 12 | :type sources: List[str] 13 | :type targets: List[str] 14 | :rtype: str 15 | """ 16 | res, pos = "", 0 17 | for idx, source, target in sorted(zip(indexes, sources, targets)): 18 | if S[idx:].startswith(source): 19 | res += S[pos:idx] 20 | res += target 21 | pos = idx + len(source) 22 | 23 | return res + S[pos:] 24 | -------------------------------------------------------------------------------- /src/_836.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 836 - Rectangle Overlap 3 | */ 4 | public class _836 { 5 | 6 | public boolean isRectangleOverlap(int[] rec1, int[] rec2) { 7 | return Math.max(rec1[0], rec2[0]) < Math.min(rec1[2], rec2[2]) && Math.max(rec1[1], rec2[1]) < Math.min(rec1[3], rec2[3]); 8 | } 9 | } 10 | 11 | -------------------------------------------------------------------------------- /src/_841.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | /** 4 | * LeetCode 841 - Keys and Rooms 5 | *

6 | * Just do a DFS or BFS. 7 | */ 8 | public class _841 { 9 | 10 | public boolean canVisitAllRooms(List> rooms) { 11 | return dfs(rooms, new boolean[rooms.size()], 0) == rooms.size(); 12 | } 13 | 14 | private int dfs(List> rooms, boolean[] visited, int i) { 15 | if (visited[i]) 16 | return 0; 17 | visited[i] = true; 18 | return rooms.get(i).stream().mapToInt(j -> dfs(rooms, visited, j)).sum() + 1; 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/_845.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 845 - Longest Mountain in Array 3 | */ 4 | public class _845 { 5 | 6 | public int longestMountain(int[] A) { 7 | int max = 0; 8 | for (int i = 1; i < A.length - 1; i++) { 9 | if (A[i] > A[i - 1] && A[i] > A[i + 1]) { 10 | int left = i, right = i; 11 | while (left - 1 >= 0 && A[left - 1] < A[left]) { 12 | left--; 13 | } 14 | while (right + 1 < A.length && A[right + 1] < A[right]) { 15 | right++; 16 | } 17 | max = Math.max(max, right - left + 1); 18 | } 19 | } 20 | return max; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/_848.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 848 - Shifting Letters 3 | *

4 | * Suffix-sum 5 | */ 6 | public class _848 { 7 | 8 | public String shiftingLetters(String S, int[] shifts) { 9 | for (int i = shifts.length - 2; i >= 0; i--) { 10 | shifts[i] = (shifts[i + 1] + shifts[i]) % 26; 11 | } 12 | StringBuilder builder = new StringBuilder(); 13 | for (int i = 0; i < S.length(); i++) { 14 | builder.append(shift(S.charAt(i), shifts[i])); 15 | } 16 | return builder.toString(); 17 | } 18 | 19 | char shift(char a, int x) { 20 | return (char) ((a - 'a' + x) % 26 + 'a'); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/_849.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 849 - Maximize Distance to Closest Person 3 | *

4 | * Linear Scan 5 | */ 6 | public class _849 { 7 | 8 | public int maxDistToClosest(int[] seats) { 9 | int ans = 0; 10 | int pos = -1; 11 | for (int i = 0; i < seats.length; i++) { 12 | if (seats[i] == 1) { 13 | if (pos == -1) { 14 | ans = Math.max(ans, i); 15 | } else { 16 | ans = Math.max(ans, (i - pos) / 2); 17 | } 18 | pos = i; 19 | } 20 | } 21 | if (seats[seats.length - 1] == 0) { 22 | ans = Math.max(ans, seats.length - 1 - pos); 23 | } 24 | return ans; 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/_852.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 852 - Peak Index in a Mountain Array 3 | *

4 | * Binary Search 5 | */ 6 | public class _852 { 7 | 8 | public int peakIndexInMountainArray(int[] a) { 9 | int left = 1, right = a.length - 2; 10 | while (true) { 11 | int mid = (left + right) / 2; 12 | if (a[mid] > a[mid - 1] && a[mid] > a[mid + 1]) { 13 | return mid; 14 | } else if (a[mid] > a[mid - 1]) { 15 | left = mid + 1; 16 | } else { 17 | right = mid - 1; 18 | } 19 | } 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/_860.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 860 - Lemonade Change 3 | *

4 | * Greedy 5 | */ 6 | public class _860 { 7 | 8 | public boolean lemonadeChange(int[] bills) { 9 | int[] cnt = new int[21]; 10 | for (int bill : bills) { 11 | cnt[bill]++; 12 | int change = bill - 5; 13 | for (int i : new int[]{10, 5}) { 14 | while (change >= i && cnt[i] > 0) { 15 | change -= i; 16 | cnt[i]--; 17 | } 18 | } 19 | if (change > 0) { 20 | return false; 21 | } 22 | } 23 | return true; 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /src/_867.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 868 - Transpose Matrix 3 | */ 4 | public class _867 { 5 | 6 | public int[][] transpose(int[][] A) { 7 | int[][] res = new int[A[0].length][A.length]; 8 | for (int i = 0; i < A.length; i++) { 9 | for (int j = 0; j < A[0].length; j++) { 10 | res[j][i] = A[i][j]; 11 | } 12 | } 13 | return res; 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/_868.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 868 - Binary Gap 3 | *

4 | * Brute-force 5 | */ 6 | public class _868 { 7 | 8 | public int binaryGap(int N) { 9 | int ans = 0; 10 | for (int i = 0; i < 32; i++) { 11 | if (((1 << i) & N) != 0) { 12 | for (int j = i + 1; j < 32; j++) { 13 | if (((1 << j) & N) != 0) { 14 | ans = Math.max(ans, j - i); 15 | break; 16 | } 17 | } 18 | } 19 | } 20 | return ans; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/_869.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.HashSet; 3 | import java.util.Set; 4 | 5 | /** 6 | * LeetCode 869 - Reordered Power of 2 7 | *

8 | * Dictionary lookup 9 | */ 10 | public class _869 { 11 | 12 | public boolean reorderedPowerOf2(int N) { 13 | Set candidates = new HashSet<>(); 14 | for (int i = 0; i < 32; i++) { 15 | char[] s = ("" + (1L << i)).toCharArray(); 16 | Arrays.sort(s); 17 | candidates.add(String.valueOf(s)); 18 | } 19 | char[] n = ("" + N).toCharArray(); 20 | Arrays.sort(n); 21 | return candidates.contains(String.valueOf(n)); 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/_876.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 876 - Middle of the Linked List 3 | *

4 | * Fast-and-slow pointers 5 | */ 6 | public class _876 { 7 | 8 | public ListNode middleNode(ListNode head) { 9 | ListNode dummy = new ListNode(0); 10 | dummy.next = head; 11 | ListNode slow = dummy, fast = dummy; 12 | while (fast != null) { 13 | slow = slow.next; 14 | fast = fast.next; 15 | fast = fast != null ? fast.next : fast; 16 | } 17 | return slow; 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/_878.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 878 - Nth Magical Number 3 | *

4 | * Binary Search + Math 5 | */ 6 | public class _878 { 7 | 8 | int gcd(int i, int j) { 9 | return i == 0 ? j : gcd(j % i, i); 10 | } 11 | 12 | public int nthMagicalNumber(int N, int A, int B) { 13 | long lcm = 1L * A * B / gcd(A, B); 14 | long left = 0, right = 1L * N * A * B; 15 | while (left + 1 < right) { 16 | long mid = left + (right - left) / 2; 17 | long cnt = mid / A + mid / B - mid / lcm; 18 | if (cnt >= N) { 19 | right = mid; 20 | } else { 21 | left = mid; 22 | } 23 | } 24 | return (int) (right % 1000000007); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/_896.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | public class _896 { 4 | 5 | public boolean isMonotonic(int[] A) { 6 | return IntStream.range(0, A.length - 1).allMatch(i -> A[i] >= A[i + 1]) || IntStream.range(0, A.length - 1).allMatch(i -> A[i] <= A[i + 1]); 7 | } 8 | } 9 | 10 | -------------------------------------------------------------------------------- /src/_901.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * LeetCode 901 - Online Stock Span 5 | * 6 | * Monotone-Stack 7 | */ 8 | public class _901 { 9 | 10 | Stack s = new Stack<>(); 11 | 12 | 13 | public _901() { 14 | 15 | } 16 | 17 | public int next(int price) { 18 | int res = 0; 19 | while (!s.isEmpty() && s.peek()[0] <= price) { 20 | res += s.pop()[1]; 21 | } 22 | s.push(new int[]{price, res + 1}); 23 | return res + 1; 24 | } 25 | } 26 | 27 | /** 28 | * Your StockSpanner object will be instantiated and called as such: 29 | * StockSpanner obj = new StockSpanner(); 30 | * int param_1 = obj.next(price); 31 | */ -------------------------------------------------------------------------------- /src/_905.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | 4 | /** 5 | * LeetCode 905 - Sort Array By Parity 6 | * 7 | * 1-Liner 8 | */ 9 | public class _905 { 10 | 11 | public int[] sortArrayByParity(int[] A) { 12 | return IntStream.concat(IntStream.of(A).filter(i -> i % 2 == 0), IntStream.of(A).filter(i -> i % 2 != 0)).toArray(); 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/_908.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 908 - Smallest Range I 5 | * 6 | * Greedy 7 | */ 8 | public class _908 { 9 | 10 | public int smallestRangeI(int[] A, int K) { 11 | int max = IntStream.of(A).max().getAsInt(); 12 | int min = IntStream.of(A).min().getAsInt(); 13 | return Math.max(0, max - min - 2 * K); 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/_914.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * LeetCode X of a Kind in a Deck of Cards 6 | * 7 | * Math 8 | */ 9 | public class _914 { 10 | 11 | int gcd(int i, int j) { 12 | return j == 0 ? i : gcd(j, i % j); 13 | } 14 | 15 | public boolean hasGroupsSizeX(int[] deck) { 16 | Map map = new HashMap<>(); 17 | for (int i : deck) { 18 | map.put(i, map.getOrDefault(i, 0) + 1); 19 | } 20 | int g = map.values().iterator().next(); 21 | for (int i : map.values()) { 22 | g = gcd(g, i); 23 | } 24 | return g >= 2; 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/_915.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 915 - Partition Array into Disjoint Intervals 3 | */ 4 | public class _915 { 5 | 6 | public int partitionDisjoint(int[] A) { 7 | int n = A.length; 8 | int[] min = new int[n]; 9 | 10 | min[n - 1] = A[n - 1]; 11 | for (int i = n - 2; i >= 0; i--) { 12 | min[i] = Math.min(min[i + 1], A[i]); 13 | } 14 | 15 | int max = Integer.MIN_VALUE; 16 | for (int i = 0; i < A.length - 1; i++) { 17 | max = Math.max(max, A[i]); 18 | if (max <= min[i + 1]) { 19 | return i + 1; 20 | } 21 | } 22 | throw new RuntimeException(""); 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /src/_921.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 921 - Minimum Add to Make Parentheses Valid 3 | */ 4 | public class _921 { 5 | 6 | public int minAddToMakeValid(String S) { 7 | int res = 0; 8 | int leftParam = 0; 9 | for (char ch : S.toCharArray()) { 10 | if (ch == '(') { 11 | leftParam++; 12 | } else { 13 | if (leftParam == 0) { 14 | res++; 15 | } else { 16 | leftParam--; 17 | } 18 | } 19 | } 20 | 21 | return res + leftParam; 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/_922.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 922 - Sort Array by Parity II 3 | */ 4 | public class _922 { 5 | 6 | public int[] sortArrayByParityII(int[] A) { 7 | int[] res = A.clone(); 8 | for (int i = 0, even = 0, odd = 1; i < A.length; i++) { 9 | if (A[i] % 2 == 0) { 10 | res[even] = A[i]; 11 | even += 2; 12 | } else { 13 | res[odd] = A[i]; 14 | odd += 2; 15 | } 16 | } 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/_933.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Deque; 3 | 4 | /** 5 | * LeetCode 933 - Number of Recent Calls 6 | * 7 | * Monotone Queue 8 | */ 9 | public class _933 { 10 | 11 | Deque queue = new ArrayDeque<>(); 12 | 13 | public _933() { 14 | 15 | } 16 | 17 | public int ping(int t) { 18 | queue.add(t); 19 | while (!queue.isEmpty() && queue.getLast() - queue.getFirst() > 3000) { 20 | queue.removeFirst(); 21 | } 22 | return queue.size(); 23 | } 24 | } 25 | 26 | /** 27 | * Your RecentCounter object will be instantiated and called as such: 28 | * RecentCounter obj = new RecentCounter(); 29 | * int param_1 = obj.ping(t); 30 | */ -------------------------------------------------------------------------------- /src/_941.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 941 - Valid Mountain Array 3 | * 4 | * Two-pointer 5 | */ 6 | public class _941 { 7 | 8 | public boolean validMountainArray(int[] a) { 9 | if (a == null || a.length < 3) return false; 10 | int i = 0, j = a.length - 1; 11 | while (i < j) { 12 | if (a[i] < a[i + 1]) i++; 13 | else if (a[j - 1] > a[j]) j--; 14 | else return false; 15 | } 16 | return i > 0 && i < a.length - 1; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/_942.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 942 - DI String Match 3 | * [ 4 | * Constructive approach 5 | */ 6 | public class _942 { 7 | 8 | public int[] diStringMatch(String S) { 9 | int n = S.length(); 10 | int[] res = new int[n + 1]; 11 | int min = 0, max = n; 12 | 13 | for (int i = 0; i < S.length(); i++) { 14 | if (S.charAt(i) == 'I') { 15 | res[i] = min++; 16 | } else { 17 | res[i] = max--; 18 | } 19 | } 20 | if (min != max) throw new RuntimeException(""); 21 | res[n] = min; 22 | 23 | return res; 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /src/_944.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 944 - Delete Columns to Make Sorted 3 | * 4 | * Stupid problem description. 5 | * It would be more interesting to compute the minimum # columns to remove such that 6 | * the remaining strings are in lexico-order. 7 | */ 8 | public class _944 { 9 | 10 | public int minDeletionSize(String[] A) { 11 | int cnt = 0; 12 | for (int j = 0; j < A[0].length(); j++) { 13 | for (int i = 0; i < A.length - 1; i++) { 14 | if (A[i].charAt(j) > A[i + 1].charAt(j)) { 15 | cnt++; 16 | break; 17 | } 18 | } 19 | } 20 | return cnt; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/_945.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 945 - Minimum Increment to Make Array Unique 5 | * 6 | * Counting 7 | */ 8 | public class _945 { 9 | 10 | public int minIncrementForUnique(int[] A) { 11 | Arrays.sort(A); 12 | int ans = 0, next = Integer.MIN_VALUE; 13 | for (int i = 0; i < A.length; i++) { 14 | if (A[i] > next) { 15 | next = A[i] + 1; 16 | } else { 17 | ans += next - A[i]; 18 | next++; 19 | } 20 | } 21 | return ans; 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/_946.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * LeetCode 946 - Validate Stack Sequences 5 | * 6 | * Stack 7 | */ 8 | public class _946 { 9 | 10 | public boolean validateStackSequences(int[] pushed, int[] popped) { 11 | Stack s = new Stack<>(); 12 | int i = 0, j = 0; 13 | for (; i < pushed.length; i++) { 14 | s.push(pushed[i]); 15 | while (j < popped.length && !s.isEmpty() && popped[j] == s.peek()) { 16 | s.pop(); 17 | j++; 18 | } 19 | } 20 | return j == popped.length; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/_948.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 948 - Bag of Tokens 5 | * 6 | * Greedy 7 | */ 8 | public class _948 { 9 | 10 | public int bagOfTokensScore(int[] tokens, int P) { 11 | int ans = 0, points = 0; 12 | Arrays.sort(tokens); 13 | int i = 0, j = tokens.length - 1; 14 | while (i <= j) { 15 | if (tokens[i] <= P) { 16 | P -= tokens[i++]; 17 | points++; 18 | ans = Math.max(ans, points); 19 | } else if (points > 0) { 20 | points--; 21 | P += tokens[j--]; 22 | } else { 23 | break; 24 | } 25 | } 26 | return ans; 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/_949.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 949 - Largest Time for Given Digits 3 | """ 4 | 5 | from itertools import permutations 6 | 7 | 8 | class Solution: 9 | def largestTimeFromDigits(self, A): 10 | """ 11 | :type A: List[int] 12 | :rtype: str 13 | """ 14 | ans = "" 15 | for (a, b, c, d) in permutations(A): 16 | hour = a * 10 + b 17 | minute = c * 10 + d 18 | if 0 <= hour < 24 and 0 <= minute < 60: 19 | current = "{:02d}:{:02d}".format(hour, minute) 20 | if ans == "" or current > ans: 21 | ans = current 22 | return ans 23 | -------------------------------------------------------------------------------- /src/_951.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 951 - Flip Equivalent Binary Trees 3 | * 4 | * DFS 5 | * This problem will be harder and more interesting if duplicates are allowed in the tree. 6 | */ 7 | public class _951 { 8 | 9 | public boolean flipEquiv(TreeNode root1, TreeNode root2) { 10 | if (root1 == null) { 11 | return root2 == null; 12 | } 13 | if (root2 == null) { 14 | return root1 == null; 15 | } 16 | if (root1.val != root2.val) { 17 | return false; 18 | } 19 | return flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) || 20 | flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left); 21 | 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/_96.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 96 - Unique Binary Search Trees 3 | * 4 | * DP for computing Catalan Number 5 | */ 6 | public class _96 { 7 | public int numTrees(int n) { 8 | int[] f = new int[n + 1]; 9 | f[0] = 1; 10 | for (int i = 1; i <= n; i++) 11 | for (int j = 0; j < i; j++) 12 | f[i] += f[j] * f[i - 1 - j]; 13 | return f[n]; 14 | } 15 | } -------------------------------------------------------------------------------- /src/_965.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 965 - Univalued Binary Tree 3 | * 4 | * DFS 5 | */ 6 | public class _965 { 7 | 8 | public boolean isUnivalTree(TreeNode root) { 9 | if (root == null) return true; 10 | return dfs(root, root.val); 11 | } 12 | 13 | boolean dfs(TreeNode root, int val) { 14 | if (root == null) { 15 | return true; 16 | } 17 | return root.val == val && dfs(root.left, val) && dfs(root.right, val); 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/_973.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.stream.Stream; 3 | 4 | /** 5 | * LeetCode 973 - K Closest Points to Origin 6 | * 7 | * 1-Liner 8 | */ 9 | public class _973 { 10 | 11 | public int[][] kClosest(int[][] points, int K) { 12 | return Stream.of(points).sorted(Comparator.comparingInt(arr -> arr[0] * arr[0] + arr[1] * arr[1])).limit(K).toArray(int[][]::new); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/_974.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 974 - Subarray Sums Divisible by K 3 | * 4 | * Prefix Sum 5 | */ 6 | public class _974 { 7 | 8 | public int subarraysDivByK(int[] A, int K) { 9 | int prefixSum = 0, ans = 0; 10 | int[] cnt = new int[K]; 11 | 12 | cnt[0] = 1; 13 | for (int i = 0; i < A.length; i++) { 14 | prefixSum += K + A[i] % K; 15 | prefixSum %= K; 16 | 17 | ans += cnt[prefixSum]; 18 | cnt[prefixSum]++; 19 | } 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/_976.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * LeetCode 976 - Largest Perimeter Triangle 5 | * 6 | * Greedy 7 | */ 8 | public class _976 { 9 | 10 | public int largestPerimeter(int[] A) { 11 | Arrays.sort(A); 12 | int ans = 0; 13 | for (int i = A.length - 1; i - 2 >= 0; i--) { 14 | if (A[i - 2] + A[i - 1] > A[i]) { 15 | return A[i - 2] + A[i - 1] + A[i]; 16 | } 17 | } 18 | return 0; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/_977.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 977 - Squares of a Sorted Array 5 | * 6 | * 1-Liner 7 | */ 8 | public class _977 { 9 | 10 | public int[] sortedSquares(int[] A) { 11 | return IntStream.of(A).map(i -> i * i).sorted().toArray(); 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /src/_977_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 977 - Squares of a Sorted Array 3 | * 4 | * O(n)-time/space solution 5 | */ 6 | public class _977_1 { 7 | 8 | public int[] sortedSquares(int[] A) { 9 | int[] res = A.clone(); 10 | for (int i = 0, j = A.length - 1, k = res.length - 1; i <= j; ) { 11 | if (A[i] * A[i] > A[j] * A[j]) { 12 | res[k--] = A[i] * A[i]; 13 | i++; 14 | } else { 15 | res[k--] = A[j] * A[j]; 16 | j--; 17 | } 18 | } 19 | return res; 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/_978.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 978 - Longest Turbulent Subarray 3 | * 4 | * Solution 5 | */ 6 | public class _978 { 7 | 8 | public int maxTurbulenceSize(int[] A) { 9 | int ans = 1; 10 | for (int i = 0; i < A.length - 1; ) { 11 | int j = i; 12 | while (j + 2 < A.length && Integer.signum(A[j] - A[j + 1]) * Integer.signum(A[j + 1] - A[j + 2]) < 0) { 13 | j++; 14 | } 15 | ans = Math.max(ans, (j + 1) - i + 1); 16 | i = j + 1; 17 | } 18 | return ans; 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/_979_1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 979 - Distribute Coins in Binary Tree 3 | * 4 | * Top-down Approach 5 | */ 6 | public class _979_1 { 7 | 8 | int ans = 0; 9 | 10 | public int distributeCoins(TreeNode root) { 11 | ans = 0; 12 | dfs(root); 13 | return ans; 14 | } 15 | 16 | int[] dfs(TreeNode root) { 17 | if (root == null) { 18 | return new int[]{0, 0}; 19 | } 20 | int[] left = dfs(root.left); 21 | int[] right = dfs(root.right); 22 | ans += Math.abs(left[0] - left[1]); 23 | ans += Math.abs(right[0] - right[1]); 24 | 25 | return new int[]{left[0] + right[0] + 1, left[1] + right[1] + root.val}; 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/_984.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 984 - String without AAA or BBB 3 | *

4 | * Greedy 5 | */ 6 | public class _984 { 7 | 8 | public String strWithout3a3b(int A, int B) { 9 | char[] ans = new char[A + B]; 10 | int m = 0; 11 | while (A + B > 0) { 12 | char t = A > B ? 'a' : 'b'; 13 | if (m >= 2 && ans[m - 1] == t && ans[m - 2] == t) { 14 | t = t == 'a' ? 'b' : 'a'; 15 | } 16 | ans[m++] = t; 17 | 18 | if (t == 'a') { 19 | A--; 20 | } else { 21 | B--; 22 | } 23 | } 24 | return String.valueOf(ans); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/_985.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | /** 4 | * LeetCode 985 - Sum of Even Numbers After Queries 5 | */ 6 | public class _985 { 7 | 8 | public int[] sumEvenAfterQueries(int[] A, int[][] queries) { 9 | int[] res = new int[queries.length]; 10 | int sum = IntStream.of(A).filter(i -> i % 2 == 0).sum(); 11 | for (int i = 0; i < queries.length; i++) { 12 | int val = queries[i][0], idx = queries[i][1]; 13 | if (A[idx] % 2 == 0) { 14 | sum -= A[idx]; 15 | } 16 | A[idx] += val; 17 | if (A[idx] % 2 == 0) { 18 | sum += A[idx]; 19 | } 20 | res[i] = sum; 21 | } 22 | return res; 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /src/_988.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LeetCode 988 - Smallest String Starting from Leaf 3 | */ 4 | public class _988 { 5 | 6 | String ans = null; 7 | 8 | public String smallestFromLeaf(TreeNode root) { 9 | ans = null; 10 | dfs(root, ""); 11 | return ans; 12 | } 13 | 14 | void dfs(TreeNode root, String s) { 15 | if (root == null) { 16 | return; 17 | } 18 | 19 | String ss = (char) (root.val + 'a') + s; 20 | if (root.left == null && root.right == null) { 21 | if (ans == null || ss.compareTo(ans) < 0) { 22 | ans = ss; 23 | } 24 | } 25 | dfs(root.left, ss); 26 | dfs(root.right, ss); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/_989.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.List; 4 | 5 | /** 6 | * LeetCode 989 - Add to Array-Form of Integer 7 | * 8 | * Arithmetic Addition 9 | */ 10 | public class _989 { 11 | 12 | public List addToArrayForm(int[] A, int K) { 13 | List res = new ArrayList<>(); 14 | int current = K; 15 | int i = A.length - 1; 16 | while (i >= 0 || current > 0) { 17 | if (i >= 0) { 18 | current += A[i]; 19 | i--; 20 | } 21 | res.add(current % 10); 22 | current /= 10; 23 | } 24 | 25 | Collections.reverse(res); 26 | return res; 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/_993.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 993 - Cousins in Binary Tree 3 | """ 4 | class Solution: 5 | def isCousins(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool': 6 | 7 | def dfs(root, parent, d, x): 8 | if root is None: 9 | return None 10 | if root.val == x: 11 | return (parent, d) 12 | return dfs(root.left, root, d + 1, x) or dfs(root.right, root, d + 1, x) 13 | 14 | (p1, d1) = dfs(root, None, 0, x) 15 | (p2, d2) = dfs(root, None, 0, y) 16 | 17 | return x != y and p1 != p2 and d1 == d2 18 | 19 | -------------------------------------------------------------------------------- /src/_997.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 997 - Find the Town Judge 3 | 4 | Essentially the "universal sink" problem 5 | """ 6 | from typing import * 7 | 8 | 9 | class Solution: 10 | def findJudge(self, N: int, trust: List[List[int]]) -> int: 11 | in_deg, out_deg = [0] * (N + 1), [0] * (N + 1) 12 | for u, v in trust: 13 | out_deg[u] += 1 14 | in_deg[v] += 1 15 | 16 | judge = [i for i in range(1, N + 1) if in_deg[i] == N - 1] 17 | if len(judge) != 1 or out_deg[judge[0]] > 0: 18 | return -1 19 | return judge[0] 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/_998.py: -------------------------------------------------------------------------------- 1 | """ 2 | LeetCode 998 - Maximum Binary Tree II 3 | 4 | DFS 5 | """ 6 | 7 | 8 | class Solution: 9 | def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode: 10 | if not root: 11 | return TreeNode(val) 12 | elif val > root.val: 13 | node = TreeNode(val) 14 | node.left = root 15 | return node 16 | else: 17 | root.right = self.insertIntoMaxTree(root.right, val) 18 | return root 19 | -------------------------------------------------------------------------------- /src/closest-divisors.py: -------------------------------------------------------------------------------- 1 | """1362. Closest Divisors 2 | 3 | Brute-force 4 | There can be at most sqrt(n) pairs of divisors, so we can just enumerate all of them. 5 | 6 | Time: O(sqrt(n)) 7 | Space: O(sqrt(n)), which can be further optimized to O(1). 8 | """ 9 | from typing import List 10 | 11 | 12 | class Solution: 13 | def closestDivisors(self, num: int) -> List[int]: 14 | def factors(n: int): 15 | i = 1 16 | while i * i <= n: 17 | if n % i == 0: 18 | yield (i, n // i) 19 | i += 1 20 | 21 | return min(list(factors(num + 1)) + list(factors(num + 2)), key=lambda key: key[1] - key[0]) 22 | -------------------------------------------------------------------------------- /src/how-many-numbers-are-smaller-than-the-current-number.py: -------------------------------------------------------------------------------- 1 | """1365. How Many Numbers Are Smaller Than the Current Number 2 | 3 | Since each number is within the range [0, 100], we can use a counting sort based approach. 4 | 1. Do a linear-time counting. 5 | 2. Compute the prefix sum. 6 | 3. Answer each query in O(1) time. 7 | 8 | Time: O(n) 9 | Space: O(100) 10 | """ 11 | 12 | 13 | class Solution: 14 | def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: 15 | cnt = [0] * 101 16 | for i in nums: 17 | cnt[i] += 1 18 | for i in range(1, 101): 19 | cnt[i] += cnt[i - 1] 20 | return [cnt[i - 1] if i - 1 >= 0 else 0 for i in nums] 21 | -------------------------------------------------------------------------------- /src/number-of-days-between-two-dates.py: -------------------------------------------------------------------------------- 1 | """1360. Number of Days Between Two Dates 2 | 3 | Most programming languages should have date related packages. 4 | Worth getting familiar with them. 5 | """ 6 | from datetime import datetime 7 | 8 | 9 | class Solution: 10 | def daysBetweenDates(self, date1: str, date2: str) -> int: 11 | date1 = datetime.fromisoformat(date1) 12 | date2 = datetime.fromisoformat(date2) 13 | return (max(date1, date2) - min(date1, date2)).days 14 | -------------------------------------------------------------------------------- /src/rank-teams-by-votes.py: -------------------------------------------------------------------------------- 1 | """1366. Rank Teams by Votes 2 | 3 | Radix Sort 4 | Assume there are m rounds of voting, we can solve this problem by a radix sort (from the m-th round to the first round). 5 | 6 | Time: O(m * (26 log 26)), which can be further optimized to O(26m) using counting sort. 7 | Space: O(26) 8 | """ 9 | from collections import Counter 10 | from typing import List 11 | 12 | 13 | class Solution: 14 | def rankTeams(self, votes: List[str]) -> str: 15 | a = sorted(list(votes[0])) 16 | for col in range(len(votes[0]) - 1, -1, -1): 17 | cnt = Counter(vote[col] for vote in votes) 18 | a.sort(key=lambda ch: -cnt[ch]) 19 | return "".join(a) 20 | -------------------------------------------------------------------------------- /tests/_140Test.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.HashSet; 3 | import java.util.Set; 4 | 5 | import static junit.framework.TestCase.assertEquals; 6 | 7 | public class _140Test { 8 | 9 | @org.junit.Test 10 | public void test() { 11 | Set set = new HashSet<>(Arrays.asList("cat", "cats", "and", "sand", "dog")); 12 | 13 | Set ans = new HashSet<>((new _140()).wordBreak("catsanddog", set)); 14 | Set want = new HashSet<>(Arrays.asList("cats and dog", "cat sand dog")); 15 | assertEquals(ans, want); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /tests/_206Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static junit.framework.Assert.assertEquals; 4 | 5 | public class _206Test { 6 | 7 | @Test 8 | public void test() { 9 | ListNode ans = (new _206()).reverseList(null); 10 | assertEquals(null, ans); 11 | 12 | ListNode b = new ListNode(1); 13 | ans = (new _206()).reverseList(b); 14 | assertEquals(b, ans); 15 | 16 | ListNode c = new ListNode(2); 17 | c.next = b; 18 | ans = (new _206()).reverseList(c); 19 | assertEquals(b, ans); 20 | assertEquals(c, ans.next); 21 | assertEquals(null, ans.next.next); 22 | } 23 | } -------------------------------------------------------------------------------- /tests/_265Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _265Test { 6 | 7 | @Test 8 | public void test() throws Exception { 9 | _265 sol = new _265(); 10 | int actual = sol.minCostII(new int[][]{{1, 3}, {2, 1}, {3, 1}}); 11 | int expected = 5; 12 | assertEquals(expected, actual); 13 | } 14 | } -------------------------------------------------------------------------------- /tests/_269Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _269Test { 6 | 7 | public void check(String[] words, String expected) throws Exception { 8 | _269 sol = new _269(); 9 | String actual = sol.alienOrder(words); 10 | assertEquals(expected, actual); 11 | } 12 | 13 | @Test 14 | public void test() throws Exception { 15 | check(new String[]{"wrt", "wrf", "er", "ett", "rftt"}, "wertf"); 16 | check(new String[]{"a", "ab"}, "ab"); 17 | check(new String[]{"a", "b", "a"}, ""); 18 | check(new String[]{"za", "zb", "ca", "cb"}, "abzc"); 19 | } 20 | } -------------------------------------------------------------------------------- /tests/_288Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertFalse; 4 | import static org.junit.Assert.assertTrue; 5 | 6 | public class _288Test { 7 | @Test 8 | public void test() { 9 | _288 sol = new _288(new String[]{"dog"}); 10 | 11 | assertFalse(sol.isUnique("dig")); 12 | assertFalse(sol.isUnique("dug")); 13 | assertFalse(sol.isUnique("dag")); 14 | assertTrue(sol.isUnique("dog")); 15 | assertTrue(sol.isUnique("doge")); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /tests/_291Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertFalse; 4 | import static org.junit.Assert.assertTrue; 5 | 6 | public class _291Test { 7 | 8 | @Test 9 | public void test() throws Exception { 10 | _291 sol = new _291(); 11 | boolean actual = sol.wordPatternMatch("abab", "redblueredblue"); 12 | assertTrue(actual); 13 | 14 | actual = sol.wordPatternMatch("aaaa", "asdasdasdasd"); 15 | assertTrue(actual); 16 | 17 | actual = sol.wordPatternMatch("aabb", "xyzabcxzyabc"); 18 | assertFalse(actual); 19 | } 20 | } -------------------------------------------------------------------------------- /tests/_400Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _400Test { 6 | 7 | @Test 8 | public void test() throws Exception { 9 | _400 sol = new _400(); 10 | StringBuilder actual = new StringBuilder(); 11 | StringBuilder expected = new StringBuilder(); 12 | for (int i = 1; i <= 500; i++) { 13 | actual.append((char) (sol.findNthDigit(i) + '0')); 14 | expected.append(i); 15 | } 16 | assertEquals(expected.toString().subSequence(0, 500), actual.toString()); 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /tests/_401Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | import static org.junit.Assert.assertEquals; 8 | 9 | public class _401Test { 10 | 11 | @Test 12 | public void test() throws Exception { 13 | _401 sol = new _401(); 14 | List actual = sol.readBinaryWatch(1); 15 | List expected = Arrays.asList("1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"); 16 | Collections.sort(actual); 17 | Collections.sort(expected); 18 | assertEquals(expected, actual); 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /tests/_403Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertFalse; 4 | import static org.junit.Assert.assertTrue; 5 | 6 | public class _403Test { 7 | 8 | @Test 9 | public void test() throws Exception { 10 | _403 sol = new _403(); 11 | assertTrue(sol.canCross(new int[]{0, 1, 3, 5, 6, 8, 12, 17})); 12 | assertFalse(sol.canCross(new int[]{0, 1, 2, 3, 4, 8, 9, 11})); 13 | assertFalse(sol.canCross(new int[]{0, 3})); 14 | assertTrue(sol.canCross(new int[]{0})); 15 | } 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /tests/_404Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _404Test { 6 | 7 | @Test 8 | public void test() throws Exception { 9 | _404 sol = new _404(); 10 | assertEquals(24, sol.sumOfLeftLeaves(Deserializer.deserializeTreeNode(new Integer[]{3, 9, 20, null, null, 15, 7}))); 11 | assertEquals(0, sol.sumOfLeftLeaves(Deserializer.deserializeTreeNode(new Integer[]{}))); 12 | assertEquals(0, sol.sumOfLeftLeaves(Deserializer.deserializeTreeNode(new Integer[]{100}))); 13 | } 14 | } -------------------------------------------------------------------------------- /tests/_405Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _405Test { 6 | 7 | @Test 8 | public void test() throws Exception { 9 | _405 sol = new _405(); 10 | assertEquals("1a", sol.toHex(26)); 11 | assertEquals("ffffffff", sol.toHex(-1)); 12 | assertEquals("0", sol.toHex(0)); 13 | } 14 | } -------------------------------------------------------------------------------- /tests/_407Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _407Test { 6 | 7 | @Test 8 | public void test() throws Exception { 9 | _407 sol = new _407(); 10 | int[][] map = { 11 | {1, 4, 3, 1, 3, 2,}, 12 | {3, 2, 1, 3, 2, 4,}, 13 | {2, 3, 3, 2, 3, 1,}, 14 | }; 15 | int actual = sol.trapRainWater(map); 16 | assertEquals(4, actual); 17 | 18 | 19 | map = new int[][]{ 20 | {1, 2}, 21 | {2, 1}, 22 | }; 23 | actual = sol.trapRainWater(map); 24 | assertEquals(0, actual); 25 | } 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /tests/_408Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertFalse; 4 | import static org.junit.Assert.assertTrue; 5 | 6 | public class _408Test { 7 | 8 | @Test 9 | public void test() throws Exception { 10 | _408 sol = new _408(); 11 | assertTrue(sol.validWordAbbreviation("internationalization", "i12iz4n")); 12 | assertFalse(sol.validWordAbbreviation("apple", "a2e")); 13 | assertFalse(sol.validWordAbbreviation("", "0")); 14 | assertFalse(sol.validWordAbbreviation("apple", "a0pple")); 15 | assertFalse(sol.validWordAbbreviation("apple", "a01ple")); 16 | } 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /tests/_409Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _409Test { 6 | 7 | @Test 8 | public void test() throws Exception { 9 | _409 sol = new _409(); 10 | assertEquals(7, sol.longestPalindrome("abccccdd")); 11 | assertEquals(1, sol.longestPalindrome("abc")); 12 | 13 | } 14 | } 15 | 16 | 17 | -------------------------------------------------------------------------------- /tests/_410Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _410Test { 6 | 7 | @Test 8 | public void test() throws Exception { 9 | _410 sol = new _410(); 10 | assertEquals(9, sol.splitArray(new int[]{1, 2, 3, 4, 5}, 2)); 11 | assertEquals(15, sol.splitArray(new int[]{5, 5, 5}, 1)); 12 | assertEquals(10, sol.splitArray(new int[]{5, 5, 5}, 2)); 13 | assertEquals(5, sol.splitArray(new int[]{5, 5, 5}, 3)); 14 | assertEquals(2147483647, sol.splitArray(new int[]{1, 2147483647}, 2)); 15 | } 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /tests/_411Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import static org.junit.Assert.assertTrue; 7 | 8 | public class _411Test { 9 | 10 | @Test 11 | public void test() throws Exception { 12 | _411 sol = new _411(); 13 | List expected = Arrays.asList("a4"); 14 | assertTrue(expected.contains(sol.minAbbreviation("apple", new String[]{"blade"}))); 15 | 16 | expected = Arrays.asList("1p3", "ap3", "a3e", "2p2", "3le", "3l1"); 17 | assertTrue(expected.contains(sol.minAbbreviation("apple", new String[]{"plain", "amber", "blade"}))); 18 | } 19 | } 20 | 21 | 22 | -------------------------------------------------------------------------------- /tests/_44Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _44Test { 6 | @Test 7 | public void test() throws Exception { 8 | _44 sol = new _44(); 9 | assertEquals(false, sol.isMatch("aa", "a")); 10 | assertEquals(true, sol.isMatch("aa", "aa")); 11 | assertEquals(false, sol.isMatch("aaa", "aa")); 12 | assertEquals(true, sol.isMatch("aaa", "*")); 13 | assertEquals(true, sol.isMatch("aaa", "a*")); 14 | assertEquals(true, sol.isMatch("ab", "??")); 15 | assertEquals(true, sol.isMatch("ab", "?*")); 16 | assertEquals(false, sol.isMatch("aab", "c*a*b")); 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /tests/_96Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | public class _96Test { 6 | 7 | @Test 8 | public void test() throws Exception { 9 | _96 sol = new _96(); 10 | assertEquals(1, sol.numTrees(0)); 11 | assertEquals(1, sol.numTrees(1)); 12 | assertEquals(2, sol.numTrees(2)); 13 | assertEquals(5, sol.numTrees(3)); 14 | } 15 | } --------------------------------------------------------------------------------