├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Challenges ├── 2020 │ ├── April-LeetCoding-Challenge.md │ ├── August-LeetCoding-Challenge.md │ ├── December-LeetCoding-Challenge.md │ ├── November-LeetCoding-Challenge.md │ └── September-LeetCoding-Challenge.md ├── 2021 │ ├── April-LeetCoding-Challenge.md │ ├── February-LeetCoding-Challenge.md │ ├── January-LeetCoding-Challenge.md │ ├── June-LeetCoding-Challenge.md │ ├── March-LeetCoding-Challenge.md │ └── May-LeetCoding-Challenge.md └── README.md ├── Easy ├── 1.TwoSum(optimized).py ├── 1.TwoSum.py ├── 100.SameTree.py ├── 1002.FindCommonCharacters.py ├── 1009.ComplementofBase10Integer.py ├── 101.SymmetricTree.py ├── 1021.RemoveOutermostParentheses.py ├── 1022.SumofRootToLeafBinaryNumbers.py ├── 1025.DivisorGame.py ├── 104.MaximumDepthofBinaryTree.py ├── 1047.RemoveAllAdjacentDuplicatesInString.py ├── 107.BinaryTreeLevelOrderTraversalII.py ├── 110.BalancedBinaryTree.py ├── 1103.DistributeCandiestoPeople.py ├── 1108.DefanginganIPAddress(join).py ├── 1108.DefanginganIPAddress(re.sub).py ├── 1108.DefanginganIPAddress(replace).py ├── 111.MinimumDepthofBinaryTree.py ├── 112.PathSum.py ├── 1122.RelativeSortArray.py ├── 1160.FindWordsThatCanBeFormedbyCharacters.py ├── 118.PascalsTriangle.py ├── 1189.MaximumNumberofBalloons.py ├── 119.PascalsTriangleII.py ├── 1200.MinimumAbsoluteDifference.py ├── 1207.UniqueNumberofOccurrences.py ├── 121.BestTimetoBuyandSellStock.py ├── 1217.MinimumCosttoMoveChipstoTheSamePosition.py ├── 1221.SplitaStringinBalancedStrings.py ├── 1237.FindPositiveIntegerSolutionforaGivenEquation.py ├── 125.ValidPalindromeReFindall.py ├── 125.ValidPalindromeReSub.py ├── 125.ValidPalindromeTwoPointer.py ├── 1252.CellswithOddValuesinaMatrix.py ├── 1260.Shift2DGrid.py ├── 1266.MinimumTimeVisitingAllPoints.py ├── 1287.ElementAppearingMoreThan25InSortedArray(binarySearch).py ├── 1287.ElementAppearingMoreThan25InSortedArray(for).py ├── 1290.ConvertBinaryNumberinaLinkedListtoInteger.py ├── 1299.ReplaceElementswithGreatestElementonRightSide.py ├── 13.RomantoInteger.py ├── 1304.FindNUniqueIntegersSumuptoZero.py ├── 1309.DecryptStringfromAlphabettoIntegerMapping.py ├── 1313.DecompressRun-LengthEncodedList.py ├── 1323.Maximum69Number.py ├── 1331.RankTransformofanArray.py ├── 1332.RemovePalindromicSubsequences.py ├── 1337.TheKWeakestRowsinaMatrix.py ├── 1342.NumberofStepstoReduceaNumbertoZero.py ├── 1351.CountNegativeNumbersinaSortedMatrix(binarySearch).py ├── 1351.CountNegativeNumbersinaSortedMatrix(nestedFor).py ├── 1351.CountNegativeNumbersinaSortedMatrix(nestedForOptimized).py ├── 1365.HowManyNumbersAreSmallerThantheCurrentNumber.py ├── 1370.IncreasingDecreasingString.py ├── 1374.GenerateaStringWithCharactersThatHaveOddCounts.py ├── 1380.LuckyNumbersinaMatrix.py ├── 1389.CreateTargetArrayintheGivenOrder.py ├── 14.LongestCommonPrefix.py ├── 1403.MinimumSubsequenceinNon-IncreasingOrder(list).py ├── 1403.MinimumSubsequenceinNon-IncreasingOrder.py ├── 141.LinkedListCycle(BruteForce).py ├── 141.LinkedListCycle.py ├── 1431.KidsWiththeGreatestNumberofCandies.py ├── 1436.DestinationCity(dict).py ├── 1436.DestinationCity(set).py ├── 1441.BuildanArrayWithStackOperations.py ├── 1446.ConsecutiveCharacters.py ├── 1450.NumberofStudentsDoingHomeworkataGivenTime.py ├── 1455.CheckIfaWordOccursAsaPrefixofAnyWordinaSentence.py ├── 1460.MakeTwoArraysEqualbyReversingSub-arrays.py ├── 1464.MaximumProductofTwoElementsinanArray.py ├── 1470.ShuffletheArray.py ├── 1475.FinalPricesWithaSpecialDiscountinaShop.py ├── 1480.RunningSumof1dArray(ListComprehension).py ├── 1480.RunningSumof1dArray.py ├── 1486.XOROperationinanArray.py ├── 1491.AverageSalaryExcludingtheMinimumandMaximumSalary.py ├── 1496.PathCrossing.py ├── 1502.CanMakeArithmeticProgressionFromSequence.py ├── 1507.ReformatDate(List).py ├── 1507.ReformatDate(String).py ├── 1512.NumberofGoodPairs(Dict).py ├── 1512.NumberofGoodPairs(For).py ├── 1518.WaterBottles.py ├── 1523.CountOddNumbersinanIntervalRange.py ├── 1528.ShuffleString(List).py ├── 1528.ShuffleString(String).py ├── 1534.CountGoodTriplets.py ├── 1539.KthMissingPositiveNumber.py ├── 1544.MakeTheStringGreat(Stack).py ├── 1544.MakeTheStringGreat(string).py ├── 1550.ThreeConsecutiveOdds.py ├── 1556.ThousandSeparator.py ├── 1566.DetectPatternofLengthMRepeatedKorMoreTimes.py ├── 1572.MatrixDiagonalSum.py ├── 1576.ReplaceAllQuestionmarkstoAvoidConsecutiveRepeatingCharacters.py ├── 1582.SpecialPositionsinaBinaryMatrix.py ├── 1588.SumofAllOddLengthSubarrays.py ├── 1592.RearrangeSpacesBetweenWords.py ├── 1598.CrawlerLogFolder.py ├── 160.IntersectionofTwoLinkedLists.py ├── 1603.DesignParkingSystem.py ├── 1614.MaximumNestingDepthoftheParentheses.py ├── 1619.MeanofArrayAfterRemovingSomeElements.py ├── 1624.LargestSubstringBetweenTwoEqualCharacters.py ├── 1629.SlowestKey.py ├── 1636.SortArraybyIncreasingFrequency.py ├── 1640.CheckArraFormationThroughConcatenation.py ├── 1646.GetMaximuminGeneratedArray(while).py ├── 1646.GetMaximuminGeneratedArray.py ├── 1652.DefusetheBomb.py ├── 1656.DesignanOrderedStream.py ├── 1662.CheckIfTwoStringArraysareEquivalent.py ├── 1668.MaximumRepeatingSubstring.py ├── 167.TwoSumII-Inputarrayissorted.py ├── 1672.RichestCustomerWealth.py ├── 1678.GoalParserInterpretation(replace).py ├── 1678.GoalParserInterpretation.py ├── 168.ExcelSheetColumnTitle.py ├── 1684.CounttheNumberofConsistentStrings.py ├── 1688.CountofMatchesinTournament.py ├── 1694.ReformatPhoneNumber.py ├── 1700.NumberofStudentsUnabletoEatLunch.py ├── 1704.DetermineifStringHalvesAreAlike.py ├── 171.ExcelSheetColumnNumber.py ├── 1710.MaximumUnitsonaTruck.py ├── 1716.CalculateMoneyinLeetcodeBank.py ├── 172.FactorialTrailingZeroes.py ├── 1720.DecodeXORedArray.py ├── 1725.NumberOfRectanglesThatCanFormTheLargestSquare.py ├── 1732.FindtheHighestAltitude.py ├── 1748.SumofUniqueElements.py ├── 1752.CheckifArrayIsSortedandRotated.py ├── 1773.CountItemsMatchingaRule.py ├── 1790.CheckifOneStringSwapCanMakeStringsEqual.py ├── 1796.SecondLargestDigitinaString.py ├── 1800.MaximumAscendingSubarraySum.py ├── 1805.NumberofDifferentIntegersinaString.py ├── 1812.DetermineColorofaChessboardSquare.py ├── 1816.TruncateSentence.py ├── 191.Numberof1Bits.py ├── 198.HouseRobber.py ├── 20.ValidParentheses(BruteForce).py ├── 20.ValidParentheses(Stack).py ├── 203.RemoveLinkedListElements.py ├── 204.CountPrimes.py ├── 205.IsomorphicStrings.py ├── 206.ReverseLinkedList(rightappr).py ├── 206.ReverseLinkedList.py ├── 21.MergeTwoSortedLists.py ├── 217.ContainsDuplicate(Dict).py ├── 219.ContainsDuplicateII.py ├── 225.ImplementStackusingQueues.py ├── 226.InvertBinaryTree.py ├── 232.ImplementQueueusingStacks.py ├── 234.PalindromeLinkedList.py ├── 237.DeleteNodeinaLinkedList.py ├── 242.ValidAnagram.py ├── 257.BinaryTreePaths.py ├── 258.AddDigits.py ├── 26.RemoveDuplicatesfromSortedArray.py ├── 268.MissingNumber.py ├── 27.RemoveElement.py ├── 290.WordPattern.py ├── 299.BullsandCows.py ├── 326.PowerofThree.py ├── 342.PowerofFour(BruteForce).py ├── 342.PowerofFour.py ├── 344.ReverseString.py ├── 345.ReverseVowelsofaString(list).py ├── 345.ReverseVowelsofaString(string).py ├── 35.SearchInsertPosition.py ├── 387.FirstUniqueCharacterinaString(BruteForce).py ├── 387.FirstUniqueCharacterinaString.py ├── 389.FindtheDifference(set).py ├── 389.FindtheDifference.py ├── 392.IsSubsequence.py ├── 404.SumofLeftLeaves.py ├── 409.LongestPalindrome.py ├── 412.FizzBuzz.py ├── 441.ArrangingCoins.py ├── 459.RepeatedSubstringPattern.py ├── 476.NumberComplement.py ├── 496.NextGreaterElementI.py ├── 500.KeyboardRow.py ├── 501.FindModeinBinarySearchTree.py ├── 509.FibonacciNumber(Dict).py ├── 509.FibonacciNumber(TwoVar).py ├── 509.FibonacciNumber(list).py ├── 520.DetectCapital.py ├── 530.MinimumAbsoluteDifferenceinBST.py ├── 538.ConvertBSTtoGreaterTree.py ├── 559.MaximumDepthofN-aryTree.py ├── 563.BinaryTreeTilt.py ├── 566.ReshapetheMatrix.py ├── 575.DistributeCandies.py ├── 58.LengthofLastWord(list).py ├── 58.LengthofLastWord(string).py ├── 589.N-aryTreePreorderTraversal.py ├── 590.N-aryTreePostorderTraversal.py ├── 594.LongestHarmoniousSubsequence(Counter).py ├── 594.LongestHarmoniousSubsequence(defaultdict).py ├── 599.MinimumIndexSumofTwoLists.py ├── 605.CanPlaceFlowers.py ├── 637.AverageofLevelsinBinaryTree.py ├── 645.SetMismatch.py ├── 653.TwoSumIV-InputisaBST.py ├── 657.RobotReturntoOrigin.py ├── 66.PlusOne.py ├── 665.Non-decreasingArray.py ├── 67.AddBinary.py ├── 671.SecondMinimumNodeInaBinaryTree.py ├── 674.LongestContinuousIncreasingSubsequence.py ├── 682.BaseballGame.py ├── 690.EmployeeImportance.py ├── 696.CountBinarySubstrings.py ├── 7.ReverseInteger.py ├── 700.SearchinaBinarySearchTree.py ├── 703.KthLargestElementinaStream.py ├── 705.DesignHashSet.py ├── 706.DesignHashMap.py ├── 709.ToLowerCase.py ├── 720.LongestWordinDictionary.py ├── 728.SelfDividingNumbers.py ├── 744.FindSmallestLetterGreaterThanTarget.py ├── 746.MinCostClimbingStairs.py ├── 771.JewelsandStones.py ├── 804.UniqueMorseCodeWords.py ├── 811.SubdomainVisitCount.py ├── 821.ShortestDistancetoaCharacter.py ├── 824.GoatLatin.py ├── 83.RemoveDuplicatesfromSortedList.py ├── 832.FlippinganImage(reverse).py ├── 832.FlippinganImage.py ├── 852.PeakIndexinaMountainArray(ListComprehension).py ├── 852.PeakIndexinaMountainArray(set).py ├── 859.BuddyStrings.py ├── 872.Leaf-SimilarTrees.py ├── 88.MergeSortedArray.py ├── 884.UncommonWordsfromTwoSentences.py ├── 896.MonotonicArray.py ├── 897.IncreasingOrderSearchTree.py ├── 9.PalindromeNumber.py ├── 905.SortArrayByParity.py ├── 908.SmallestRangeI.py ├── 922.SortArrayByParityII(Dictionary).py ├── 922.SortArrayByParityII(List).py ├── 922.SortArrayByParityII(TwoPointers).py ├── 929.UniqueEmailAddresses.py ├── 933.NumberofRecentCalls(BinarySearch).py ├── 933.NumberofRecentCalls(while).py ├── 933.NumberofRecentCalls(whilePop).py ├── 938.RangeSumofBST(Optimized).py ├── 938.RangeSumofBST.py ├── 941.ValidMountainArray.py ├── 949.LargestTimeforGivenDigits.py ├── 953.VerifyinganAlienDictionary.py ├── 961.N-RepeatedElementinSize2NArray(BruteForce).py ├── 961.N-RepeatedElementinSize2NArray.py ├── 965.UnivaluedBinaryTree.py ├── 970.PowerfulIntegers.py ├── 977.SquaresofaSortedArray.py ├── 989.AddtoArray-FormofInteger.py ├── 993.CousinsinBinaryTree.py └── 999.AvailableCapturesforRook.py ├── Hard ├── 1032.StreamofCharacters.py ├── 1095.FindinMountainArray.py ├── 123.BestTimetoBuyandSellStockIII.py ├── 1345.JumpGameIV.py ├── 145.BinaryTreePostorderTraversal.py ├── 1463.CherryPickupII.py ├── 154.FindMinimuminRotatedSortedArrayII.py ├── 164.MaximumGap.py ├── 23.MergekSortedLists.py ├── 25.ReverseNodesink-Group.py ├── 295.FindMedianfromDataStream(binarySearch).py ├── 295.FindMedianfromDataStream(bruteforce).py ├── 297.SerializeandDeserializeBinaryTree.py ├── 329.LongestIncreasingPathinaMatrix.py ├── 381.InsertDeleteGetRandomO(1)-Duplicatesallowed.py ├── 41.FirstMissingPositive.py ├── 432.AllOoneDataStructure.py ├── 458.PoorPigs.py ├── 57.InsertInterval.py ├── 895.MaximumFrequencyStack.py ├── 952.LargestComponentSizebyCommonFactor.py ├── 980.UniquePathsIII.py └── MedianofTwoSortedArrays.py ├── LICENSE ├── Medium ├── 1010.PairsofSongsWithTotalDurationsDivisibleby60.py ├── 1015.SmallestIntegerDivisiblebyK.py ├── 1019.NextGreaterNodeInLinkedList.py ├── 102.BinaryTreeLevelOrderTraversal.py ├── 1026.MaximumDifferenceBetweenNodeandAncestor.py ├── 103.BinaryTreeZigzagLevelOrderTraversal.py ├── 1038.BinarySearchTreetoGreaterSumTree.py ├── 1041.RobotBoundedInCircle.py ├── 1079.LetterTilePossibilities.py ├── 1091.ShortestPathinBinaryMatrix.py ├── 1094.CarPooling.py ├── 11.ContainerWithMostWater.py ├── 1123.LowestCommonAncestorofDeepestLeaves.py ├── 114.FlattenBinaryTreetoLinkedList.py ├── 116.PopulatingNextRightPointersinEachNode.py ├── 1161.MaximumLevelSumofaBinaryTree.py ├── 1169.InvalidTransactions.py ├── 117.PopulatingNextRightPointersinEachNodeII.py ├── 1171.RemoveZeroSumConsecutiveNodesfromLinkedList.py ├── 12.IntegertoRoman.py ├── 120.Triangle.py ├── 1227.AirplaneSeatAssignmentProbability.py ├── 1261.FindElementsinaContaminatedBinaryTree.py ├── 1268.SearchSuggestionsSystem.py ├── 128.LongestConsecutiveSequence.py ├── 1282.GroupthePeopleGiventheGroupSizeTheyBelongTo.py ├── 1283.FindtheSmallestDivisorGivenaThreshold.py ├── 1286.IteratorforCombination.py ├── 1288.RemoveCoveredIntervals.py ├── 129.SumRoottoLeafNumbers.py ├── 1291.SequentialDigits.py ├── 1302.DeepestLeavesSum.py ├── 1305.AllElementsinTwoBinarySearchTrees.py ├── 1306.JumpGameIII.py ├── 1311.GetWatchedVideosbyYourFriends.py ├── 1315.SumofNodeswithEven-ValuedGrandparent.py ├── 1325.DeleteLeavesWithaGivenValue.py ├── 1329.SorttheMatrixDiagonally.py ├── 1338.ReduceArraySizetoTheHalf.py ├── 134.GasStation.py ├── 1347.MinimumNumberofStepstoMakeTwoStringsAnagram.py ├── 1348.TweetCountsPerFrequency.py ├── 1352.ProductoftheLastKNumbers(BruteForce).py ├── 1352.ProductoftheLastKNumbers(MySolution).py ├── 1352.ProductoftheLastKNumbers(Revisited).py ├── 1357.ApplyDiscountEverynOrders(BruteForce).py ├── 1357.ApplyDiscountEverynOrders.py ├── 1361.ValidateBinaryTreeNodes.py ├── 1367.LinkedListinBinaryTree.py ├── 137.SingleNumberII.py ├── 1379.FindaCorrespondingNodeofaBinaryTreeinaCloneofThatTree(iteratively).py ├── 1379.FindaCorrespondingNodeofaBinaryTreeinaCloneofThatTree(recursion).py ├── 138.CopyListwithRandomPointer.py ├── 1381.DesignaStackWithIncrementOperation.py ├── 1387.SortIntegersbyThePowerValue.py ├── 139.WordBreak.py ├── 1395.CountNumberofTeams.py ├── 1396.DesignUndergroundSystem.py ├── 1409.QueriesonaPermutationWithKey.py ├── 1410.HTMLEntityParser.py ├── 1414.FindtheMinimumNumberofFibonacciNumbersWhoseSumIsK.py ├── 142.LinkedListCycleII.py ├── 1423.MaximumPointsYouCanObtainfromCards.py ├── 143.ReorderList.py ├── 1437.CheckIfAll1sAreatLeastLengthKPlacesAway.py ├── 144.BinaryTreePreorderTraversal.py ├── 1448.CountGoodNodesinBinaryTree(optimized).py ├── 1448.CountGoodNodesinBinaryTree.py ├── 1457.Pseudo-PalindromicPathsinaBinaryTree.py ├── 1461.CheckIfaStringContainsAllBinaryCodesofSizeK.py ├── 1465.MaximumAreaofaPieceofCakeAfterHorizontalandVerticalCuts.py ├── 147.InsertionSortList.py ├── 1472.DesignBrowserHistory(Dictionary).py ├── 1472.DesignBrowserHistory.py ├── 1476.SubrectangleQueries.py ├── 148.SortList.py ├── 1487.MakingFileNamesUnique.py ├── 1492.ThekthFactorofn.py ├── 15.3Sum(bruteforce).py ├── 150.EvaluateReversePolishNotation.py ├── 152.MaximumProductSubarray.py ├── 153.FindMinimuminRotatedSortedArray(BinarySearch).py ├── 153.FindMinimuminRotatedSortedArray(forLoop).py ├── 1545.FindKthBitinNthBinaryString.py ├── 1551.MinimumOperationstoMakeArrayEqual.py ├── 1557.MinimumNumberofVerticestoReachAllNodes.py ├── 1561.MaximumNumberofCoinsYouCanGet.py ├── 1567.MaximumLengthofSubarrayWithPositiveProduct.py ├── 16.3SumClosest(bruteforce).py ├── 1609.EvenOddTree.py ├── 162.FindPeakElement.py ├── 1630.ArithmeticSubarrays.py ├── 1631.PathWithMinimumEffort.py ├── 1637.WidestVerticalAreaBetweenTwoPointsContainingNoPoints.py ├── 1641.CountSortedVowelStrings.py ├── 165.CompareVersionNumbers.py ├── 1657.DetermineifTwoStringsAreClose.py ├── 1658.MinimumOperationstoReduceXtoZero.py ├── 1663.SmallestStringWithAGivenNumericValue.py ├── 1669.MergeInBetweenLinkedLists.py ├── 1670.DesignFrontMiddleBackQueue.py ├── 1673.FindtheMostCompetitiveSubsequence.py ├── 1679.MaxNumberofK-SumPairs.py ├── 1680.ConcatenationofConsecutiveBinaryNumbers.py ├── 1685.SumofAbsoluteDifferencesinaSortedArray.py ├── 1689.PartitioningIntoMinimumNumberOfDeci-BinaryNumbers.py ├── 1695.MaximumErasureValue.py ├── 17.LetterCombinationsofaPhoneNumber.py ├── 1721.SwappingNodesinaLinkedList.py ├── 173.BinarySearchTreeIterator.py ├── 179.LargestNumber.py ├── 1791.FindCenterofStarGraph.py ├── 19.RemoveNthNodeFromEndofList.py ├── 199.BinaryTreeRightSideView.py ├── 2.AddTwoNumbers.py ├── 208.ImplementTrie(PrefixTree).py ├── 209.MinimumSizeSubarraySum.py ├── 211.AddandSearchWord-Datastructuredesign.py ├── 215.KthLargestElementinanArray.py ├── 216.CombinationSumIII.py ├── 220.ContainsDuplicateIII.py ├── 222.CountCompleteTreeNodes.py ├── 227.BasicCalculatorII.py ├── 228.SummaryRanges.py ├── 229.MajorityElementII(BruteForce).py ├── 229.MajorityElementII.py ├── 230.KthSmallestElementinaBST.py ├── 24.SwapNodesinPairs.py ├── 240.Searcha2DMatrixII.py ├── 260.SingleNumberIII.py ├── 274.H-Index.py ├── 275.H-IndexII.py ├── 284.PeekingIterator.py ├── 289.GameofLife.py ├── 29.DivideTwoIntegers.py ├── 3.LongestSubstringWithoutRepeatingCharacters.py ├── 304.RangeSumQuery2D-Immutable(bruteforce).py ├── 304.RangeSumQuery2D-Immutable(bruteforce2).py ├── 307.RangeSumQuery - Mutable.py ├── 318.MaximumProductofWordLengths.py ├── 328.OddEvenLinkedList.py ├── 334.IncreasingTripletSubsequence.py ├── 34.FindFirstandLastPositionofElementinSortedArray(BinarySearch).py ├── 34.FindFirstandLastPositionofElementinSortedArray.py ├── 341.FlattenNestedListIterator.py ├── 347.TopKFrequentElements.py ├── 355.DesignTwitter.py ├── 36.ValidSudoku.py ├── 376.WiggleSubsequence.py ├── 378.KthSmallestElementinaSortedMatrix.py ├── 380.InsertDeleteGetRandomO(1).py ├── 382.LinkedListRandomNode.py ├── 384.ShuffleanArray.py ├── 394.DecodeString.py ├── 395.LongestSubstringwithAtLeastKRepeatingCharacters.py ├── 398.RandomPickIndex.py ├── 399.EvaluateDivision.py ├── 402.RemoveKDigits.py ├── 421.MaximumXORofTwoNumbersinanArray.py ├── 423.ReconstructOriginalDigitsfromEnglish.py ├── 429.N-aryTreeLevelOrderTraversal.py ├── 435.Non-overlappingIntervals.py ├── 436.FindRightInterval.py ├── 437.PathSumIII.py ├── 442.FindAllDuplicatesinanArray.py ├── 445.AddTwoNumbersII.py ├── 449.SerializeandDeserializeBST.py ├── 450.DeleteNodeinaBST.py ├── 451.SortCharactersByFrequency.py ├── 452.MinimumNumberofArrowstoBurstBalloons.py ├── 454.4SumII.py ├── 456.132Pattern.py ├── 46.Permutations.py ├── 462.MinimumMovestoEqualArrayElementsII.py ├── 468.ValidateIPAddress.py ├── 47.PermutationsII.py ├── 470.ImplementRand10()UsingRand7().py ├── 478.GenerateRandomPointinaCircle.py ├── 48.RotateImage.py ├── 495.TeemoAttacking.py ├── 497.RandomPointinNon-overlappingRectangles.py ├── 498.DiagonalTraverse.py ├── 5.LongestPalindromicSubstring(bruteforce).py ├── 50.Pow(x,n).py ├── 503.NextGreaterElementII.py ├── 513.FindBottomLeftTreeValue.py ├── 515.FindLargestValueinEachTreeRow.py ├── 524.LongestWordinDictionarythroughDeleting.py ├── 526.BeautifulArrangement.py ├── 532.K-diffPairsinanArray.py ├── 535.EncodeandDecodeTinyURL.py ├── 54.SpiralMatrix.py ├── 540.SingleElementinaSortedArray.py ├── 554.BrickWall.py ├── 556.NextGreaterElementIII.py ├── 56.MergeIntervals.py ├── 581.ShortestUnsortedContinuousSubarray.py ├── 59.SpiralMatrixII.py ├── 593.ValidSquare.py ├── 609.FindDuplicateFileinSystem.py ├── 61.RotateList.py ├── 622.DesignCircularQueue.py ├── 623.AddOneRowtoTree.py ├── 63.UniquePathsII.py ├── 641.DesignCircularDeque.py ├── 647.PalindromicSubstrings.py ├── 654.MaximumBinaryTree.py ├── 658.FindKClosestElements.py ├── 667.BeautifulArrangementII.py ├── 677.MapSumPairs.py ├── 695.MaxAreaofIsland.py ├── 701.InsertintoaBinarySearchTree.py ├── 707.DesignLinkedList.py ├── 71.SimplifyPath.py ├── 713.SubarrayProductLessThanK.py ├── 722.RemoveComments.py ├── 729.MyCalendarI.py ├── 73.SetMatrixZeroes.py ├── 735.AsteroidCollision.py ├── 74.Searcha2DMatrix.py ├── 75.SortColors(BubleSort).py ├── 75.SortColors(InsertionSort).py ├── 75.SortColors(MergeSort).py ├── 75.SortColors(QuickSort).py ├── 75.SortColors(SelectionSort).py ├── 754.ReachaNumber.py ├── 763.PartitionLabels(bruteforce).py ├── 775.GlobalandLocalInversions.py ├── 78.Subsets.py ├── 785.IsGraphBipartite.py ├── 791.CustomSortString.py ├── 80.RemoveDuplicatesfromSortedArrayII.py ├── 807.MaxIncreasetoKeepCitySkyline.py ├── 81.SearchinRotatedSortedArrayII.py ├── 817.LinkedListComponents(set).py ├── 817.LinkedListComponents.py ├── 82.RemoveDuplicatesfromSortedListII.py ├── 820.ShortEncodingofWords.py ├── 835.ImageOverlap.py ├── 841.KeysandRooms.py ├── 845.LongestMountaininArray.py ├── 849.MaximizeDistancetoClosestPerson.py ├── 858.MirrorReflection.py ├── 86.PartitionList.py ├── 865.SmallestSubtreewithalltheDeepestNodes.py ├── 869.ReorderedPowerof2.py ├── 880.DecodedStringatIndex.py ├── 881.BoatstoSavePeople.py ├── 890.FindandReplacePattern.py ├── 900.RLEIterator.py ├── 910.SmallestRangeII.py ├── 911.OnlineElection.py ├── 912.SortanArray.py ├── 916.WordSubsets.py ├── 92.ReverseLinkedListII.py ├── 923.3SumWithMultiplicity.py ├── 94.BinaryTreeInorderTraversal.py ├── 946.ValidateStackSequences.py ├── 966.VowelSpellchecker.py ├── 967.NumbersWithSameConsecutiveDifferences.py ├── 969.PancakeSorting.py ├── 98.ValidateBinarySearchTree(2nd).py ├── 98.ValidateBinarySearchTree.py ├── 981.TimeBasedKey-ValueStore.py ├── 987.VerticalOrderTraversalofaBinaryTree.py ├── 991.BrokenCalculator.py └── 994.RottingOranges.py └── README.md /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute to "Python Solutions of LeetCode Problems" 2 | 3 | coming soon 4 | -------------------------------------------------------------------------------- /Challenges/README.md: -------------------------------------------------------------------------------- 1 | # LeetCoding Challenges 2 | 2020: 3 | - [April LeetCoding Challenge](/Challenges/2020/April-LeetCoding-Challenge.md) 4 | - [August LeetCoding Challenge](/Challenges/2020/August-LeetCoding-Challenge.md) 5 | - [September LeetCoding Challenge](/Challenges/2020/September-LeetCoding-Challenge.md) 6 | - [November LeetCoding Challenge](/Challenges/2020/November-LeetCoding-Challenge.md) 7 | - [December LeetCoding Challenge](/Challenges/2020/December-LeetCoding-Challenge.md) 8 | 9 | 2021: 10 | - [January LeetCoding Challenge](/Challenges/2021/January-LeetCoding-Challenge.md) 11 | - [February LeetCoding Challenge](/Challenges/2021/February-LeetCoding-Challenge.md) 12 | - [March LeetCoding Challenge](/Challenges/2021/March-LeetCoding-Challenge.md) 13 | - [April LeetCoding Challenge](/Challenges/2021/April-LeetCoding-Challenge.md) 14 | - [May LeetCoding Challenge](/Challenges/2021/May-LeetCoding-Challenge.md) 15 | - [June LeetCoding Challenge](/Challenges/2021/June-LeetCoding-Challenge.md) 16 | -------------------------------------------------------------------------------- /Easy/1.TwoSum(optimized).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums and an integer target, return 3 | indices of the two numbers such that they add up to target. 4 | 5 | You may assume that each input would have exactly one solution, 6 | and you may not use the same element twice. 7 | 8 | You can return the answer in any order. 9 | 10 | Example: 11 | Input: nums = [2,7,11,15], target = 9 12 | Output: [0,1] 13 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 14 | 15 | Example: 16 | Input: nums = [3,2,4], target = 6 17 | Output: [1,2] 18 | 19 | Example: 20 | Input: nums = [3,3], target = 6 21 | Output: [0,1] 22 | 23 | Constraints: 24 | - 2 <= nums.length <= 10^3 25 | - -10^9 <= nums[i] <= 10^9 26 | - -10^9 <= target <= 10^9 27 | - Only one valid answer exists. 28 | """ 29 | #Difficulty: Easy 30 | #52 / 52 test cases passed. 31 | #Runtime: 40 ms 32 | #Memory Usage: 14.6 MB 33 | 34 | #Runtime: 40 ms, faster than 96.53% of Python3 online submissions for Two Sum. 35 | #Memory Usage: 14.6 MB, less than 59.48% of Python3 online submissions for Two Sum. 36 | 37 | class Solution: 38 | def twoSum(self, nums: List[int], target: int) -> List[int]: 39 | for i, n in enumerate(nums): 40 | if target-n in nums[i+1:]: 41 | return i, i+1+nums[i+1:].index(target-n) 42 | -------------------------------------------------------------------------------- /Easy/1.TwoSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, return indices of the two numbers such that they 3 | add up to a specific target. 4 | You may assume that each input would have exactly one solution, and you may 5 | not use the same element twice. 6 | 7 | Example: 8 | Given nums = [2, 7, 11, 15], target = 9, 9 | Because nums[0] + nums[1] = 2 + 7 = 9, 10 | return [0, 1]. 11 | """ 12 | #Difficulty: Easy 13 | #29 / 29 test cases passed. 14 | #Runtime: 1172 ms 15 | #Memory Usage: 14.7 MB 16 | 17 | #Runtime: 1152 ms, faster than 27.16% of Python3 online submissions for Two Sum. 18 | #Memory Usage: 14.6 MB, less than 18.14% of Python3 online submissions for Two Sum. 19 | 20 | class Solution: 21 | def twoSum(self, nums: List[int], target: int) -> List[int]: 22 | l = len(nums) 23 | for i in range(l): 24 | n = nums[i] 25 | d = target - n 26 | if d in nums[i+1:]: 27 | return [nums.index(n), i + nums[i+1:].index(d) + 1] 28 | -------------------------------------------------------------------------------- /Easy/1025.DivisorGame.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Alice and Bob take turns playing a game, with Alice 3 | starting first. 4 | 5 | Initially, there is a number N on the chalkboard. 6 | On each player's turn, that player makes a move consisting 7 | of: 8 | - Choosing any x with 0 < x < N and N % x == 0. 9 | - Replacing the number N on the chalkboard with N - x. 10 | 11 | Also, if a player cannot make a move, they lose the game. 12 | 13 | Return True if and only if Alice wins the game, assuming 14 | both players play optimally. 15 | 16 | Example: 17 | Input: 2 18 | Output: true 19 | Explanation: Alice chooses 1, and Bob has no more moves. 20 | 21 | Example: 22 | Input: 3 23 | Output: false 24 | Explanation: Alice chooses 1, Bob chooses 1, and Alice 25 | has no more moves. 26 | 27 | Note: 28 | 1. 1 <= N <= 1000 29 | ''' 30 | #Difficulty: Easy 31 | #40 / 40 test cases passed. 32 | #Runtime: 28 ms 33 | #Memory Usage: 14.2 MB 34 | 35 | #Runtime: 28 ms, faster than 79.57% of Python3 online submissions for Divisor Game. 36 | #Memory Usage: 14.2 MB, less than 51.41% of Python3 online submissions for Divisor Game. 37 | 38 | class Solution: 39 | def divisorGame(self, N: int) -> bool: 40 | return not N % 2 41 | -------------------------------------------------------------------------------- /Easy/104.MaximumDepthofBinaryTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, find its maximum depth. 3 | The maximum depth is the number of nodes along the longest path from the 4 | root node down to the farthest leaf node. 5 | 6 | Note: A leaf is a node with no children. 7 | 8 | Example: 9 | Given binary tree [3,9,20,null,null,15,7], 10 | 11 | 3 12 | / \ 13 | 9 20 14 | / \ 15 | 15 7 16 | return its depth = 3. 17 | """ 18 | #Difficulty: Easy 19 | #39 / 39 test cases passed. 20 | #Runtime: 28 ms 21 | #Memory Usage: 15.3 MB 22 | 23 | #Runtime: 28 ms, faster than 99.81% of Python3 online submissions for Maximum Depth of Binary Tree. 24 | #Memory Usage: 15.3 MB, less than 68.94% of Python3 online submissions for Maximum Depth of Binary Tree. 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, val=0, left=None, right=None): 29 | # self.val = val 30 | # self.left = left 31 | # self.right = right 32 | 33 | class Solution: 34 | def maxDepth(self, root: TreeNode) -> int: 35 | if not root: 36 | return 0 37 | left = self.maxDepth(root.left) 38 | right = self.maxDepth(root.right) 39 | return left + 1 if left > right else right + 1 40 | -------------------------------------------------------------------------------- /Easy/1108.DefanginganIPAddress(join).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 3 | A defanged IP address replaces every period "." with "[.]". 4 | 5 | Example: 6 | Input: address = "1.1.1.1" 7 | Output: "1[.]1[.]1[.]1" 8 | 9 | Constraints: 10 | - The given address is a valid IPv4 address. 11 | """ 12 | #Difficulty: Easy 13 | #62 / 62 test cases passed. 14 | #Runtime: 64 ms 15 | #Memory Usage: 13.9 MB 16 | 17 | #Runtime: 64 ms, faster than 6.22% of Python3 online submissions for Defanging an IP Address. 18 | #Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Defanging an IP Address. 19 | 20 | class Solution: 21 | def defangIPaddr(self, address: str) -> str: 22 | return '[.]'.join(address.split('.')) 23 | -------------------------------------------------------------------------------- /Easy/1108.DefanginganIPAddress(re.sub).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 3 | A defanged IP address replaces every period "." with "[.]". 4 | 5 | Example: 6 | Input: address = "1.1.1.1" 7 | Output: "1[.]1[.]1[.]1" 8 | 9 | Constraints: 10 | - The given address is a valid IPv4 address. 11 | """ 12 | #Difficulty: Easy 13 | #62 / 62 test cases passed. 14 | #Runtime: 48 ms 15 | #Memory Usage: 13.9 MB 16 | 17 | #Runtime: 48 ms, faster than 6.22% of Python3 online submissions for Defanging an IP Address. 18 | #Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Defanging an IP Address. 19 | 20 | import re 21 | class Solution: 22 | def defangIPaddr(self, address: str) -> str: 23 | return re.sub("\.", "[.]", address) 24 | -------------------------------------------------------------------------------- /Easy/1108.DefanginganIPAddress(replace).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 3 | A defanged IP address replaces every period "." with "[.]". 4 | 5 | Example: 6 | Input: address = "1.1.1.1" 7 | Output: "1[.]1[.]1[.]1" 8 | 9 | Constraints: 10 | - The given address is a valid IPv4 address. 11 | """ 12 | #Difficulty: Easy 13 | #62 / 62 test cases passed. 14 | #Runtime: 28 ms 15 | #Memory Usage: 13.6 MB 16 | 17 | #Runtime: 28 ms, faster than 72.89% of Python3 online submissions for Defanging an IP Address. 18 | #Memory Usage: 13.6 MB, less than 100.00% of Python3 online submissions for Defanging an IP Address. 19 | 20 | class Solution: 21 | def defangIPaddr(self, address: str) -> str: 22 | return address.replace('.', '[.]') 23 | -------------------------------------------------------------------------------- /Easy/111.MinimumDepthofBinaryTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, find its minimum depth. 3 | The minimum depth is the number of nodes along the shortest path from the 4 | root node down to the nearest leaf node. 5 | 6 | Note: A leaf is a node with no children. 7 | 8 | Example: 9 | Given binary tree [3,9,20,null,null,15,7], 10 | 11 | 3 12 | / \ 13 | 9 20 14 | / \ 15 | 15 7 16 | return its minimum depth = 2. 17 | """ 18 | #Difficulty: Easy 19 | #41 / 41 test cases passed. 20 | #Runtime: 36 ms 21 | #Memory Usage: 15.8 MB 22 | 23 | #Runtime: 36 ms, faster than 96.45% of Python3 online submissions for Minimum Depth of Binary Tree. 24 | #Memory Usage: 15.8 MB, less than 19.03% of Python3 online submissions for Minimum Depth of Binary Tree. 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, val=0, left=None, right=None): 29 | # self.val = val 30 | # self.left = left 31 | # self.right = right 32 | 33 | class Solution: 34 | def minDepth(self, root: TreeNode) -> int: 35 | if not root: 36 | return 0 37 | left = self.minDepth(root.left) 38 | right = self.minDepth(root.right) 39 | if left and right and left < right or right == 0: 40 | return left + 1 41 | else: 42 | return right + 1 43 | -------------------------------------------------------------------------------- /Easy/1122.RelativeSortArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all 3 | elements in arr2 are also in arr1. 4 | Sort the elements of arr1 such that the relative ordering of items in arr1 5 | are the same as in arr2. Elements that don't appear in arr2 should be 6 | placed at the end of arr1 in ascending order. 7 | 8 | Example: 9 | Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] 10 | Output: [2,2,2,1,4,3,3,9,6,7,19] 11 | 12 | Constraints: 13 | - arr1.length, arr2.length <= 1000 14 | - 0 <= arr1[i], arr2[i] <= 1000 15 | - Each arr2[i] is distinct. 16 | - Each arr2[i] is in arr1. 17 | """ 18 | #Difficulty: Easy 19 | #16 / 16 test cases passed. 20 | #Runtime: 48 ms 21 | #Memory Usage: 13.9 MB 22 | 23 | #Runtime: 48 ms, faster than 51.84% of Python3 online submissions for Relative Sort Array. 24 | #Memory Usage: 13.9 MB, less than 67.55% of Python3 online submissions for Relative Sort Array. 25 | 26 | class Solution: 27 | def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: 28 | head = [] 29 | tail = [] 30 | diff = list(set(arr1).difference(set(arr2))) 31 | for num in arr2: 32 | head.extend([num] * arr1.count(num)) 33 | for num in diff: 34 | tail.extend([num] * arr1.count(num)) 35 | return head + sorted(tail) 36 | -------------------------------------------------------------------------------- /Easy/118.PascalsTriangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-negative integer numRows, generate the first numRows of 3 | Pascal's triangle. 4 | In Pascal's triangle, each number is the sum of the two numbers directly 5 | above it. 6 | 7 | Example: 8 | Input: 5 9 | Output: 10 | [ 11 | [1], 12 | [1,1], 13 | [1,2,1], 14 | [1,3,3,1], 15 | [1,4,6,4,1] 16 | ] 17 | """ 18 | #Difficulty: Easy 19 | #15 / 15 test cases passed. 20 | #Runtime: 28 ms 21 | #Memory Usage: 13.6 MB 22 | 23 | #Runtime: 28 ms, faster than 72.51% of Python3 online submissions for Pascal's Triangle. 24 | #Memory Usage: 13.6 MB, less than 7.14% of Python3 online submissions for Pascal's Triangle. 25 | 26 | class Solution: 27 | def generate(self, numRows: int) -> List[List[int]]: 28 | if not numRows: return None 29 | triangle = [[1]] 30 | for n in range(1, numRows): 31 | t = triangle[n-1] 32 | l = [t[0], t[-1]] 33 | while len(l) < n+1: 34 | for i in range(1, len(t)): 35 | l.insert(len(l) - 1, t[i-1] + t[i]) 36 | triangle.extend([l]) 37 | return triangle 38 | -------------------------------------------------------------------------------- /Easy/1189.MaximumNumberofBalloons.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string text, you want to use the characters of text to form as 3 | many instances of the word "balloon" as possible. 4 | 5 | You can use each character in text at most once. Return the maximum 6 | number of instances that can be formed. 7 | 8 | Example: 9 | Input: text = "nlaebolko" 10 | Output: 1 11 | 12 | Example: 13 | Input: text = "loonbalxballpoon" 14 | Output: 2 15 | 16 | Example: 17 | Input: text = "leetcode" 18 | Output: 0 19 | 20 | Constraints: 21 | - 1 <= text.length <= 10^4 22 | - text consists of lower case English letters only. 23 | """ 24 | #Difficulty: Easy 25 | #23 / 23 test cases passed. 26 | #Runtime: 32 ms 27 | #Memory Usage: 14.3 MB 28 | 29 | #Runtime: 32 ms, faster than 67.90% of Python3 online submissions for Maximum Number of Balloons. 30 | #Memory Usage: 14.3 MB, less than 53.34% of Python3 online submissions for Maximum Number of Balloons. 31 | 32 | class Solution: 33 | def maxNumberOfBalloons(self, text: str) -> int: 34 | balloons = float(inf) 35 | for char in 'balon': 36 | if char in 'lo': 37 | balloons = min(balloons, text.count(char) // 2) 38 | else: 39 | balloons = min(balloons, text.count(char)) 40 | return balloons 41 | -------------------------------------------------------------------------------- /Easy/119.PascalsTriangleII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-negative index k where k ≤ 33, return the kth index row of the 3 | Pascal's triangle. 4 | Note that the row index starts from 0. 5 | 6 | In Pascal's triangle, each number is the sum of the two numbers directly 7 | above it. 8 | 9 | Example: 10 | Input: 3 11 | Output: [1,3,3,1] 12 | Follow up: 13 | 14 | Could you optimize your algorithm to use only O(k) extra space? 15 | """ 16 | #Difficulty: Easy 17 | #34 / 34 test cases passed. 18 | #Runtime: 24 ms 19 | #Memory Usage: 13.8 MB 20 | 21 | #Runtime: 24 ms, faster than 92.36% of Python3 online submissions for Pascal's Triangle II. 22 | #Memory Usage: 13.8 MB, less than 7.69% of Python3 online submissions for Pascal's Triangle II. 23 | 24 | class Solution: 25 | def getRow(self, rowIndex: int) -> List[int]: 26 | triangle = [[1]] 27 | for n in range(1, rowIndex+1): 28 | t = triangle[n-1] 29 | l = [t[0], t[-1]] 30 | while len(l) < n+1: 31 | for i in range(1, len(t)): 32 | l.insert(len(l) - 1, t[i-1] + t[i]) 33 | triangle.extend([l]) 34 | return triangle[-1] 35 | -------------------------------------------------------------------------------- /Easy/1207.UniqueNumberofOccurrences.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers arr, write a function that returns true if and 3 | only if the number of occurrences of each value in the array is unique. 4 | 5 | Example: 6 | Input: arr = [1,2,2,1,1,3] 7 | Output: true 8 | Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two 9 | values have the same number of occurrences. 10 | 11 | Example: 12 | Input: arr = [1,2] 13 | Output: false 14 | 15 | Example: 16 | Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] 17 | Output: true 18 | 19 | Constraints: 20 | - 1 <= arr.length <= 1000 21 | - -1000 <= arr[i] <= 1000 22 | """ 23 | #Difficulty: Easy 24 | #63 / 63 test cases passed. 25 | #Runtime: 48 ms 26 | #Memory Usage: 13.8 MB 27 | 28 | #Runtime: 48 ms, faster than 39.33% of Python3 online submissions for Unique Number of Occurrences. 29 | #Memory Usage: 13.8 MB, less than 92.46% of Python3 online submissions for Unique Number of Occurrences. 30 | 31 | class Solution: 32 | def uniqueOccurrences(self, arr: List[int]) -> bool: 33 | digits = {} 34 | for d in arr: 35 | if d not in digits: 36 | digits[d] = 0 37 | digits[d] += 1 38 | return len(digits.keys()) == len(set(digits.values())) 39 | -------------------------------------------------------------------------------- /Easy/121.BestTimetoBuyandSellStock.py: -------------------------------------------------------------------------------- 1 | """ 2 | Say you have an array for which the ith element is the price of a given 3 | stock on day i. 4 | If you were only permitted to complete at most one transaction (i.e., buy 5 | one and sell one share of the stock), design an algorithm to find the 6 | maximum profit. 7 | Note that you cannot sell a stock before you buy one. 8 | 9 | Example: 10 | Input: [7,1,5,3,6,4] 11 | Output: 5 12 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), 13 | profit = 6-1 = 5. 14 | Not 7-1 = 6, as selling price needs to be larger than buying 15 | price. 16 | 17 | Example: 18 | Input: [7,6,4,3,1] 19 | Output: 0 20 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 21 | """ 22 | #Difficulty: Easy 23 | #200 / 200 test cases passed. 24 | #Runtime: 64 ms 25 | #Memory Usage: 15.2 MB 26 | 27 | #Runtime: 64 ms, faster than 80.54% of Python3 online submissions for Best Time to Buy and Sell Stock. 28 | #Memory Usage: 15.2 MB, less than 33.70% of Python3 online submissions for Best Time to Buy and Sell Stock. 29 | 30 | class Solution: 31 | def maxProfit(self, prices: List[int]) -> int: 32 | buy = float(inf) 33 | sell = 0 34 | for price in prices: 35 | buy = min(buy, price) 36 | sell = max(sell, price - buy) 37 | return sell 38 | -------------------------------------------------------------------------------- /Easy/1221.SplitaStringinBalancedStrings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Balanced strings are those who have equal quantity of 'L' and 'R' characters. 3 | Given a balanced string s split it in the maximum amount of balanced strings. 4 | Return the maximum amount of splitted balanced strings. 5 | 6 | Example: 7 | Input: s = "RLRRLLRLRL" 8 | Output: 4 9 | Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring 10 | contains same number of 'L' and 'R'. 11 | 12 | Example: 13 | Input: s = "RLLLLRRRLR" 14 | Output: 3 15 | Explanation: s can be split into "RL", "LLLRRR", "LR", each substring 16 | contains same number of 'L' and 'R'. 17 | 18 | Constraints: 19 | - 1 <= s.length <= 1000 20 | - s[i] = 'L' or 'R' 21 | """ 22 | #Diffculty: Easy 23 | #40 / 40 test cases passed. 24 | #Runtime: 36 ms 25 | #Memory Usage: 13.9 MB 26 | 27 | #Runtime: 36 ms, faster than 42.16% of Python3 online submissions for Split a String in Balanced Strings. 28 | #Memory Usage: 13.9 MB, less than 37.65% of Python3 online submissions for Split a String in Balanced Strings. 29 | 30 | class Solution: 31 | def balancedStringSplit(self, s: str) -> int: 32 | count = 0 33 | stack = [] 34 | d = {'R' : 'L', 'L' : 'R'} 35 | for c in s: 36 | if c not in stack: 37 | stack.append(d[c]) 38 | continue 39 | stack.pop() 40 | if not stack: 41 | count += 1 42 | return count 43 | -------------------------------------------------------------------------------- /Easy/125.ValidPalindromeReFindall.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, determine if it is a palindrome, considering only 3 | alphanumeric characters and ignoring cases. 4 | Note: For the purpose of this problem, we define empty string as valid 5 | palindrome. 6 | 7 | Example: 8 | Input: "A man, a plan, a canal: Panama" 9 | Output: true 10 | """ 11 | #Difficulty: Easy 12 | #476 / 476 test cases passed. 13 | #Runtime: 40 ms 14 | #Memory Usage: 15 MB 15 | 16 | #Runtime: 40 ms, faster than 88.62% of Python3 online submissions for Valid Palindrome. 17 | #Memory Usage: 15 MB, less than 9.52% of Python3 online submissions for Valid Palindrome. 18 | 19 | import re 20 | class Solution: 21 | def isPalindrome(self, s: str) -> bool: 22 | s = ''.join(re.findall(r'\w+', s)).lower() 23 | length = len(s) 24 | mid = length//2 25 | left = s[:mid] 26 | return left[::-1] == s[mid+1:] if length % 2 != 0 else left[::-1] == s[mid:] 27 | -------------------------------------------------------------------------------- /Easy/125.ValidPalindromeReSub.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, determine if it is a palindrome, considering only 3 | alphanumeric characters and ignoring cases. 4 | Note: For the purpose of this problem, we define empty string as valid 5 | palindrome. 6 | 7 | Example: 8 | Input: "A man, a plan, a canal: Panama" 9 | Output: true 10 | """ 11 | #Difficulty: Easy 12 | #476 / 476 test cases passed. 13 | #Runtime: 44 ms 14 | #Memory Usage: 15.4 MB 15 | 16 | #Runtime: 44 ms, faster than 78.91% of Python3 online submissions for Valid Palindrome. 17 | #Memory Usage: 15.4 MB, less than 9.52% of Python3 online submissions for Valid Palindrome. 18 | 19 | import re 20 | class Solution: 21 | def isPalindrome(self, s: str) -> bool: 22 | s = re.sub(r'\W', '', s).lower() 23 | return s == s[::-1] 24 | -------------------------------------------------------------------------------- /Easy/125.ValidPalindromeTwoPointer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, determine if it is a palindrome, considering only 3 | alphanumeric characters and ignoring cases. 4 | Note: For the purpose of this problem, we define empty string as valid 5 | palindrome. 6 | 7 | Example: 8 | Input: "A man, a plan, a canal: Panama" 9 | Output: true 10 | """ 11 | #Difficulty: Easy 12 | #476 / 476 test cases passed. 13 | #Runtime: 60 ms 14 | #Memory Usage: 14.1 MB 15 | 16 | #Runtime: 60 ms, faster than 25.38% of Python3 online submissions for Valid Palindrome. 17 | #Memory Usage: 14.1 MB, less than 48.81% of Python3 online submissions for Valid Palindrome. 18 | 19 | class Solution: 20 | def isPalindrome(self, s: str) -> bool: 21 | i = 0 22 | j = len(s)-1 23 | while i < j: 24 | if s[i].isalnum(): 25 | if s[j].isalnum(): 26 | if s[i].lower() == s[j].lower(): 27 | i += 1 28 | j -= 1 29 | else: 30 | return False 31 | else: 32 | j -= 1 33 | else: 34 | i += 1 35 | return True 36 | -------------------------------------------------------------------------------- /Easy/1287.ElementAppearingMoreThan25InSortedArray(for).py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array sorted in non-decreasing order, 3 | there is exactly one integer in the array that occurs 4 | more than 25% of the time. 5 | 6 | Return that integer. 7 | 8 | Example: 9 | Input: arr = [1,2,2,6,6,6,6,7,10] 10 | Output: 6 11 | 12 | Constraints: 13 | - 1 <= arr.length <= 10^4 14 | - 0 <= arr[i] <= 10^5 15 | ''' 16 | #Difficulty: Easy 17 | #18 / 18 test cases passed. 18 | #Runtime: 180 ms 19 | #Memory Usage: 15.9 MB 20 | 21 | #Runtime: 180 ms, faster than 11.20% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array. 22 | #Memory Usage: 15.9 MB, less than 12.26% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array. 23 | 24 | class Solution: 25 | def findSpecialInteger(self, arr: List[int]) -> int: 26 | length = len(arr) 27 | nums = {} 28 | result = arr[0] 29 | for num in arr: 30 | if num not in nums: 31 | nums[num] = 0 32 | nums[num] += 1 33 | if nums[num] >= length // 4: 34 | result = result if nums[result] > nums[num] else num 35 | return result 36 | -------------------------------------------------------------------------------- /Easy/1299.ReplaceElementswithGreatestElementonRightSide.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array arr, replace every element in that array with the greatest 3 | element among the elements to its right, and replace the last element with -1. 4 | After doing so, return the array. 5 | 6 | Example: 7 | Input: arr = [17,18,5,4,6,1] 8 | Output: [18,6,6,6,1,-1] 9 | """ 10 | #Difficulty: Easy 11 | #15 / 15 test cases passed. 12 | #Runtime: 112 ms 13 | #Memory Usage: 14.8 MB 14 | 15 | #Runtime: 112 ms, faster than 99.50% of Python3 online submissions for Replace Elements with Greatest Element on Right Side. 16 | #Memory Usage: 14.8 MB, less than 100.00% of Python3 online submissions for Replace Elements with Greatest Element on Right Side. 17 | 18 | class Solution: 19 | def replaceElements(self, arr: List[int]) -> List[int]: 20 | i = len(arr)-1 21 | greater = -1 22 | while i >= 0: 23 | if arr[i] > greater: 24 | arr[i], greater = greater, arr[i] 25 | else: 26 | arr[i] = greater 27 | i -= 1 28 | return arr 29 | -------------------------------------------------------------------------------- /Easy/1304.FindNUniqueIntegersSumuptoZero.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer n, return any array containing n unique integers such that 3 | they add up to 0. 4 | 5 | Example: 6 | Input: n = 5 7 | Output: [-7,-1,1,3,4] 8 | Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. 9 | 10 | Example: 11 | Input: n = 3 12 | Output: [-1,0,1] 13 | 14 | Example: 15 | Input: n = 1 16 | Output: [0] 17 | 18 | Constraints: 19 | - 1 <= n <= 1000 20 | """ 21 | #Difficulty: Easy 22 | #42 / 42 test cases passed. 23 | #Runtime: 32 ms 24 | #Memory Usage: 14.3 MB 25 | 26 | #Runtime: 32 ms, faster than 72.59% of Python3 online submissions for Find N Unique Integers Sum up to Zero. 27 | #Memory Usage: 14.3 MB, less than 5.20% of Python3 online submissions for Find N Unique Integers Sum up to Zero. 28 | 29 | class Solution: 30 | def sumZero(self, n: int) -> List[int]: 31 | result = [] 32 | if n % 2: 33 | result.append(0) 34 | n -= 1 35 | while n: 36 | result.extend([n, -n]) 37 | n -= 2 38 | return result 39 | -------------------------------------------------------------------------------- /Easy/1323.Maximum69Number.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer num consisting only of digits 6 and 9. 3 | Return the maximum number you can get by changing at most one digit 4 | (6 becomes 9, and 9 becomes 6). 5 | 6 | Example: 7 | Input: num = 9669 8 | Output: 9969 9 | Explanation: 10 | Changing the first digit results in 6669. 11 | Changing the second digit results in 9969. 12 | Changing the third digit results in 9699. 13 | Changing the fourth digit results in 9666. 14 | The maximum number is 9969. 15 | 16 | Constraints: 17 | - 1 <= num <= 10^4 18 | - num's digits are 6 or 9. 19 | """ 20 | #Difficulty: Easy 21 | #153 / 153 test cases passed. 22 | #Runtime: 28 ms 23 | #Memory Usage: 13.8 MB 24 | 25 | #Runtime: 28 ms, faster than 82.26% of Python3 online submissions for Maximum 69 Number. 26 | #Memory Usage: 13.6 MB, less than 96.45% of Python3 online submissions for Maximum 69 Number. 27 | 28 | class Solution: 29 | def maximum69Number (self, num: int) -> int: 30 | n = list(str(num)) 31 | for i in range(len(n)): 32 | if n[i] < '9': 33 | n[i] = '9' 34 | break 35 | return int(''.join(n)) 36 | -------------------------------------------------------------------------------- /Easy/1342.NumberofStepstoReduceaNumbertoZero.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-negative integer num, return the number of steps to reduce it 3 | to zero. If the current number is even, you have to divide it by 2, 4 | otherwise, you have to subtract 1 from it. 5 | 6 | Example: 7 | Input: num = 14 8 | Output: 6 9 | Explanation: 10 | Step 1) 14 is even; divide by 2 and obtain 7. 11 | Step 2) 7 is odd; subtract 1 and obtain 6. 12 | Step 3) 6 is even; divide by 2 and obtain 3. 13 | Step 4) 3 is odd; subtract 1 and obtain 2. 14 | Step 5) 2 is even; divide by 2 and obtain 1. 15 | Step 6) 1 is odd; subtract 1 and obtain 0. 16 | """ 17 | #Difficulty: Easy 18 | #203 / 203 test cases passed. 19 | #Runtime: 28 ms 20 | #Memory Usage: 13.8 MB 21 | 22 | #Runtime: 28 ms, faster than 74.69% of Python3 online submissions for Number of Steps to Reduce a Number to Zero. 23 | #Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Number of Steps to Reduce a Number to Zero. 24 | 25 | class Solution: 26 | def numberOfSteps (self, num: int) -> int: 27 | steps = 0 28 | while num > 0: 29 | if num % 2 != 0: 30 | num -= 1 31 | else: 32 | num /= 2 33 | steps += 1 34 | return steps 35 | -------------------------------------------------------------------------------- /Easy/1351.CountNegativeNumbersinaSortedMatrix(nestedFor).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a m * n matrix grid which is sorted in non-increasing order both 3 | row-wise and column-wise. 4 | Return the number of negative numbers in grid. 5 | 6 | Example: 7 | Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 8 | Output: 8 9 | Explanation: There are 8 negatives number in the matrix. 10 | 11 | Constraints: 12 | - m == grid.length 13 | - n == grid[i].length 14 | - 1 <= m, n <= 100 15 | - -100 <= grid[i][j] <= 100 16 | """ 17 | #Difficulty: Easy 18 | #44 / 44 test cases passed. 19 | #Runtime: 148 ms 20 | #Memory Usage: 14.7 MB 21 | 22 | #Runtime: 148 ms, faster than 19.10% of Python3 online submissions for Count Negative Numbers in a Sorted Matrix. 23 | #Memory Usage: 14.7 MB, less than 66.55% of Python3 online submissions for Count Negative Numbers in a Sorted Matrix. 24 | 25 | class Solution: 26 | def countNegatives(self, grid: List[List[int]]) -> int: 27 | count = 0 28 | rows = len(grid) 29 | cols = len(grid[0]) 30 | for row in range(rows): 31 | for col in range(cols): 32 | if grid[row][col] < 0: 33 | count += 1 34 | return count 35 | -------------------------------------------------------------------------------- /Easy/1351.CountNegativeNumbersinaSortedMatrix(nestedForOptimized).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a m * n matrix grid which is sorted in non-increasing order both 3 | row-wise and column-wise. 4 | Return the number of negative numbers in grid. 5 | 6 | Example: 7 | Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 8 | Output: 8 9 | Explanation: There are 8 negatives number in the matrix. 10 | 11 | Constraints: 12 | - m == grid.length 13 | - n == grid[i].length 14 | - 1 <= m, n <= 100 15 | - -100 <= grid[i][j] <= 100 16 | """ 17 | #Difficulty: Easy 18 | #44 / 44 test cases passed. 19 | #Runtime: 136 ms 20 | #Memory Usage: 14.5 MB 21 | 22 | #Runtime: 136 ms, faster than 28.51% of Python3 online submissions for Count Negative Numbers in a Sorted Matrix. 23 | #Memory Usage: 14.5 MB, less than 95.00% of Python3 online submissions for Count Negative Numbers in a Sorted Matrix. 24 | 25 | class Solution: 26 | def countNegatives(self, grid: List[List[int]]) -> int: 27 | count = 0 28 | rows = len(grid) 29 | cols = len(grid[0]) 30 | for row in range(rows): 31 | for col in range(cols): 32 | if grid[row][col] < 0: 33 | count += cols - col 34 | break 35 | return count 36 | -------------------------------------------------------------------------------- /Easy/1374.GenerateaStringWithCharactersThatHaveOddCounts.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer n, return a string with n characters such that each 3 | character in such string occurs an odd number of times. 4 | 5 | The returned string must contain only lowercase English letters. If there 6 | are multiples valid strings, return any of them. 7 | 8 | Example: 9 | Input: n = 4 10 | Output: "pppz" 11 | Explanation: "pppz" is a valid string since the character 'p' occurs three 12 | times and the character 'z' occurs once. Note that there are 13 | many other valid strings such as "ohhh" and "love". 14 | 15 | Example: 16 | Input: n = 2 17 | Output: "xy" 18 | Explanation: "xy" is a valid string since the characters 'x' and 'y' occur 19 | once. Note that there are many other valid strings such as 20 | "ag" and "ur". 21 | 22 | Example: 23 | Input: n = 7 24 | Output: "holasss" 25 | 26 | Constraints: 27 | - 1 <= n <= 500 28 | """ 29 | #Difficulty: Easy 30 | #103 / 103 test cases passed. 31 | #Runtime: 28 ms 32 | #Memory Usage: 13.8 MB 33 | 34 | #Runtime: 28 ms, faster than 81.87% of Python3 online submissions for Generate a String With Characters That Have Odd Counts. 35 | #Memory Usage: 13.8 MB, less than 70.96% of Python3 online submissions for Generate a String With Characters That Have Odd Counts. 36 | 37 | class Solution: 38 | def generateTheString(self, n: int) -> str: 39 | return 'a' * n if n % 2 else 'b' + 'a' * (n - 1) 40 | -------------------------------------------------------------------------------- /Easy/14.LongestCommonPrefix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function to find the longest common prefix string amongst an array 3 | of strings. 4 | If there is no common prefix, return an empty string "". 5 | 6 | Example 1: 7 | Input: ["flower","flow","flight"] 8 | Output: "fl" 9 | """ 10 | #Difficulty: Easy 11 | #118 / 118 test cases passed. 12 | #Runtime: 24 ms 13 | #Memory Usage: 14 MB 14 | 15 | #Runtime: 24 ms, faster than 97.59% of Python3 online submissions for Longest Common Prefix. 16 | #Memory Usage: 14 MB, less than 6.67% of Python3 online submissions for Longest Common Prefix. 17 | 18 | class Solution: 19 | def longestCommonPrefix(self, strs: List[str]) -> str: 20 | if not strs: return '' 21 | if len(strs) == 1: return strs[0] 22 | i = 0 23 | strs = sorted(strs, key=len) 24 | word = strs[0] 25 | for letter in word: 26 | if self.counter(strs[1:], letter, i): 27 | i += 1 28 | else: break 29 | return word[:i] 30 | 31 | def counter(self, strs, letter, i): 32 | for word in strs: 33 | if letter not in word[i]: 34 | return 0 35 | return 1 36 | -------------------------------------------------------------------------------- /Easy/1446.ConsecutiveCharacters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s, the power of the string is the maximum length of a 3 | non-empty substring that contains only one unique character. 4 | 5 | Return the power of the string. 6 | 7 | Example: 8 | Input: s = "leetcode" 9 | Output: 2 10 | Explanation: The substring "ee" is of length 2 with the character 'e' only. 11 | 12 | Constraints: 13 | - 1 <= s.length <= 500 14 | - s contains only lowercase English letters. 15 | """ 16 | #Difficulty: Easy 17 | #333 / 333 test cases passed. 18 | #Runtime: 36 ms 19 | #Memory Usage: 13.7 MB 20 | 21 | #Runtime: 36 ms, faster than 94.53% of Python3 online submissions for Consecutive Characters. 22 | #Memory Usage: 13.7 MB, less than 88.51% of Python3 online submissions for Consecutive Characters. 23 | 24 | class Solution: 25 | def maxPower(self, s: str) -> int: 26 | result = count = 1 27 | i = 0 28 | j = i + 1 29 | l = len(s) - 1 30 | while i < l: 31 | if j <= l and s[j] == s[i]: 32 | count += 1 33 | j += 1 34 | else: 35 | result = max(result, count) 36 | count = 1 37 | i = j 38 | j = i + 1 39 | return result 40 | -------------------------------------------------------------------------------- /Easy/1464.MaximumProductofTwoElementsinanArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the array of integers nums, you will choose two different indices i 3 | and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). 4 | 5 | Example: 6 | Input: nums = [3,4,5,2] 7 | Output: 12 8 | Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you 9 | will get the maximum value, that is, 10 | (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 11 | 12 | Constraints: 13 | - 2 <= nums.length <= 500 14 | - 1 <= nums[i] <= 10^3 15 | """ 16 | #Difficulty: Easy 17 | #104 / 104 test cases passed. 18 | #Runtime: 44 ms 19 | #Memory Usage: 13.8 MB 20 | 21 | #Runtime: 44 ms, faster than 97.04% of Python3 online submissions for Maximum Product of Two Elements in an Array. 22 | #Memory Usage: 13.8 MB, less than 84.74% of Python3 online submissions for Maximum Product of Two Elements in an Array. 23 | 24 | class Solution: 25 | def maxProduct(self, nums: List[int]) -> int: 26 | nums.sort() 27 | return (nums[-2] - 1) * (nums[-1] - 1) 28 | -------------------------------------------------------------------------------- /Easy/1470.ShuffletheArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the array nums consisting of 2n elements in the form 3 | [x1,x2,...,xn,y1,y2,...,yn]. 4 | 5 | Return the array in the form [x1,y1,x2,y2,...,xn,yn]. 6 | 7 | Example: 8 | Input: nums = [2,5,1,3,4,7], n = 3 9 | Output: [2,3,5,4,1,7] 10 | Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is 11 | [2,3,5,4,1,7]. 12 | 13 | Constraints: 14 | - 1 <= n <= 500 15 | - nums.length == 2n 16 | - 1 <= nums[i] <= 10^3 17 | """ 18 | #Difficulty: Easy 19 | #53 / 53 test cases passed. 20 | #Runtime: 56 ms 21 | #Memory Usage: 13.9 MB 22 | 23 | #Runtime: 56 ms, faster than 95.78% of Python3 online submissions for Shuffle the Array. 24 | #Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Shuffle the Array. 25 | 26 | class Solution: 27 | def shuffle(self, nums: List[int], n: int) -> List[int]: 28 | shuffle = [] 29 | for num in zip(nums[:n], nums[n:]): 30 | shuffle += list(num) 31 | return shuffle 32 | -------------------------------------------------------------------------------- /Easy/1480.RunningSumof1dArray(ListComprehension).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array nums. We define a running sum of an array as 3 | runningSum[i] = sum(nums[0]…nums[i]). 4 | 5 | Return the running sum of nums. 6 | 7 | Example: 8 | Input: nums = [1,2,3,4] 9 | Output: [1,3,6,10] 10 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 11 | 12 | Constraints: 13 | - 1 <= nums.length <= 1000 14 | - -10^6 <= nums[i] <= 10^6 15 | """ 16 | #Difficulty: Easy 17 | #53 / 53 test cases passed. 18 | #Runtime: 48 ms 19 | #Memory Usage: 14 MB 20 | 21 | #Runtime: 48 ms, faster than 55.37% of Python3 online submissions for Running Sum of 1d Array. 22 | #Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Running Sum of 1d Array. 23 | 24 | class Solution: 25 | def runningSum(self, nums: List[int]) -> List[int]: 26 | return [sum(nums[:i]) for i in range(1, len(nums)+1)] 27 | -------------------------------------------------------------------------------- /Easy/1480.RunningSumof1dArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array nums. We define a running sum of an array as 3 | runningSum[i] = sum(nums[0]…nums[i]). 4 | 5 | Return the running sum of nums. 6 | 7 | Example: 8 | Input: nums = [1,2,3,4] 9 | Output: [1,3,6,10] 10 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 11 | 12 | Constraints: 13 | - 1 <= nums.length <= 1000 14 | - -10^6 <= nums[i] <= 10^6 15 | """ 16 | #Difficulty: Easy 17 | #53 / 53 test cases passed. 18 | #Runtime: 36 ms 19 | #Memory Usage: 13.9 MB 20 | 21 | #Runtime: 36 ms, faster than 92.99% of Python3 online submissions for Running Sum of 1d Array. 22 | #Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Running Sum of 1d Array. 23 | 24 | class Solution: 25 | def runningSum(self, nums: List[int]) -> List[int]: 26 | for i in range(1, len(nums)): 27 | nums[i] += nums[i-1] 28 | return nums 29 | -------------------------------------------------------------------------------- /Easy/1486.XOROperationinanArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer n and an integer start. 3 | Define an array nums where nums[i] = start + 2*i (0-indexed) and 4 | n == nums.length. 5 | Return the bitwise XOR of all elements of nums. 6 | 7 | Example: 8 | Input: n = 5, start = 0 9 | Output: 8 10 | Explanation: Array nums is equal to [0, 2, 4, 6, 8] 11 | where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. 12 | Where "^" corresponds to bitwise XOR operator. 13 | 14 | Constraints: 15 | - 1 <= n <= 1000 16 | - 0 <= start <= 1000 17 | - n == nums.length 18 | """ 19 | #Difficulty: Easy 20 | #54 / 54 test cases passed. 21 | #Runtime: 28 ms 22 | #Memory Usage: 13.9 MB 23 | 24 | #Runtime: 28 ms, faster than 85.34% of Python3 online submissions for XOR Operation in an Array. 25 | #Memory Usage: 13.9 MB, less than 27.03% of Python3 online submissions for XOR Operation in an Array. 26 | 27 | class Solution: 28 | def xorOperation(self, n: int, start: int) -> int: 29 | num = start 30 | for i in range(1, n): 31 | num ^= start + 2 * i 32 | return num 33 | -------------------------------------------------------------------------------- /Easy/1496.PathCrossing.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing 3 | moving one unit north, south, east, or west, respectively. You start at the 4 | origin (0, 0) on a 2D plane and walk on the path specified by path. 5 | 6 | Return True if the path crosses itself at any point, that is, if at any time 7 | you are on a location you've previously visited. Return False otherwise. 8 | 9 | Example: 10 | Input: path = "NESWW" 11 | Output: true 12 | Explanation: Notice that the path visits the origin twice. 13 | 14 | Constraints: 15 | - 1 <= path.length <= 10^4 16 | - path will only consist of characters in {'N', 'S', 'E', 'W} 17 | """ 18 | #Difficulty: Easy 19 | #76 / 76 test cases passed. 20 | #Runtime: 40 ms 21 | #Memory Usage: 14 MB 22 | 23 | #Runtime: 40 ms, faster than 36.06% of Python3 online submissions for Path Crossing. 24 | #Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Path Crossing. 25 | 26 | class Solution: 27 | def isPathCrossing(self, path: str) -> bool: 28 | db = {"N" : [1, 0], "S" : [-1, 0], "E" : [0, 1], "W" : [0, -1]} 29 | moves = [[0, 0]] 30 | for i in path: 31 | moves.append([moves[-1][0] + db[i][0], moves[-1][1] + db[i][1]]) 32 | if moves[-1] in moves[:-1]: 33 | return True 34 | return False 35 | -------------------------------------------------------------------------------- /Easy/1502.CanMakeArithmeticProgressionFromSequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of numbers arr. A sequence of numbers is called an 3 | arithmetic progression if the difference between any two consecutive 4 | elements is the same. 5 | Return true if the array can be rearranged to form an arithmetic 6 | progression, otherwise, return false. 7 | 8 | Example: 9 | Input: arr = [3,5,1] 10 | Output: true 11 | Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with 12 | ifferences 2 and -2 respectively, between each consecutive 13 | elements. 14 | 15 | Example: 16 | Input: arr = [1,2,4] 17 | Output: false 18 | Explanation: There is no way to reorder the elements to obtain an 19 | arithmetic progression. 20 | 21 | Constraints: 22 | - 2 <= arr.length <= 1000 23 | - -10^6 <= arr[i] <= 10^6 24 | """ 25 | #Difficulty: Easy 26 | #102 / 102 test cases passed. 27 | #Runtime: 36 ms 28 | #Memory Usage: 14.2 MB 29 | 30 | #Runtime: 36 ms, faster than 90.39% of Python3 online submissions for Can Make Arithmetic Progression From Sequence. 31 | #Memory Usage: 14.2 MB, less than 6.83% of Python3 online submissions for Can Make Arithmetic Progression From Sequence. 32 | 33 | class Solution: 34 | def canMakeArithmeticProgression(self, arr: List[int]) -> bool: 35 | arr.sort() 36 | diff = arr[1] - arr[0] 37 | for i in range(1, len(arr)): 38 | if arr[i] - arr[i-1] != diff: 39 | return False 40 | return True 41 | -------------------------------------------------------------------------------- /Easy/1507.ReformatDate(String).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a date string in the form Day Month Year, where: 3 | - Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}. 4 | - Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", 5 | "Aug", "Sep", "Oct", "Nov", "Dec"}. 6 | - Year is in the range [1900, 2100]. 7 | 8 | Convert the date string to the format YYYY-MM-DD, where: 9 | - YYYY denotes the 4 digit year. 10 | - MM denotes the 2 digit month. 11 | - DD denotes the 2 digit day. 12 | 13 | Example: 14 | Input: date = "20th Oct 2052" 15 | Output: "2052-10-20" 16 | 17 | Constraints: 18 | - The given dates are guaranteed to be valid, so no error handling is n 19 | ecessary. 20 | """ 21 | #Difficulty: Easy 22 | #110 / 110 test cases passed. 23 | #Runtime: 40 ms 24 | #Memory Usage: 13.8 MB 25 | 26 | #Runtime: 40 ms, faster than 100.00% of Python3 online submissions for Reformat Date. 27 | #Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Reformat Date. 28 | 29 | class Solution: 30 | def reformatDate(self, date: str) -> str: 31 | months = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", 32 | "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", 33 | "Nov":"11", "Dec":"12"} 34 | if date[1].isalpha(): date = "0" + date 35 | return date[-4:] + '-' + months[date[5:8]] + '-' + date[:2] 36 | -------------------------------------------------------------------------------- /Easy/1512.NumberofGoodPairs(Dict).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums. 3 | A pair (i,j) is called good if nums[i] == nums[j] and i < j. 4 | Return the number of good pairs. 5 | 6 | Example: 7 | Input: nums = [1,2,3,1,1,3] 8 | Output: 4 9 | Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. 10 | 11 | Constraints: 12 | - 1 <= nums.length <= 100 13 | - 1 <= nums[i] <= 100 14 | """ 15 | #Difficulty: Easy 16 | #48 / 48 test cases passed. 17 | #Runtime: 40 ms 18 | #Memory Usage: 13.9 MB 19 | 20 | #Runtime: 40 ms, faster than 66.67% of Python3 online submissions for Number of Good Pairs. 21 | #Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Number of Good Pairs. 22 | 23 | class Solution: 24 | def numIdenticalPairs(self, nums: List[int]) -> int: 25 | d = {} 26 | s = set() 27 | for i, n in enumerate(nums): 28 | if n in d: 29 | d[n].append(i) 30 | else: 31 | d[n] = [i] 32 | for value in d.values(): 33 | l = len(value) 34 | i = 0 35 | j = 1 36 | if l > 1: 37 | while i < l-1: 38 | if j == l: 39 | i += 1 40 | j = min(i + 1, l-1) 41 | if i == j: 42 | break 43 | s.add((value[i], value[j])) 44 | j += 1 45 | return len(s) 46 | -------------------------------------------------------------------------------- /Easy/1512.NumberofGoodPairs(For).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers nums. 3 | A pair (i,j) is called good if nums[i] == nums[j] and i < j. 4 | Return the number of good pairs. 5 | 6 | Example: 7 | Input: nums = [1,2,3,1,1,3] 8 | Output: 4 9 | Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. 10 | 11 | Constraints: 12 | - 1 <= nums.length <= 100 13 | - 1 <= nums[i] <= 100 14 | """ 15 | #Difficulty: Easy 16 | #48 / 48 test cases passed. 17 | #Runtime: 60 ms 18 | #Memory Usage: 13.9 MB 19 | 20 | #Runtime: 60 ms, faster than 33.33% of Python3 online submissions for Number of Good Pairs. 21 | #Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Number of Good Pairs. 22 | 23 | class Solution: 24 | def numIdenticalPairs(self, nums: List[int]) -> int: 25 | count = 0 26 | for i in range(len(nums)): 27 | for j in range(i): 28 | if nums[i] == nums[j]: 29 | count += 1 30 | return count 31 | -------------------------------------------------------------------------------- /Easy/1518.WaterBottles.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given numBottles full water bottles, you can exchange numExchange empty 3 | water bottles for one full water bottle. 4 | The operation of drinking a full water bottle turns it into an empty bottle. 5 | Return the maximum number of water bottles you can drink. 6 | 7 | Example: 8 | Input: numBottles = 15, numExchange = 4 9 | Output: 19 10 | Explanation: You can exchange 4 empty bottles to get 1 full water bottle. 11 | Number of water bottles you can drink: 15 + 3 + 1 = 19. 12 | 13 | Constraints: 14 | - 1 <= numBottles <= 100 15 | - 2 <= numExchange <= 100 16 | """ 17 | #Difficulty: Easy 18 | #64 / 64 test cases passed. 19 | #Runtime: 16 ms 20 | #Memory Usage: 13.9 MB 21 | 22 | #Runtime: 16 ms, faster than 99.90% of Python3 online submissions for Water Bottles. 23 | #Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Water Bottles. 24 | 25 | class Solution: 26 | def numWaterBottles(self, numBottles: int, numExchange: int) -> int: 27 | total = numBottles 28 | while numBottles >= numExchange: 29 | emptyExchange = numBottles // numExchange 30 | emptyNotExchange = numBottles % numExchange 31 | numBottles = emptyExchange + emptyNotExchange 32 | total += emptyExchange 33 | return total 34 | -------------------------------------------------------------------------------- /Easy/1523.CountOddNumbersinanIntervalRange.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two non-negative integers low and high. Return the count of odd 3 | numbers between low and high (inclusive). 4 | 5 | Example: 6 | Input: low = 3, high = 7 7 | Output: 3 8 | Explanation: The odd numbers between 3 and 7 are [3,5,7]. 9 | 10 | Constraints: 11 | - 0 <= low <= high <= 10^9 12 | """ 13 | #Difficulty: Easy 14 | #84 / 84 test cases passed. 15 | #Runtime: 24 ms 16 | #Memory Usage: 13.9 MB 17 | 18 | #Runtime: 24 ms, faster than 75.00% of Python3 online submissions for Count Odd Numbers in an Interval Range. 19 | #Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Count Odd Numbers in an Interval Range. 20 | 21 | class Solution: 22 | def countOdds(self, low: int, high: int) -> int: 23 | return 1 + (high + 1 - low) // 2 if low % 2 and high % 2 else (high + 1 - low) // 2 24 | -------------------------------------------------------------------------------- /Easy/1528.ShuffleString(List).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s and an integer array indices of the same length. 3 | The string s will be shuffled such that the character at the ith position 4 | moves to indices[i] in the shuffled string. 5 | Return the shuffled string. 6 | 7 | Example: 8 | Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] 9 | Output: "leetcode" 10 | Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. 11 | 12 | Constraints: 13 | - s.length == indices.length == n 14 | - 1 <= n <= 100 15 | - s contains only lower-case English letters. 16 | - 0 <= indices[i] < n 17 | - All values of indices are unique (i.e. indices is a permutation of 18 | the integers from 0 to n - 1). 19 | """ 20 | #Difficulty: Easy 21 | #399 / 399 test cases passed. 22 | #Runtime: 52 ms 23 | #Memory Usage: 13.8 MB 24 | 25 | #Runtime: 52 ms, faster than 97.33% of Python3 online submissions for Shuffle String. 26 | #Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Shuffle String. 27 | 28 | class Solution: 29 | def restoreString(self, s: str, indices: List[int]) -> str: 30 | l = len(s) 31 | shuffle = [None] * l 32 | for i in range(l): 33 | shuffle[indices[i]] = s[i] 34 | return ''.join(shuffle) 35 | -------------------------------------------------------------------------------- /Easy/1528.ShuffleString(String).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s and an integer array indices of the same length. 3 | The string s will be shuffled such that the character at the ith position 4 | moves to indices[i] in the shuffled string. 5 | Return the shuffled string. 6 | 7 | Example: 8 | Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] 9 | Output: "leetcode" 10 | Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. 11 | 12 | Constraints: 13 | - s.length == indices.length == n 14 | - 1 <= n <= 100 15 | - s contains only lower-case English letters. 16 | - 0 <= indices[i] < n 17 | - All values of indices are unique (i.e. indices is a permutation of 18 | the integers from 0 to n - 1). 19 | """ 20 | #Difficulty: Easy 21 | #399 / 399 test cases passed. 22 | #Runtime: 72 ms 23 | #Memory Usage: 13.8 MB 24 | 25 | #Runtime: 72 ms, faster than 69.20% of Python3 online submissions for Shuffle String. 26 | #Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Shuffle String. 27 | 28 | class Solution: 29 | def restoreString(self, s: str, indices: List[int]) -> str: 30 | l = len(s) 31 | shuffle = "_" * l 32 | for i in range(l): 33 | shuffle = shuffle[:indices[i]] + s[i] + shuffle[indices[i]+1:] 34 | return shuffle 35 | -------------------------------------------------------------------------------- /Easy/1539.KthMissingPositiveNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array arr of positive integers sorted in a strictly increasing 3 | order, and an integer k. 4 | Find the kth positive integer that is missing from this array. 5 | 6 | Example: 7 | Input: arr = [2,3,4,7,11], k = 5 8 | Output: 9 9 | Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. 10 | The 5th missing positive integer is 9. 11 | 12 | Example: 13 | Input: arr = [1,2,3,4], k = 2 14 | Output: 6 15 | Explanation: The missing positive integers are [5,6,7,...]. 16 | The 2nd missing positive integer is 6. 17 | 18 | Constraints: 19 | - 1 <= arr.length <= 1000 20 | - 1 <= arr[i] <= 1000 21 | - 1 <= k <= 1000 22 | - arr[i] < arr[j] for 1 <= i < j <= arr.length 23 | """ 24 | #Difficulty: Easy 25 | #83 / 83 test cases passed. 26 | #Runtime: 52 ms 27 | #Memory Usage: 13.8 MB 28 | 29 | #Runtime: 52 ms, faster than 82.94% of Python3 online submissions for Kth Missing Positive Number. 30 | #Memory Usage: 13.8 MB, less than 92.67% of Python3 online submissions for Kth Missing Positive Number. 31 | 32 | class Solution: 33 | def findKthPositive(self, arr: List[int], k: int) -> int: 34 | maximum = max(arr) 35 | array = [0] * 1001 36 | for number in arr: 37 | array[number] = number 38 | for i in range(1, maximum): 39 | if not array[i]: 40 | k -= 1 41 | if k == 0: 42 | return i 43 | return maximum + k 44 | -------------------------------------------------------------------------------- /Easy/1550.ThreeConsecutiveOdds.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array arr, return true if there are three consecutive odd 3 | numbers in the array. Otherwise, return false. 4 | 5 | Example: 6 | Input: arr = [2,6,4,1] 7 | Output: false 8 | Explanation: There are no three consecutive odds. 9 | 10 | Example: 11 | Input: arr = [1,2,34,3,4,5,7,23,12] 12 | Output: true 13 | Explanation: [5,7,23] are three consecutive odds. 14 | 15 | Constraints: 16 | - 1 <= arr.length <= 1000 17 | - 1 <= arr[i] <= 1000 18 | """ 19 | #Difficulty: Easy 20 | #32 / 32 test cases passed. 21 | #Runtime: 40 ms 22 | #Memory Usage: 14.1 MB 23 | 24 | #Runtime: 40 ms, faster than 92.21% of Python3 online submissions for Three Consecutive Odds. 25 | #Memory Usage: 14.1 MB, less than 100.00% of Python3 online submissions for Three Consecutive Odds. 26 | 27 | class Solution: 28 | def threeConsecutiveOdds(self, arr: List[int]) -> bool: 29 | count = 0 30 | for num in arr: 31 | if num % 2: 32 | count += 1 33 | else: 34 | count = 0 35 | if count == 3: 36 | return True 37 | return False 38 | -------------------------------------------------------------------------------- /Easy/1556.ThousandSeparator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer n, add a dot (".") as the thousands separator and return 3 | it in string format. 4 | 5 | Example: 6 | Input: n = 987 7 | Output: "987" 8 | 9 | Example: 10 | Input: n = 1234 11 | Output: "1.234" 12 | 13 | Example: 14 | Input: n = 123456789 15 | Output: "123.456.789" 16 | 17 | Example: 18 | Input: n = 0 19 | Output: "0" 20 | 21 | Constraints: 22 | - 0 <= n < 2^31 23 | """ 24 | #Difficulty: Easy 25 | #69 / 69 test cases passed. 26 | #Runtime: 52 ms 27 | #Memory Usage: 13.9 MB 28 | 29 | #Runtime: 52 ms, faster than 25.00% of Python3 online submissions for Thousand Separator. 30 | #Memory Usage: 13.9 MB, less than 25.00% of Python3 online submissions for Thousand Separator. 31 | 32 | class Solution: 33 | def thousandSeparator(self, n: int) -> str: 34 | s = str(n) 35 | l = len(s) 36 | nums = [] 37 | while s: 38 | if l > 2: 39 | l -= 3 40 | else: 41 | nums.insert(0, s[:l]) 42 | break 43 | nums.insert(0, s[l:]) 44 | s = s[:l] 45 | return '.'.join(nums) 46 | -------------------------------------------------------------------------------- /Easy/167.TwoSumII-Inputarrayissorted.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers that is already sorted in ascending order, find 3 | two numbers such that they add up to a specific target number. 4 | The function twoSum should return indices of the two numbers such that they 5 | add up to the target, where index1 must be less than index2. 6 | 7 | Note: 8 | - Your returned answers (both index1 and index2) are not zero-based. 9 | - You may assume that each input would have exactly one solution and you may 10 | not use the same element twice. 11 | 12 | Example: 13 | Input: numbers = [2,7,11,15], target = 9 14 | Output: [1,2] 15 | Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 16 | """ 17 | #Difficulty: Easy 18 | #17 / 17 test cases passed. 19 | #Runtime: 52 ms 20 | #Memory Usage: 14.1 MB 21 | 22 | #Runtime: 52 ms, faster than 99.27% of Python3 online submissions for Two Sum II - Input array is sorted. 23 | #Memory Usage: 14.1 MB, less than 5.80% of Python3 online submissions for Two Sum II - Input array is sorted. 24 | 25 | class Solution: 26 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 27 | s = sorted(list(set(numbers))) 28 | for n in s: 29 | if target - n in numbers: 30 | i = numbers.index(n) + 1 31 | j = i + numbers[i:].index(target - n) + 1 32 | return [i, j] 33 | -------------------------------------------------------------------------------- /Easy/168.ExcelSheetColumnTitle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer, return its corresponding column title as appear 3 | in an Excel sheet. 4 | 5 | For example: 6 | 7 | 1 -> A 8 | 2 -> B 9 | 3 -> C 10 | ... 11 | 26 -> Z 12 | 27 -> AA 13 | 28 -> AB 14 | ... 15 | 16 | Example: 17 | Input: 701 18 | Output: "ZY" 19 | """ 20 | #Difficulty: Easy 21 | #18 / 18 test cases passed. 22 | #Runtime: 28 ms 23 | #Memory Usage: 14.1 MB 24 | 25 | #Runtime: 28 ms, faster than 73.06% of Python3 online submissions for Excel Sheet Column Title. 26 | #Memory Usage: 14.1 MB, less than 99.90% of Python3 online submissions for Excel Sheet Column Title. 27 | 28 | class Solution: 29 | def convertToTitle(self, n: int) -> str: 30 | s = "" 31 | if n <= 26: 32 | s += chr(64+n) 33 | while n > 26: 34 | m = n % 26 35 | n = n // 26 36 | if not m: 37 | m = 26 38 | n -= 1 39 | if n > 26: 40 | s += chr(64+m) 41 | continue 42 | s += chr(64+m) 43 | s += chr(64+n) 44 | return s[::-1] 45 | -------------------------------------------------------------------------------- /Easy/171.ExcelSheetColumnNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a column title as appear in an Excel sheet, return its corresponding 3 | column number. 4 | 5 | For example: 6 | 7 | A -> 1 8 | B -> 2 9 | C -> 3 10 | ... 11 | Z -> 26 12 | AA -> 27 13 | AB -> 28 14 | ... 15 | 16 | Example: 17 | Input: "AB" 18 | Output: 28 19 | 20 | Example: 21 | Input: "ZY" 22 | Output: 701 23 | 24 | Constraints: 25 | - 1 <= s.length <= 7 26 | - s consists only of uppercase English letters. 27 | - s is between "A" and "FXSHRXW". 28 | """ 29 | #Difficulty: Easy 30 | #1000 / 1000 test cases passed. 31 | #Runtime: 28 ms 32 | #Memory Usage: 13.7 MB 33 | 34 | #Runtime: 28 ms, faster than 92.13% of Python3 online submissions for Excel Sheet Column Number. 35 | #Memory Usage: 13.7 MB, less than 83.68% of Python3 online submissions for Excel Sheet Column Number. 36 | 37 | class Solution: 38 | def titleToNumber(self, s: str) -> int: 39 | number, prod = 0, 1 40 | for char in s[::-1]: 41 | number += (1 + ord(char) - ord('A')) * prod 42 | prod *= 26 43 | return number 44 | -------------------------------------------------------------------------------- /Easy/172.FactorialTrailingZeroes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer n, return the number of trailing zeroes in n!. 3 | 4 | Follow up: Could you write a solution that works in logarithmic time 5 | complexity? 6 | 7 | Example: 8 | Input: n = 3 9 | Output: 0 10 | Explanation: 3! = 6, no trailing zero. 11 | 12 | Example: 13 | Input: n = 5 14 | Output: 1 15 | Explanation: 5! = 120, one trailing zero. 16 | 17 | Example: 18 | Input: n = 0 19 | Output: 0 20 | 21 | Constraints: 22 | - 1 <= n <= 10^4 23 | """ 24 | #Difficulty: Easy 25 | #500 / 500 test cases passed. 26 | #Runtime: 4236 ms 27 | #Memory Usage: 14.3 MB 28 | 29 | #Runtime: 4236 ms, faster than 11.06% of Python3 online submissions for Factorial Trailing Zeroes. 30 | #Memory Usage: 14.3 MB, less than 16.42% of Python3 online submissions for Factorial Trailing Zeroes. 31 | 32 | class Solution: 33 | def trailingZeroes(self, n: int) -> int: 34 | f = 1 35 | while n > 0: 36 | f = f * n 37 | n -= 1 38 | f = str(f)[::-1] 39 | count = float(inf) 40 | for i in range(1,10): 41 | i = str(i) 42 | if i in f: 43 | count = min(count, f.index(i)) 44 | return count 45 | -------------------------------------------------------------------------------- /Easy/1732.FindtheHighestAltitude.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There is a biker going on a road trip. The road trip 3 | consists of n + 1 points at different altitudes. The 4 | biker starts his trip on point 0 with altitude equal 0. 5 | 6 | You are given an integer array gain of length n where 7 | gain[i] is the net gain in altitude between points i​​​​​​ and 8 | i + 1 for all (0 <= i < n). Return the highest altitude 9 | of a point. 10 | 11 | Example: 12 | Input: gain = [-5,1,5,0,-7] 13 | Output: 1 14 | Explanation: The altitudes are [0,-5,-4,1,1,-6]. The 15 | highest is 1. 16 | 17 | Example: 18 | Input: gain = [-4,-3,-2,-1,4,3,2] 19 | Output: 0 20 | Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. 21 | The highest is 0. 22 | 23 | Constraints: 24 | - n == gain.length 25 | - 1 <= n <= 100 26 | - -100 <= gain[i] <= 100 27 | ''' 28 | #Difficulty: Easy 29 | #80 / 80 test cases passed. 30 | #Runtime: 32 ms 31 | #Memory Usage: 14.3 MB 32 | 33 | #Runtime: 32 ms, faster than 100.00% of Python3 online submissions for Find the Highest Altitude. 34 | #Memory Usage: 14.3 MB, less than 100.00% of Python3 online submissions for Find the Highest Altitude. 35 | 36 | class Solution: 37 | def largestAltitude(self, gain: List[int]) -> int: 38 | current_height = 0 39 | height = 0 40 | for g in gain: 41 | current_height += g 42 | height = max(height, current_height) 43 | return height 44 | -------------------------------------------------------------------------------- /Easy/1748.SumofUniqueElements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an integer array nums. The unique elements 3 | of an array are the elements that appear exactly once in 4 | the array. 5 | 6 | Return the sum of all the unique elements of nums. 7 | 8 | Example: 9 | Input: nums = [1,2,3,2] 10 | Output: 4 11 | Explanation: The unique elements are [1,3], and the sum 12 | is 4. 13 | 14 | Example: 15 | Input: nums = [1,1,1,1,1] 16 | Output: 0 17 | Explanation: There are no unique elements, and the sum 18 | is 0. 19 | 20 | Example: 21 | Input: nums = [1,2,3,4,5] 22 | Output: 15 23 | Explanation: The unique elements are [1,2,3,4,5], and 24 | the sum is 15. 25 | 26 | Constraints: 27 | - 1 <= nums.length <= 100 28 | - 1 <= nums[i] <= 100 29 | ''' 30 | #Difficulty: Easy 31 | #73 / 73 test cases passed. 32 | #Runtime: 28 ms 33 | #Memory Usage: 14.4 MB 34 | 35 | #Runtime: 28 ms, faster than 96.38% of Python3 online submissions for Sum of Unique Elements. 36 | #Memory Usage: 14.4 MB, less than 15.39% of Python3 online submissions for Sum of Unique Elements. 37 | 38 | from collections import Counter 39 | 40 | class Solution: 41 | def sumOfUnique(self, nums: List[int]) -> int: 42 | return sum(num for num, count in Counter(nums).items() if count == 1) -------------------------------------------------------------------------------- /Easy/1796.SecondLargestDigitinaString.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an alphanumeric string s, return the second 3 | largest numerical digit that appears in s, or -1 if it 4 | does not exist. 5 | 6 | An alphanumeric string is a string consisting of 7 | lowercase English letters and digits. 8 | 9 | Example: 10 | Input: s = "dfa12321afd" 11 | Output: 2 12 | Explanation: The digits that appear in s are [1, 2, 3]. 13 | The second largest digit is 2. 14 | 15 | Example: 16 | Input: s = "abc1111" 17 | Output: -1 18 | Explanation: The digits that appear in s are [1]. There 19 | is no second largest digit. 20 | 21 | Constraints: 22 | - 1 <= s.length <= 500 23 | - s consists of only lowercase English letters 24 | and/or digits. 25 | ''' 26 | #Difficulty: Easy 27 | #301 / 301 test cases passed. 28 | #Runtime: 32 ms 29 | #Memory Usage: 14.1 MB 30 | 31 | #Runtime: 32 ms, faster than 92.59% of Python3 online submissions for Second Largest Digit in a String. 32 | #Memory Usage: 14.1 MB, less than 94.39% of Python3 online submissions for Second Largest Digit in a String. 33 | 34 | class Solution: 35 | def secondHighest(self, s: str) -> int: 36 | n = set() 37 | n.add(-1) 38 | for c in s: 39 | if 48 <= ord(c) <= 57: 40 | n.add(int(c)) 41 | n = sorted(n) 42 | if n[-1] >= 0: 43 | n.pop() 44 | return n[-1] -------------------------------------------------------------------------------- /Easy/20.ValidParentheses(BruteForce).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string containing just the characters '(', ')', '{', '}', '[', ']', 3 | determine if the input string is valid. 4 | 5 | An input string is valid if: 6 | 1. Open brackets must be closed by the same type of brackets. 7 | 2. Open brackets must be closed in the correct order. 8 | 9 | Note that an empty string is also considered valid. 10 | 11 | Example: 12 | Input: "()[]{}" 13 | Output: true 14 | """ 15 | #Difficulty: Easy 16 | #76 / 76 test cases passed. 17 | #Runtime: 44 ms 18 | #Memory Usage: 14 MB 19 | 20 | #Runtime: 44 ms, faster than 23.31% of Python3 online submissions for Valid Parentheses. 21 | #Memory Usage: 14 MB, less than 25.86% of Python3 online submissions for Valid Parentheses. 22 | 23 | class Solution: 24 | def isValid(self, s: str) -> bool: 25 | parentheses = {'()', '{}', '[]'} 26 | length = len(s) 27 | if length < 2: 28 | return not s 29 | i = 1 30 | while s: 31 | if s[i-1:i+1] in parentheses: 32 | s = s[:i-1] + s[i+1:] 33 | i -= 1 34 | else: 35 | i += 1 36 | if i == length: 37 | break 38 | return not s 39 | -------------------------------------------------------------------------------- /Easy/20.ValidParentheses(Stack).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string containing just the characters '(', ')', '{', '}', '[', ']', 3 | determine if the input string is valid. 4 | 5 | An input string is valid if: 6 | 1. Open brackets must be closed by the same type of brackets. 7 | 2. Open brackets must be closed in the correct order. 8 | 9 | Note that an empty string is also considered valid. 10 | 11 | Example: 12 | Input: "()[]{}" 13 | Output: true 14 | """ 15 | #Difficulty: Easy 16 | #76 / 76 test cases passed. 17 | #Runtime: 28 ms 18 | #Memory Usage: 13.8 MB 19 | 20 | #Runtime: 28 ms, faster than 82.23% of Python3 online submissions for Valid Parentheses. 21 | #Memory Usage: 13.8 MB, less than 64.83% of Python3 online submissions for Valid Parentheses. 22 | 23 | class Solution: 24 | def isValid(self, s: str) -> bool: 25 | parentheses = {'(':')', '{':'}', '[':']'} 26 | stack = [] 27 | for b in s: # take bracket 'b' from string 's' 28 | if b in parentheses: # if bracket in parentheses 29 | stack.append(parentheses[b]) # append it's opposite to stack 30 | elif not stack or stack.pop() != b: # if not stack or bracket not 31 | return False # equal last bracket in stack 32 | return not stack # if stack still exists -> False else True 33 | -------------------------------------------------------------------------------- /Easy/203.RemoveLinkedListElements.py: -------------------------------------------------------------------------------- 1 | """ 2 | Remove all elements from a linked list of integers that have value val. 3 | 4 | Example: 5 | Input: 1->2->6->3->4->5->6, val = 6 6 | Output: 1->2->3->4->5 7 | """ 8 | #Difficulty: Easy 9 | #65 / 65 test cases passed. 10 | #Runtime: 68 ms 11 | #Memory Usage: 16.9 MB 12 | 13 | #Runtime: 68 ms, faster than 88.02% of Python3 online submissions for Remove Linked List Elements. 14 | #Memory Usage: 16.9 MB, less than 56.57% of Python3 online submissions for Remove Linked List Elements. 15 | 16 | # Definition for singly-linked list. 17 | # class ListNode: 18 | # def __init__(self, val=0, next=None): 19 | # self.val = val 20 | # self.next = next 21 | 22 | class Solution: 23 | def removeElements(self, head: ListNode, val: int) -> ListNode: 24 | while head: 25 | if head.val == val: 26 | head = head.next 27 | else: 28 | break 29 | if not head: 30 | return 31 | node = head 32 | while node: 33 | if node.val == val: 34 | if node.next: 35 | node.val = node.next.val 36 | node.next = node.next.next 37 | continue 38 | else: 39 | prev.next = None 40 | if not node.next: 41 | return head 42 | prev = node 43 | node = node.next 44 | -------------------------------------------------------------------------------- /Easy/204.CountPrimes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Count the number of prime numbers less than a non-negative 3 | number, n. 4 | 5 | Example: 6 | Input: n = 10 7 | Output: 4 8 | Explanation: There are 4 prime numbers less than 10, 9 | they are 2, 3, 5, 7. 10 | 11 | Example: 12 | Input: n = 0 13 | Output: 0 14 | 15 | Example: 16 | Input: n = 1 17 | Output: 0 18 | 19 | Constraints: 20 | 0 <= n <= 5 * 10^6 21 | ''' 22 | #Difficulty: Easy 23 | #21 / 21 test cases passed. 24 | #Runtime: 1744 ms 25 | #Memory Usage: 92.1 MB 26 | 27 | #Runtime: 1744 ms, faster than 31.36% of Python3 online submissions for Count Primes. 28 | #Memory Usage: 92.1 MB, less than 17.77% of Python3 online submissions for Count Primes. 29 | 30 | class Solution: 31 | def countPrimes(self, n: int) -> int: 32 | is_prime = [True] * n 33 | i = 2 34 | while i * i < n: 35 | if is_prime[i]: 36 | j = i * i 37 | while j < n: 38 | is_prime[j] = False 39 | j += i 40 | i += 1 41 | return sum(is_prime[2:]) -------------------------------------------------------------------------------- /Easy/205.IsomorphicStrings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings s and t, determine if they are isomorphic. 3 | Two strings are isomorphic if the characters in s can be replaced to get t. 4 | All occurrences of a character must be replaced with another character 5 | while preserving the order of characters. No two characters may map to the 6 | same character but a character may map to itself. 7 | 8 | Example: 9 | Input: s = "paper", t = "title" 10 | Output: true 11 | 12 | Note: 13 | You may assume both s and t have the same length. 14 | """ 15 | #Difficulty: Easy 16 | #32 / 32 test cases passed. 17 | #Runtime: 48 ms 18 | #Memory Usage: 14 MB 19 | 20 | #Runtime: 48 ms, faster than 45.10% of Python3 online submissions for Isomorphic Strings. 21 | #Memory Usage: 14 MB, less than 64.61% of Python3 online submissions for Isomorphic Strings. 22 | 23 | class Solution: 24 | def isIsomorphic(self, s: str, t: str) -> bool: 25 | d = {} 26 | for i in range(len(s)): 27 | if s[i] in d: 28 | if d[s[i]] != t[i]: 29 | return False 30 | elif t[i] not in d.values(): 31 | d[s[i]] = t[i] 32 | else: 33 | return False 34 | return True 35 | -------------------------------------------------------------------------------- /Easy/206.ReverseLinkedList(rightappr).py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse a singly linked list. 3 | 4 | Example: 5 | Input: 1->2->3->4->5->NULL 6 | Output: 5->4->3->2->1->NULL 7 | 8 | Follow up: 9 | A linked list can be reversed either iteratively or recursively. Could you 10 | implement both? 11 | """ 12 | #Difficulty: Easy 13 | #27 / 27 test cases passed. 14 | #Runtime: 48 ms 15 | #Memory Usage: 15.3 MB 16 | 17 | #Runtime: 48 ms, faster than 30.10% of Python3 online submissions for Reverse Linked List. 18 | #Memory Usage: 15.3 MB, less than 60.64% of Python3 online submissions for Reverse Linked List. 19 | 20 | # Definition for singly-linked list. 21 | # class ListNode: 22 | # def __init__(self, val=0, next=None): 23 | # self.val = val 24 | # self.next = next 25 | 26 | class Solution: 27 | def reverseList(self, head: ListNode) -> ListNode: 28 | prev = None 29 | current = head 30 | next_element = None 31 | while current: 32 | next_element = current.next 33 | current.next = prev 34 | prev = current 35 | current = next_element 36 | return prev 37 | -------------------------------------------------------------------------------- /Easy/206.ReverseLinkedList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse a singly linked list. 3 | 4 | Example: 5 | Input: 1->2->3->4->5->NULL 6 | Output: 5->4->3->2->1->NULL 7 | 8 | Follow up: 9 | A linked list can be reversed either iteratively or recursively. Could you 10 | implement both? 11 | """ 12 | #Difficulty: Easy 13 | #27 / 27 test cases passed. 14 | #Runtime: 720 ms 15 | #Memory Usage: 16.2 MB 16 | 17 | #Runtime: 720 ms, faster than 5.95% of Python3 online submissions for Reverse Linked List. 18 | #Memory Usage: 16.2 MB, less than 24.09% of Python3 online submissions for Reverse Linked List. 19 | 20 | # Definition for singly-linked list. 21 | # class ListNode: 22 | # def __init__(self, val=0, next=None): 23 | # self.val = val 24 | # self.next = next 25 | 26 | class Solution: 27 | def reverseList(self, head: ListNode) -> ListNode: 28 | if not head: 29 | return 30 | stack = [] 31 | while head: 32 | stack.append(head.val) 33 | head = head.next 34 | new_head = ListNode(stack.pop()) 35 | while stack: 36 | self.addAtTail(new_head, stack.pop()) 37 | return new_head 38 | 39 | def addAtTail(self, node, val): 40 | while node.next: 41 | node = node.next 42 | node.next = ListNode(val) 43 | -------------------------------------------------------------------------------- /Easy/217.ContainsDuplicate(Dict).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, find if the array contains any duplicates. 3 | Your function should return true if any value appears at least twice in 4 | the array, and it should return false if every element is distinct. 5 | 6 | Example: 7 | Input: [1,1,1,3,3,4,3,2,4,2] 8 | Output: true 9 | """ 10 | #Difficulty: Easy 11 | #18 / 18 test cases passed. 12 | #Runtime: 144 ms 13 | #Memory Usage: 20.1 MB 14 | 15 | #Runtime: 144 ms, faster than 31.07% of Python3 online submissions for Contains Duplicate. 16 | #Memory Usage: 20.1 MB, less than 27.68% of Python3 online submissions for Contains Duplicate. 17 | 18 | class Solution: 19 | def containsDuplicate(self, nums: List[int]) -> bool: 20 | d = {} 21 | for num in nums: 22 | if num in d.keys(): 23 | return d[num] 24 | d[num] = True 25 | return False 26 | -------------------------------------------------------------------------------- /Easy/219.ContainsDuplicateII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers and an integer k, find out whether there are two 3 | distinct indices i and j in the array such that nums[i] = nums[j] and the 4 | absolute difference between i and j is at most k. 5 | 6 | Example: 7 | Input: nums = [1,2,3,1], k = 3 8 | Output: true 9 | """ 10 | #Difficulty: Easy 11 | #23 / 23 test cases passed. 12 | #Runtime: 92 ms 13 | #Memory Usage: 24.8 MB 14 | 15 | #Runtime: 92 ms, faster than 86.57% of Python3 online submissions for Contains Duplicate II. 16 | #Memory Usage: 24.8 MB, less than 11.60% of Python3 online submissions for Contains Duplicate II. 17 | 18 | class Solution: 19 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 20 | d = {} 21 | for i, num in enumerate(nums): 22 | if num in d: 23 | if i - d[num][-1] <= k: 24 | return True 25 | d[num].append(i) 26 | else: 27 | d[num] = [i] 28 | return False 29 | -------------------------------------------------------------------------------- /Easy/226.InvertBinaryTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Invert a binary tree. 3 | 4 | Example: 5 | Input: 6 | 4 7 | / \ 8 | 2 7 9 | / \ / \ 10 | 1 3 6 9 11 | 12 | Output: 13 | 4 14 | / \ 15 | 7 2 16 | / \ / \ 17 | 9 6 3 1 18 | 19 | Trivia: 20 | This problem was inspired by this original tweet by Max Howell: 21 | Google: 90% of our engineers use the software you wrote (Homebrew), 22 | but you can’t invert a binary tree on a whiteboard so f*** off. 23 | """ 24 | #Difficulty: Easy 25 | #68 / 68 test cases passed. 26 | #Runtime: 40 ms 27 | #Memory Usage: 13.6 MB 28 | 29 | #Runtime: 40 ms, faster than 10.02% of Python3 online submissions for Invert Binary Tree. 30 | #Memory Usage: 13.6 MB, less than 94.69% of Python3 online submissions for Invert Binary Tree. 31 | 32 | # Definition for a binary tree node. 33 | # class TreeNode: 34 | # def __init__(self, val=0, left=None, right=None): 35 | # self.val = val 36 | # self.left = left 37 | # self.right = right 38 | 39 | class Solution: 40 | def invertTree(self, root: TreeNode) -> TreeNode: 41 | if not root: 42 | return 43 | root.left, root.right = root.right, root.left 44 | self.invertTree(root.left) 45 | self.invertTree(root.right) 46 | return root 47 | -------------------------------------------------------------------------------- /Easy/234.PalindromeLinkedList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a singly linked list, determine if it is a palindrome. 3 | 4 | Example: 5 | Input: 1->2->2->1 6 | Output: true 7 | 8 | Follow up: 9 | Could you do it in O(n) time and O(1) space? 10 | """ 11 | #Difficulty: Easy 12 | #26 / 26 test cases passed. 13 | #Runtime: 96 ms 14 | #Memory Usage: 23.8 MB 15 | 16 | #Runtime: 96 ms, faster than 31.45% of Python3 online submissions for Palindrome Linked List. 17 | #Memory Usage: 23.8 MB, less than 94.98% of Python3 online submissions for Palindrome Linked List. 18 | 19 | # Definition for singly-linked list. 20 | # class ListNode: 21 | # def __init__(self, val=0, next=None): 22 | # self.val = val 23 | # self.next = next 24 | 25 | class Solution: 26 | def isPalindrome(self, head: ListNode) -> bool: 27 | nums = [] 28 | while head: 29 | nums.append(head.val) 30 | head = head.next 31 | i = 0 32 | j = len(nums) - 1 33 | while i <= j: 34 | if nums[i] != nums[j]: 35 | return False 36 | i += 1 37 | j -= 1 38 | return True 39 | -------------------------------------------------------------------------------- /Easy/242.ValidAnagram.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings s and t , write a function to determine 3 | if t is an anagram of s. 4 | 5 | Example: 6 | Input: s = "anagram", t = "nagaram" 7 | Output: true 8 | 9 | Example: 10 | Input: s = "rat", t = "car" 11 | Output: false 12 | 13 | Note: 14 | You may assume the string contains only lowercase alphabets. 15 | 16 | Follow up: 17 | What if the inputs contain unicode characters? How would 18 | you adapt your solution to such case? 19 | ''' 20 | #Dfficulty: Easy 21 | #34 / 34 test cases passed. 22 | #Runtime: 32 ms 23 | #Memory Usage: 14.5 MB 24 | 25 | #Runtime: 32 ms, faster than 98.22% of Python3 online submissions for Valid Anagram. 26 | #Memory Usage: 14.5 MB, less than 48.96% of Python3 online submissions for Valid Anagram. 27 | 28 | class Solution: 29 | def isAnagram(self, s: str, t: str) -> bool: 30 | if not s and not t: return True 31 | if not s or not t or len(s) != len(t): return False 32 | i = 0 33 | c = set(s+t) 34 | result = False 35 | for l in c: 36 | if l in s and l in t and s.count(l) == t.count(l): 37 | result = True 38 | continue 39 | else: 40 | result = False 41 | break 42 | return result -------------------------------------------------------------------------------- /Easy/257.BinaryTreePaths.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, return all root-to-leaf paths. 3 | Note: A leaf is a node with no children. 4 | 5 | Example: 6 | Input: 7 | 1 8 | / \ 9 | 2 3 10 | \ 11 | 5 12 | 13 | Output: ["1->2->5", "1->3"] 14 | Explanation: All root-to-leaf paths are: 1->2->5, 1->3 15 | """ 16 | #Difficulty: Easy 17 | #209 / 209 test cases passed. 18 | #Runtime: 16 ms 19 | #Memory Usage: 13.8 MB 20 | 21 | #Runtime: 16 ms, faster than 99.92% of Python3 online submissions for Binary Tree Paths. 22 | #Memory Usage: 13.8 MB, less than 78.79% of Python3 online submissions for Binary Tree Paths. 23 | 24 | # Definition for a binary tree node. 25 | # class TreeNode: 26 | # def __init__(self, val=0, left=None, right=None): 27 | # self.val = val 28 | # self.left = left 29 | # self.right = right 30 | 31 | class Solution: 32 | 33 | def binaryTreePaths(self, root: TreeNode) -> List[str]: 34 | paths = [] 35 | path = '' 36 | self.preorder(root, path, paths) 37 | return paths 38 | 39 | def preorder(self, root, path, paths): 40 | if not root: 41 | return 42 | path += str(root.val) + '->' 43 | self.preorder(root.left, path, paths) 44 | self.preorder(root.right, path, paths) 45 | if not root.left and not root.right: 46 | path = path[:-2] 47 | paths.append(path) 48 | -------------------------------------------------------------------------------- /Easy/258.AddDigits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative integer num, repeatedly add all its 3 | digits until the result has only one digit. 4 | 5 | Example: 6 | Input: 38 7 | Output: 2 8 | Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 9 | Since 2 has only one digit, return it. 10 | 11 | Follow up: 12 | Could you do it without any loop/recursion in O(1) 13 | runtime? 14 | ''' 15 | #Difficulty: Easy 16 | #1101 / 1101 test cases passed. 17 | #Runtime: 36 ms 18 | #Memory Usage: 14.2 MB 19 | 20 | #Runtime: 36 ms, faster than 28.26% of Python3 online submissions for Add Digits. 21 | #Memory Usage: 14.2 MB, less than 51.11% of Python3 online submissions for Add Digits. 22 | 23 | class Solution: 24 | def addDigits(self, num: int) -> int: 25 | while num > 9: 26 | num = num//10 + num%10 27 | return num 28 | -------------------------------------------------------------------------------- /Easy/268.MissingNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, 3 | find the one that is missing from the array. 4 | 5 | Example: 6 | Input: [9,6,4,2,3,5,7,0,1] 7 | Output: 8 8 | 9 | Note: 10 | Your algorithm should run in linear runtime complexity. Could you implement 11 | it using only constant extra space complexity? 12 | """ 13 | #Difficulty: Easy 14 | #122 / 122 test cases passed. 15 | #Runtime: 132 ms 16 | #Memory Usage: 14.9 MB 17 | 18 | #Runtime: 132 ms, faster than 93.14% of Python3 online submissions for Missing Number. 19 | #Memory Usage: 14.9 MB, less than 89.02% of Python3 online submissions for Missing Number. 20 | 21 | class Solution: 22 | def missingNumber(self, nums: List[int]) -> int: 23 | max_number = max(nums) + 1 24 | range_sum = sum([i for i in range(max_number)]) 25 | nums_sum = sum(nums) 26 | missing_number = range_sum - nums_sum 27 | return missing_number if missing_number not in nums else max_number 28 | -------------------------------------------------------------------------------- /Easy/27.RemoveElement.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array nums and a value val, remove all instances of that value 3 | in-place and return the new length. 4 | Do not allocate extra space for another array, you must do this by modifying 5 | the input array in-place with O(1) extra memory. 6 | The order of elements can be changed. It doesn't matter what you leave 7 | beyond the new length. 8 | 9 | Example: 10 | Given nums = [3,2,2,3], val = 3, 11 | Your function should return length = 2, with the first two elements of nums 12 | being 2. 13 | It doesn't matter what you leave beyond the returned length. 14 | """ 15 | #Difficulty: Easy 16 | #113 / 113 test cases passed. 17 | #Runtime: 28 ms 18 | #Memory Usage: 13.6 MB 19 | 20 | #Runtime: 28 ms, faster than 88.43% of Python3 online submissions for Remove Element. 21 | #Memory Usage: 13.6 MB, less than 6.06% of Python3 online submissions for Remove Element. 22 | 23 | class Solution: 24 | def removeElement(self, nums: List[int], val: int) -> int: 25 | length = len(nums)-1 26 | while val in nums: 27 | if nums[length] == val: 28 | nums.pop(length) 29 | length-=1 30 | return len(nums) 31 | -------------------------------------------------------------------------------- /Easy/326.PowerofThree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer n, return true if it is a power of 3 | three. Otherwise, return false. 4 | 5 | An integer n is a power of three, if there exists an 6 | integer x such that n == 3x. 7 | 8 | Example: 9 | Input: n = 27 10 | Output: true 11 | 12 | Example: 13 | Input: n = 0 14 | Output: false 15 | 16 | Example: 17 | Input: n = 9 18 | Output: true 19 | 20 | Example: 21 | Input: n = 45 22 | Output: false 23 | 24 | Constraints: 25 | - -2^31 <= n <= 2^31 - 1 26 | 27 | Follow up: Could you solve it without loops/recursion? 28 | ''' 29 | #Difficulty: Easy 30 | #21038 / 21038 test cases passed. 31 | #Runtime: 188 ms 32 | #Memory Usage: 14.3 MB 33 | 34 | #Runtime: 188 ms, faster than 6.05% of Python3 online submissions for Power of Three. 35 | #Memory Usage: 14.3 MB, less than 47.05% of Python3 online submissions for Power of Three. 36 | 37 | class Solution: 38 | def isPowerOfThree(self, n: int) -> bool: 39 | x = 0 40 | while 3 ** x <= n: 41 | if 3 ** x == n: 42 | return True 43 | x += 1 44 | return False -------------------------------------------------------------------------------- /Easy/342.PowerofFour(BruteForce).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer (signed 32 bits), write a function to check whether it is 3 | a power of 4. 4 | 5 | Example: 6 | Input: 16 7 | Output: true 8 | 9 | Follow up: Could you solve it without loops/recursion? 10 | """ 11 | #Difficulty: Easy 12 | #1060 / 1060 test cases passed. 13 | #Runtime: 24 ms 14 | #Memory Usage: 13.7 MB 15 | 16 | #Runtime: 24 ms, faster than 96.97% of Python3 online submissions for Power of Four. 17 | #Memory Usage: 13.7 MB, less than 78.95% of Python3 online submissions for Power of Four. 18 | 19 | class Solution: 20 | def isPowerOfFour(self, num: int) -> bool: 21 | if num in [1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824]: 22 | return True 23 | return False 24 | -------------------------------------------------------------------------------- /Easy/342.PowerofFour.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer (signed 32 bits), write a function to check whether it is 3 | a power of 4. 4 | 5 | Example: 6 | Input: 16 7 | Output: true 8 | 9 | Follow up: Could you solve it without loops/recursion? 10 | """ 11 | #Difficulty: Easy 12 | #1060 / 1060 test cases passed. 13 | #Runtime: 28 ms 14 | #Memory Usage: 13.6 MB 15 | 16 | #Runtime: 28 ms, faster than 88.81% of Python3 online submissions for Power of Four. 17 | #Memory Usage: 13.6 MB, less than 93.86% of Python3 online submissions for Power of Four. 18 | 19 | class Solution: 20 | def isPowerOfFour(self, num: int) -> bool: 21 | if num != 0: 22 | return (num & (num - 1) == 0) & len(bin(num)) % 2 == 1 23 | return False 24 | -------------------------------------------------------------------------------- /Easy/344.ReverseString.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that reverses a string. The input string is given as an 3 | array of characters char[]. 4 | Do not allocate extra space for another array, you must do this by 5 | modifying the input array in-place with O(1) extra memory. 6 | You may assume all the characters consist of printable ascii characters. 7 | 8 | Example: 9 | Input: ["h","e","l","l","o"] 10 | Output: ["o","l","l","e","h"] 11 | """ 12 | #Difficulty: Easy 13 | #478 / 478 test cases passed. 14 | #Runtime: 204 ms 15 | #Memory Usage: 18 MB 16 | 17 | #Runtime: 204 ms, faster than 91.57% of Python3 online submissions for Reverse String. 18 | #Memory Usage: 18 MB, less than 5.81% of Python3 online submissions for Reverse String. 19 | 20 | class Solution: 21 | def reverseString(self, s: List[str]) -> None: 22 | i = 0 23 | l = len(s) - 1 24 | while i <= l: 25 | s[i], s[l] = s[l], s[i] 26 | i += 1 27 | l -= 1 28 | return s 29 | -------------------------------------------------------------------------------- /Easy/345.ReverseVowelsofaString(list).py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a string as input and reverse only the vowels 3 | of a string. 4 | 5 | Example: 6 | Input: "hello" 7 | Output: "holle" 8 | 9 | Example: 10 | Input: "leetcode" 11 | Output: "leotcede" 12 | 13 | Note: 14 | - The vowels does not include the letter "y". 15 | """ 16 | #Difficulty: Easy 17 | #481 / 481 test cases passed. 18 | #Runtime: 48 ms 19 | #Memory Usage: 14.8 MB 20 | 21 | #Runtime: 48 ms, faster than 92.51% of Python3 online submissions for Reverse Vowels of a String. 22 | #Memory Usage: 14.8 MB, less than 61.15% of Python3 online submissions for Reverse Vowels of a String 23 | 24 | class Solution: 25 | def reverseVowels(self, s: str) -> str: 26 | s = list(s) 27 | i = 0 28 | l = len(s) - 1 29 | #vowels = 'aAeEiIoOuU' 30 | vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} 31 | while i < l: 32 | if s[i] in vowels: 33 | while s[l] not in vowels: 34 | l -= 1 35 | if i < l: 36 | s[i], s[l] = s[l], s[i] 37 | i += 1 38 | l -= 1 39 | continue 40 | i += 1 41 | return ''.join(s) 42 | -------------------------------------------------------------------------------- /Easy/345.ReverseVowelsofaString(string).py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a string as input and reverse only the vowels 3 | of a string. 4 | 5 | Example: 6 | Input: "hello" 7 | Output: "holle" 8 | 9 | Example: 10 | Input: "leetcode" 11 | Output: "leotcede" 12 | 13 | Note: 14 | - The vowels does not include the letter "y". 15 | """ 16 | #Difficulty: Easy 17 | #481 / 481 test cases passed. 18 | #Runtime: 184 ms 19 | #Memory Usage: 14.4 MB 20 | 21 | #Runtime: 184 ms, faster than 7.25% of Python3 online submissions for Reverse Vowels of a String. 22 | #Memory Usage: 14.4 MB, less than 96.24% of Python3 online submissions for Reverse Vowels of a String. 23 | 24 | class Solution: 25 | def reverseVowels(self, s: str) -> str: 26 | i = 0 27 | l = len(s) - 1 28 | #vowels = 'aAeEiIoOuU' 29 | vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} 30 | while i < l: 31 | if s[i] in vowels: 32 | while s[l] not in vowels: 33 | l -= 1 34 | if i < l: 35 | s = s[:i] + s[l] + s[i+1:l] + s[i] + s[l+1:] 36 | i += 1 37 | l -= 1 38 | continue 39 | i += 1 40 | return s 41 | -------------------------------------------------------------------------------- /Easy/35.SearchInsertPosition.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sorted array and a target value, return the index if the target is 3 | found. If not, return the index where it would be if it were inserted in 4 | order. 5 | You may assume no duplicates in the array. 6 | 7 | Example: 8 | Input: [1,3,5,6], 7 9 | Output: 4 10 | """ 11 | #Difficulty: Easy 12 | #62 / 62 test cases passed. 13 | #Runtime: 44 ms 14 | #Memory Usage: 14.5 MB 15 | 16 | #Runtime: 44 ms, faster than 91.93% of Python3 online submissions for Search Insert Position. 17 | #Memory Usage: 14.5 MB, less than 5.97% of Python3 online submissions for Search Insert Position. 18 | 19 | class Solution: 20 | def searchInsert(self, nums: List[int], target: int) -> int: 21 | l = 0 22 | r = len(nums)-1 23 | while l <= r: 24 | m = (l+r)//2 25 | if m == r and target > nums[m]: 26 | return m + 1 27 | if target > nums[m]: 28 | l = m + 1 29 | else: 30 | r = m - 1 31 | return m 32 | -------------------------------------------------------------------------------- /Easy/387.FirstUniqueCharacterinaString(BruteForce).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, find the first non-repeating character in it and return its 3 | index. If it doesn't exist, return -1. 4 | 5 | Examples: 6 | s = "leetcode" 7 | return 0. 8 | s = "loveleetcode" 9 | return 2. 10 | 11 | Note: You may assume the string contains only lowercase English letters. 12 | """ 13 | #Difficulty: Easy 14 | #104 / 104 test cases passed. 15 | #Runtime: 9232 ms 16 | #Memory Usage: 13.9 MB 17 | 18 | class Solution: 19 | def firstUniqChar(self, s: str) -> int: 20 | if not s: 21 | return -1 22 | for index, letter in enumerate(s): 23 | if s.count(letter) == 1: 24 | return index 25 | return -1 26 | -------------------------------------------------------------------------------- /Easy/387.FirstUniqueCharacterinaString.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, find the first non-repeating character in it and return its 3 | index. If it doesn't exist, return -1. 4 | 5 | Examples: 6 | s = "leetcode" 7 | return 0. 8 | s = "loveleetcode" 9 | return 2. 10 | 11 | Note: You may assume the string contains only lowercase English letters. 12 | """ 13 | #Difficulty: Easy 14 | #104 / 104 test cases passed. 15 | #Runtime: 104 ms 16 | #Memory Usage: 13.9 MB 17 | 18 | #Runtime: 104 ms, faster than 71.09% of Python3 online submissions for First Unique Character in a String. 19 | #Memory Usage: 13.9 MB, less than 46.48% of Python3 online submissions for First Unique Character in a String. 20 | 21 | class Solution: 22 | def firstUniqChar(self, s: str) -> int: 23 | d = {} 24 | mi = len(s) 25 | for index, letter in enumerate(s): 26 | if letter in d: 27 | if d[letter][0]: 28 | d[letter][0] -= 1 29 | else: 30 | continue 31 | else: 32 | d[letter] = [1, index] 33 | for value in d.values(): 34 | if value[0] == 1: 35 | mi = min(mi, value[1]) 36 | return mi if mi != len(s) else -1 37 | -------------------------------------------------------------------------------- /Easy/389.FindtheDifference(set).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings s and t which consist of only lowercase letters. 3 | String t is generated by random shuffling string s and then add one more 4 | letter at a random position. 5 | Find the letter that was added in t. 6 | 7 | Example: 8 | Input: 9 | s = "abcd" 10 | t = "abcde" 11 | Output: 12 | e 13 | Explanation: 14 | 'e' is the letter that was added. 15 | """ 16 | #Difficulty: Easy 17 | #54 / 54 test cases passed. 18 | #Runtime: 24 ms 19 | #Memory Usage: 14.1 MB 20 | 21 | #Runtime: 24 ms, faster than 97.91% of Python3 online submissions for Find the Difference. 22 | #Memory Usage: 14.1 MB, less than 5.37% of Python3 online submissions for Find the Difference. 23 | 24 | class Solution: 25 | def findTheDifference(self, s: str, t: str) -> str: 26 | chars = set(t) 27 | for char in chars: 28 | if t.count(char) != s.count(char): 29 | return char 30 | -------------------------------------------------------------------------------- /Easy/389.FindtheDifference.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings s and t which consist of only lowercase letters. 3 | String t is generated by random shuffling string s and then add one more 4 | letter at a random position. 5 | Find the letter that was added in t. 6 | 7 | Example: 8 | Input: 9 | s = "abcd" 10 | t = "abcde" 11 | Output: 12 | e 13 | Explanation: 14 | 'e' is the letter that was added. 15 | """ 16 | #Difficulty: Easy 17 | #54 / 54 test cases passed. 18 | #Runtime: 40 ms 19 | #Memory Usage: 13.6 MB 20 | 21 | #Runtime: 40 ms, faster than 35.80% of Python3 online submissions for Find the Difference. 22 | #Memory Usage: 13.6 MB, less than 98.36% of Python3 online submissions for Find the Difference. 23 | 24 | class Solution: 25 | def findTheDifference(self, s: str, t: str) -> str: 26 | for char in t: 27 | if char not in s: 28 | return char 29 | else: 30 | s = s.replace(char, '', 1) 31 | -------------------------------------------------------------------------------- /Easy/404.SumofLeftLeaves.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find the sum of all left leaves in a given binary tree. 3 | 4 | Example: 5 | 6 | 3 7 | / \ 8 | 9 20 9 | / \ 10 | 15 7 11 | There are two left leaves in the binary tree, with values 9 and 15 12 | respectively. Return 24. 13 | """ 14 | #Difficulty: Easy 15 | #102 / 102 test cases passed. 16 | #Runtime: 28 ms 17 | #Memory Usage: 14.2 MB 18 | 19 | #Runtime: 28 ms, faster than 91.15% of Python3 online submissions for Sum of Left Leaves. 20 | #Memory Usage: 14.2 MB, less than 78.35% of Python3 online submissions for Sum of Left Leaves. 21 | 22 | # Definition for a binary tree node. 23 | # class TreeNode: 24 | # def __init__(self, val=0, left=None, right=None): 25 | # self.val = val 26 | # self.left = left 27 | # self.right = right 28 | 29 | class Solution: 30 | def sumOfLeftLeaves(self, root: TreeNode) -> int: 31 | result = [] 32 | self.preorder(root, result) 33 | return sum(result) 34 | 35 | def preorder(self, root, result): 36 | if not root: 37 | return 0 38 | if root.left and not root.left.left and not root.left.right: 39 | result.append(root.left.val) 40 | self.preorder(root.left, result) 41 | self.preorder(root.right, result) 42 | -------------------------------------------------------------------------------- /Easy/409.LongestPalindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string which consists of lowercase or uppercase letters, find the 3 | length of the longest palindromes that can be built with those letters. 4 | This is case sensitive, for example "Aa" is not considered a palindrome 5 | here. 6 | 7 | Note: 8 | Assume the length of given string will not exceed 1,010. 9 | 10 | Example: 11 | Input: 12 | "abccccdd" 13 | Output: 14 | 7 15 | Explanation: 16 | One longest palindrome that can be built is "dccaccd", 17 | whose length is 7. 18 | """ 19 | #Difficulty: Easy 20 | #95 / 95 test cases passed. 21 | #Runtime: 28 ms 22 | #Memory Usage: 14 MB 23 | 24 | #Runtime: 28 ms, faster than 91.20% of Python3 online submissions for Longest Palindrome. 25 | #Memory Usage: 14 MB, less than 9.61% of Python3 online submissions for Longest Palindrome. 26 | 27 | class Solution: 28 | def longestPalindrome(self, s: str) -> int: 29 | chars_set = set(s) 30 | length = 0 31 | odd = 0 32 | for char in chars_set: 33 | count = s.count(char) 34 | if count % 2: 35 | odd += 1 36 | length += count 37 | return length - odd + 1 if odd else length 38 | -------------------------------------------------------------------------------- /Easy/412.FizzBuzz.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that outputs the string representation of numbers from 1 3 | to n. 4 | But for multiples of three it should output “Fizz” instead of the number 5 | and for the multiples of five output “Buzz”. For numbers which are 6 | multiples of both three and five output “FizzBuzz”. 7 | 8 | Example: 9 | n = 15, 10 | Return: 11 | [ 12 | "1", 13 | "2", 14 | "Fizz", 15 | "4", 16 | "Buzz", 17 | "Fizz", 18 | "7", 19 | "8", 20 | "Fizz", 21 | "Buzz", 22 | "11", 23 | "Fizz", 24 | "13", 25 | "14", 26 | "FizzBuzz" 27 | ] 28 | """ 29 | #Difficulty: Easy 30 | #8 / 8 test cases passed. 31 | #Runtime: 40 ms 32 | #Memory Usage: 14.7 MB 33 | 34 | #Runtime: 40 ms, faster than 88.30% of Python3 online submissions for Fizz Buzz. 35 | #Memory Usage: 14.7 MB, less than 96.17% of Python3 online submissions for Fizz Buzz. 36 | 37 | class Solution: 38 | def fizzBuzz(self, n: int) -> List[str]: 39 | i = 1 40 | result = [] 41 | while i <= n: 42 | if not i % 3 and not i % 5: 43 | result.append('FizzBuzz') 44 | elif not i % 5: 45 | result.append('Buzz') 46 | elif not i % 3: 47 | result.append('Fizz') 48 | else: 49 | result.append(str(i)) 50 | i += 1 51 | return result 52 | -------------------------------------------------------------------------------- /Easy/441.ArrangingCoins.py: -------------------------------------------------------------------------------- 1 | """ 2 | You have a total of n coins that you want to form in a staircase shape, 3 | where every k-th row must have exactly k coins. 4 | Given n, find the total number of full staircase rows that can be formed. 5 | n is a non-negative integer and fits within the range of a 32-bit signed 6 | integer. 7 | 8 | Example: 9 | n = 8 10 | The coins can form the following rows: 11 | ¤ 12 | ¤ ¤ 13 | ¤ ¤ ¤ 14 | ¤ ¤ 15 | Because the 4th row is incomplete, we return 3. 16 | """ 17 | #Difficulty: Easy 18 | #1336 / 1336 test cases passed. 19 | #Runtime: 852 ms 20 | #Memory Usage: 13.8 MB 21 | 22 | #Runtime: 852 ms, faster than 47.02% of Python3 online submissions for Arranging Coins. 23 | #Memory Usage: 13.8 MB, less than 54.40% of Python3 online submissions for Arranging Coins. 24 | 25 | class Solution: 26 | def arrangeCoins(self, n: int) -> int: 27 | i = 0 28 | while i < n: 29 | i += 1 30 | n -= i 31 | return i 32 | -------------------------------------------------------------------------------- /Easy/459.RepeatedSubstringPattern.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-empty string check if it can be constructed by taking a 3 | substring of it and appending multiple copies of the substring together. 4 | You may assume the given string consists of lowercase English letters only 5 | and its length will not exceed 10000. 6 | 7 | Example: 8 | Input: "abab" 9 | Output: True 10 | Explanation: It's the substring "ab" twice. 11 | 12 | Example: 13 | Input: "aba" 14 | Output: False 15 | 16 | Example: 17 | Input: "abcabcabcabc" 18 | Output: True 19 | Explanation: It's the substring "abc" four times. 20 | (And the substring "abcabc" twice.) 21 | """ 22 | #Difficulty: Easy 23 | #120 / 120 test cases passed. 24 | #Runtime: 124 ms 25 | #Memory Usage: 13.6 MB 26 | 27 | #Runtime: 124 ms, faster than 45.73% of Python3 online submissions for Repeated Substring Pattern. 28 | #Memory Usage: 13.6 MB, less than 96.45% of Python3 online submissions for Repeated Substring Pattern. 29 | 30 | class Solution: 31 | def repeatedSubstringPattern(self, s: str) -> bool: 32 | length = len(s) 33 | l = 1 + length // 2 34 | i = 1 35 | while i < l: 36 | if s[:i] * (length // i) == s: 37 | return True 38 | i += 1 39 | return False 40 | -------------------------------------------------------------------------------- /Easy/476.NumberComplement.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer num, output its complement number. The complement 3 | strategy is to flip the bits of its binary representation. 4 | 5 | Example: 6 | Input: num = 5 7 | Output: 2 8 | Explanation: The binary representation of 5 is 101 (no leading zero bits), 9 | and its complement is 010. So you need to output 2. 10 | 11 | Example: 12 | Input: num = 1 13 | Output: 0 14 | Explanation: The binary representation of 1 is 1 (no leading zero bits), 15 | and its complement is 0. So you need to output 0. 16 | 17 | Constraints: 18 | - The given integer num is guaranteed to fit within the range of a 19 | 32-bit signed integer. 20 | - num >= 1 21 | - You could assume no leading zero bit in the integer’s binary 22 | representation. 23 | - This question is the same as 1009: 24 | https://leetcode.com/problems/complement-of-base-10-integer/ 25 | """ 26 | #Difficulty: Easy 27 | #149 / 149 test cases passed. 28 | #Runtime: 28 ms 29 | #Memory Usage: 14.1 MB 30 | 31 | #Runtime: 28 ms, faster than 77.02% of Python3 online submissions for Number Complement. 32 | #Memory Usage: 14.1 MB, less than 6.63% of Python3 online submissions for Number Complement. 33 | 34 | class Solution: 35 | def findComplement(self, num: int) -> int: 36 | return int(''.join(['0' if n =='1' else '1' for n in list(bin(num)[2:])]), 2) 37 | -------------------------------------------------------------------------------- /Easy/509.FibonacciNumber(Dict).py: -------------------------------------------------------------------------------- 1 | """ 2 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the 3 | Fibonacci sequence, such that each number is the sum of the two preceding 4 | ones, starting from 0 and 1. That is, 5 | 6 | F(0) = 0, F(1) = 1 7 | F(N) = F(N - 1) + F(N - 2), for N > 1. 8 | 9 | Given N, calculate F(N). 10 | 11 | Example: 12 | Input: 4 13 | Output: 3 14 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 15 | 16 | Note: 17 | 0 ≤ N ≤ 30. 18 | """ 19 | #Difficulty: Easy 20 | #31 / 31 test cases passed. 21 | #Runtime: 24 ms 22 | #Memory Usage: 13.7 MB 23 | 24 | #Runtime: 24 ms, faster than 93.52% of Python3 online submissions for Fibonacci Number. 25 | #Memory Usage: 13.7 MB, less than 5.80% of Python3 online submissions for Fibonacci Number. 26 | 27 | class Solution: 28 | def fib(self, N: int) -> int: 29 | fib = {0:0, 1:1, 2:1} 30 | if N <= 2: 31 | return fib[N] 32 | for i in range(3, N+1): 33 | fib[i] = fib[i-1] + fib[i-2] 34 | return fib[N] 35 | -------------------------------------------------------------------------------- /Easy/509.FibonacciNumber(TwoVar).py: -------------------------------------------------------------------------------- 1 | """ 2 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the 3 | Fibonacci sequence, such that each number is the sum of the two preceding 4 | ones, starting from 0 and 1. That is, 5 | 6 | F(0) = 0, F(1) = 1 7 | F(N) = F(N - 1) + F(N - 2), for N > 1. 8 | 9 | Given N, calculate F(N). 10 | 11 | Example: 12 | Input: 4 13 | Output: 3 14 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 15 | 16 | Note: 17 | 0 ≤ N ≤ 30. 18 | """ 19 | #Difficulty: Easy 20 | #31 / 31 test cases passed. 21 | #Runtime: 24 ms 22 | #Memory Usage: 13.6 MB 23 | 24 | #Runtime: 24 ms, faster than 93.52% of Python3 online submissions for Fibonacci Number. 25 | #Memory Usage: 13.6 MB, less than 5.80% of Python3 online submissions for Fibonacci Number. 26 | 27 | class Solution: 28 | def fib(self, N: int) -> int: 29 | n1, n2 = 0, 1 30 | for i in range(N): 31 | n1, n2 = n2, n1 + n2 32 | return n1 33 | -------------------------------------------------------------------------------- /Easy/509.FibonacciNumber(list).py: -------------------------------------------------------------------------------- 1 | """ 2 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the 3 | Fibonacci sequence, such that each number is the sum of the two preceding 4 | ones, starting from 0 and 1. That is, 5 | 6 | F(0) = 0, F(1) = 1 7 | F(N) = F(N - 1) + F(N - 2), for N > 1. 8 | 9 | Given N, calculate F(N). 10 | 11 | Example: 12 | Input: 4 13 | Output: 3 14 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 15 | 16 | Note: 17 | 0 ≤ N ≤ 30. 18 | """ 19 | #Difficulty: Easy 20 | #31 / 31 test cases passed. 21 | #Runtime: 12 ms 22 | #Memory Usage: 13.8 MB 23 | 24 | #Runtime: 12 ms, faster than 99.99% of Python3 online submissions for Fibonacci Number. 25 | #Memory Usage: 13.8 MB, less than 5.80% of Python3 online submissions for Fibonacci Number. 26 | 27 | class Solution: 28 | def fib(self, N: int) -> int: 29 | fib = [0,1,1] 30 | if N <= 2: 31 | return fib[N] 32 | while True: 33 | i = len(fib) - 1 34 | fib.append(fib[i] + fib[i-1]) 35 | if i == N - 1: # if i == N: 36 | break 37 | return sum(fib[-3:-1]) # return fib[N] 38 | -------------------------------------------------------------------------------- /Easy/520.DetectCapital.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a word, you need to judge whether the usage of capitals in it is right 3 | or not. 4 | We define the usage of capitals in a word to be right when one of the 5 | following cases holds: 6 | 1. All letters in this word are capitals, like "USA". 7 | 2. All letters in this word are not capitals, like "leetcode". 8 | 3. Only the first letter in this word is capital, like "Google". 9 | Otherwise, we define that this word doesn't use capitals in a right way. 10 | 11 | Example: 12 | Input: "USA" 13 | Output: True 14 | 15 | Example: 16 | Input: "FlaG" 17 | Output: False 18 | 19 | Note: The input will be a non-empty word consisting of uppercase and 20 | lowercase latin letters. 21 | """ 22 | #Difficulty: Easy 23 | #550 / 550 test cases passed. 24 | #Runtime: 28 ms 25 | #Memory Usage: 13.8 MB 26 | 27 | #Runtime: 28 ms, faster than 86.51% of Python3 online submissions for Detect Capital. 28 | #Memory Usage: 13.8 MB, less than 57.14% of Python3 online submissions for Detect Capital. 29 | 30 | class Solution: 31 | def detectCapitalUse(self, word: str) -> bool: 32 | return word.isupper() or word.islower() or word.istitle() 33 | -------------------------------------------------------------------------------- /Easy/58.LengthofLastWord(list).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s consists of upper/lower-case alphabets and empty space 3 | characters ' ', return the length of last word (last word means the last 4 | appearing word if we loop from left to right) in the string. 5 | If the last word does not exist, return 0. 6 | Note: A word is defined as a maximal substring consisting of non-space 7 | characters only. 8 | 9 | Example: 10 | Input: "Hello World" 11 | Output: 5 12 | """ 13 | #Difficulty: Easy 14 | #59 / 59 test cases passed. 15 | #Runtime: 24 ms 16 | #Memory Usage: 14 MB 17 | 18 | #Runtime: 24 ms, faster than 91.10% of Python3 online submissions for Length of Last Word. 19 | #Memory Usage: 14 MB, less than 37.01% of Python3 online submissions for Length of Last Word. 20 | 21 | class Solution: 22 | def lengthOfLastWord(self, s: str) -> int: 23 | words = s.rstrip().split(" ") 24 | return len(words[-1]) 25 | -------------------------------------------------------------------------------- /Easy/58.LengthofLastWord(string).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string s consists of upper/lower-case alphabets and empty space 3 | characters ' ', return the length of last word (last word means the last 4 | appearing word if we loop from left to right) in the string. 5 | If the last word does not exist, return 0. 6 | Note: A word is defined as a maximal substring consisting of non-space 7 | characters only. 8 | 9 | Example: 10 | Input: "Hello World" 11 | Output: 5 12 | """ 13 | #Difficulty: Easy 14 | #59 / 59 test cases passed. 15 | #Runtime: 24 ms 16 | #Memory Usage: 14 MB 17 | 18 | #Runtime: 24 ms, faster than 91.10% of Python3 online submissions for Length of Last Word. 19 | #Memory Usage: 14 MB, less than 36.01% of Python3 online submissions for Length of Last Word. 20 | 21 | class Solution: 22 | def lengthOfLastWord(self, s: str) -> int: 23 | s = s.strip() 24 | if ' ' in s: 25 | return len(s[:s[::-1].index(' ')]) 26 | else: 27 | return len(s) 28 | -------------------------------------------------------------------------------- /Easy/599.MinimumIndexSumofTwoLists.py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose Andy and Doris want to choose a restaurant for dinner, and they 3 | both have a list of favorite restaurants represented by strings. 4 | 5 | You need to help them find out their common interest with the least list i 6 | ndex sum. If there is a choice tie between answers, output all of them with 7 | no order requirement. You could assume there always exists an answer. 8 | 9 | Note: 10 | 1. The length of both lists will be in the range of [1, 1000]. 11 | 2. The length of strings in both lists will be in the range of [1, 30]. 12 | 3. The index is starting from 0 to the list length minus 1. 13 | 4. No duplicates in both lists. 14 | """ 15 | #Difficulty: Easy 16 | #133 / 133 test cases passed. 17 | #Runtime: 348 ms 18 | #Memory Usage: 13.9 MB 19 | 20 | #Your runtime beats 19.17 % of python3 submissions. 21 | #Your memory usage beats 93.00 % of python3 submissions. 22 | 23 | class Solution: 24 | def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: 25 | d = {} 26 | for i, restaurant in enumerate(list1): 27 | if restaurant in list2: 28 | index_sum = i + list2.index(restaurant) 29 | if index_sum not in d: 30 | d[index_sum] = [restaurant] 31 | else: 32 | d[index_sum].append(restaurant) 33 | return d[min(d.keys())] 34 | -------------------------------------------------------------------------------- /Easy/645.SetMismatch.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You have a set of integers s, which originally contains 3 | all the numbers from 1 to n. Unfortunately, due to some 4 | error, one of the numbers in s got duplicated to another 5 | number in the set, which results in repetition of one 6 | number and loss of another number. 7 | 8 | You are given an integer array nums representing the 9 | data status of this set after the error. 10 | 11 | Find the number that occurs twice and the number that is 12 | missing and return them in the form of an array. 13 | 14 | Example: 15 | Input: nums = [1,2,2,4] 16 | Output: [2,3] 17 | 18 | Example: 19 | Input: nums = [1,1] 20 | Output: [1,2] 21 | 22 | Constraints: 23 | - 2 <= nums.length <= 10^4 24 | - 1 <= nums[i] <= 10^4 25 | ''' 26 | #Difficulty: Easy 27 | #49 / 49 test cases passed. 28 | #Runtime: 204 ms 29 | #Memory Usage: 15.8 MB 30 | 31 | #Runtime: 204 ms, faster than 56.13% of Python3 online submissions for Set Mismatch. 32 | #Memory Usage: 15.8 MB, less than 60.76% of Python3 online submissions for Set Mismatch. 33 | 34 | from collections import Counter 35 | 36 | class Solution: 37 | def findErrorNums(self, nums: List[int]) -> List[int]: 38 | n = len(nums) 39 | nums = Counter(nums) 40 | return [num for num, count in nums.items() if count==2][0], [num for num in range(1, n+1) if not nums[num]][0] 41 | -------------------------------------------------------------------------------- /Easy/66.PlusOne.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-empty array of digits representing a non-negative integer, 3 | plus one to the integer. 4 | The digits are stored such that the most significant digit is at the head 5 | of the list, and each element in the array contain a single digit. 6 | You may assume the integer does not contain any leading zero, except the 7 | number 0 itself. 8 | 9 | Example: 10 | Input: [1,2,3] 11 | Output: [1,2,4] 12 | Explanation: The array represents the integer 123. 13 | """ 14 | #Difficulty: Easy 15 | #109 / 109 test cases passed. 16 | #Runtime: 32 ms 17 | #Memory Usage: 13.6 MB 18 | 19 | #Runtime: 32 ms, faster than 63.07% of Python3 online submissions for Plus One. 20 | #Memory Usage: 13.6 MB, less than 5.13% of Python3 online submissions for Plus One. 21 | 22 | class Solution: 23 | def plusOne(self, digits: List[int]) -> List[int]: 24 | d = 0 25 | l = len(digits) 26 | for digit in digits: 27 | d = d * 10 + digit 28 | d+=1 29 | digits.clear() 30 | while d: 31 | number = d % 10 32 | digits.insert(0,number) 33 | d//=10 34 | while len(digits) < l: 35 | digits.insert(0,0) 36 | return digits 37 | -------------------------------------------------------------------------------- /Easy/7.ReverseInteger.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a 32-bit signed integer, reverse digits of an integer. 3 | 4 | Example 1: 5 | Input: 123 6 | Output: 321 7 | 8 | Example 2: 9 | Input: -123 10 | Output: -321 11 | """ 12 | #Difficulty: Easy 13 | #1032 / 1032 test cases passed. 14 | #Runtime: 24 ms 15 | #Memory Usage: 13.9 MB 16 | 17 | #Runtime: 24 ms, faster than 95.17% of Python3 online submissions for Reverse Integer. 18 | #Memory Usage: 13.9 MB, less than 5.26% of Python3 online submissions for Reverse Integer. 19 | 20 | class Solution: 21 | def reverse(self, x: int) -> int: 22 | if -2147483648 <= x <= 2147483647: 23 | if x < 0: 24 | x = abs(x) 25 | x = 0-Solution.reverser(x) 26 | else: 27 | x = Solution.reverser(x) 28 | return x if -2147483648 <= x <= 2147483647 else 0 29 | 30 | def reverser(x): 31 | nn = 0 32 | while x: 33 | lastDigit = x % 10 34 | nn = nn * 10 + lastDigit 35 | x = x // 10 36 | return nn 37 | -------------------------------------------------------------------------------- /Easy/709.ToLowerCase.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement function ToLowerCase() that has a string parameter str, and 3 | returns the same string in lowercase. 4 | 5 | Example: 6 | Input: "Hello" 7 | Output: "hello" 8 | """ 9 | #Difficulty: Easy 10 | #8 / 8 test cases passed. 11 | #Runtime: 20 ms 12 | #Memory Usage: 14 MB 13 | 14 | #Runtime: 20 ms, faster than 98.48% of Python3 online submissions for To Lower Case. 15 | #Memory Usage: 14 MB, less than 15.97% of Python3 online submissions for To Lower Case. 16 | 17 | class Solution: 18 | def toLowerCase(self, s: str) -> str: 19 | length = len(s) 20 | for i in range(length): 21 | if ord(s[i]) in range(65, 91): 22 | s = s[:i] + chr(ord(s[i]) + 32) + s[i+1:] 23 | return s 24 | 25 | #Runtime: 28 ms, faster than 72.96% of Python3 online submissions for To Lower Case. 26 | #Memory Usage: 13.9 MB, less than 40.32% of Python3 online submissions for To Lower Case. 27 | 28 | class Solution: 29 | def toLowerCase(self, s: str) -> str: 30 | ans = '' 31 | for c in s: 32 | if ord(c) in range(65, 91): 33 | ans += chr(ord(c) + 32) 34 | else: 35 | ans += c 36 | return ans 37 | -------------------------------------------------------------------------------- /Easy/746.MinCostClimbingStairs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an integer array cost where cost[i] is the 3 | cost of ith step on a staircase. Once you pay the cost, 4 | you can either climb one or two steps. 5 | 6 | You can either start from the step with index 0, or the 7 | step with index 1. 8 | 9 | Return the minimum cost to reach the top of the floor. 10 | 11 | Example: 12 | Input: cost = [10,15,20] 13 | Output: 15 14 | Explanation: Cheapest is: start on cost[1], pay that 15 | cost, and go to the top. 16 | 17 | Example: 18 | Input: cost = [1,100,1,1,1,100,1,1,100,1] 19 | Output: 6 20 | Explanation: Cheapest is: start on cost[0], and only 21 | step on 1s, skipping cost[3]. 22 | 23 | Constraints: 24 | - 2 <= cost.length <= 1000 25 | - 0 <= cost[i] <= 999 26 | ''' 27 | #Difficulty: Easy 28 | #279 / 279 test cases passed. 29 | #Runtime: 64 ms 30 | #Memory Usage: 14.5 MB 31 | 32 | #Runtime: 64 ms, faster than 23.75% of Python3 online submissions for Min Cost Climbing Stairs. 33 | #Memory Usage: 14.5 MB, less than 44.78% of Python3 online submissions for Min Cost Climbing Stairs. 34 | 35 | class Solution: 36 | def minCostClimbingStairs(self, cost: List[int]) -> int: 37 | prev0 = 0 38 | prev1 = 0 39 | count = 0 40 | for i in range(1, len(cost)): 41 | count = min(prev0+cost[i-1], prev1+cost[i]) 42 | prev0, prev1 = prev1, count 43 | return count 44 | -------------------------------------------------------------------------------- /Easy/83.RemoveDuplicatesfromSortedList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sorted linked list, delete all duplicates such that each element 3 | appear only once. 4 | 5 | Example: 6 | Input: 1->1->2->3->3 7 | Output: 1->2->3 8 | """ 9 | #Difficulty: Easy 10 | #165 / 165 test cases passed. 11 | #Runtime: 40 ms 12 | #Memory Usage: 13.9 MB 13 | 14 | #Runtime: 40 ms, faster than 87.68% of Python3 online submissions for Remove Duplicates from Sorted List. 15 | #Memory Usage: 13.9 MB, less than 31.86% of Python3 online submissions for Remove Duplicates from Sorted List. 16 | 17 | # Definition for singly-linked list. 18 | # class ListNode: 19 | # def __init__(self, val=0, next=None): 20 | # self.val = val 21 | # self.next = next 22 | 23 | class Solution: 24 | def deleteDuplicates(self, head: ListNode) -> ListNode: 25 | if not head: 26 | return 27 | prev = head 28 | curr = head.next 29 | while curr: 30 | if prev.val != curr.val: 31 | prev = curr 32 | curr = curr.next 33 | else: 34 | while prev.val == curr.val: 35 | curr = curr.next 36 | if not curr: 37 | prev.next = None 38 | break 39 | prev.next = curr 40 | return head 41 | -------------------------------------------------------------------------------- /Easy/832.FlippinganImage(reverse).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary matrix A, we want to flip the image horizontally, then 3 | invert it, and return the resulting image. 4 | To flip an image horizontally means that each row of the image is reversed. 5 | For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. 6 | To invert an image means that each 0 is replaced by 1, and each 1 is 7 | replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. 8 | 9 | Example: 10 | Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 11 | Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 12 | Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. 13 | Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 14 | 15 | Notes: 16 | - 1 <= A.length = A[0].length <= 20 17 | - 0 <= A[i][j] <= 1 18 | """ 19 | #Difficulty: Easy 20 | #82 / 82 test cases passed. 21 | #Runtime: 48 ms 22 | #Memory Usage: 13.9 MB 23 | 24 | #Runtime: 48 ms, faster than 92.68% of Python3 online submissions for Flipping an Image. 25 | #Memory Usage: 13.9 MB, less than 39.81% of Python3 online submissions for Flipping an Image. 26 | 27 | class Solution: 28 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 29 | for row in A: 30 | row.reverse() 31 | for i in range(len(row)): 32 | row[i] = abs(row[i]-1) 33 | return A 34 | -------------------------------------------------------------------------------- /Easy/832.FlippinganImage.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary matrix A, we want to flip the image horizontally, then 3 | invert it, and return the resulting image. 4 | To flip an image horizontally means that each row of the image is reversed. 5 | For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. 6 | To invert an image means that each 0 is replaced by 1, and each 1 is 7 | replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. 8 | 9 | Example: 10 | Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 11 | Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 12 | Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. 13 | Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 14 | 15 | Notes: 16 | - 1 <= A.length = A[0].length <= 20 17 | - 0 <= A[i][j] <= 1 18 | """ 19 | #Difficulty: Easy 20 | #82 / 82 test cases passed. 21 | #Runtime: 48 ms 22 | #Memory Usage: 13.6 MB 23 | 24 | #Runtime: 48 ms, faster than 92.68% of Python3 online submissions for Flipping an Image. 25 | #Memory Usage: 13.6 MB, less than 93.20% of Python3 online submissions for Flipping an Image. 26 | 27 | class Solution: 28 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 29 | for row in A: 30 | i = 0 31 | j = len(row) - 1 32 | while i <= j: 33 | row[i], row[j] = abs(row[j] - 1), abs(row[i] - 1) 34 | i += 1 35 | j -= 1 36 | return A 37 | -------------------------------------------------------------------------------- /Easy/852.PeakIndexinaMountainArray(ListComprehension).py: -------------------------------------------------------------------------------- 1 | """ 2 | Let's call an array A a mountain if the following properties hold: 3 | - A.length >= 3 4 | - There exists some 0 < i < A.length - 1 such that 5 | A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 6 | - Given an array that is definitely a mountain, return any i such that 7 | A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. 8 | 9 | Example: 10 | Input: [0,2,1,0] 11 | Output: 1 12 | 13 | Note: 14 | 1. 3 <= A.length <= 10000 15 | 2. 0 <= A[i] <= 10^6 16 | 3. A is a mountain, as defined above. 17 | """ 18 | #Difficulty: Easy 19 | #32 / 32 test cases passed. 20 | #Runtime: 72 ms 21 | #Memory Usage: 15.1 MB 22 | 23 | #Runtime: 72 ms, faster than 94.64% of Python3 online submissions for Peak Index in a Mountain Array. 24 | #Memory Usage: 15.1 MB, less than 49.72% of Python3 online submissions for Peak Index in a Mountain Array. 25 | 26 | class Solution: 27 | def peakIndexInMountainArray(self, A: List[int]) -> int: 28 | return [i for i in range(1,len(A)) if A[i-1] < A[i] > A[i+1]][0] 29 | -------------------------------------------------------------------------------- /Easy/852.PeakIndexinaMountainArray(set).py: -------------------------------------------------------------------------------- 1 | """ 2 | Let's call an array A a mountain if the following properties hold: 3 | - A.length >= 3 4 | - There exists some 0 < i < A.length - 1 such that 5 | A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 6 | - Given an array that is definitely a mountain, return any i such that 7 | A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. 8 | 9 | Example: 10 | Input: [0,2,1,0] 11 | Output: 1 12 | 13 | Note: 14 | 1. 3 <= A.length <= 10000 15 | 2. 0 <= A[i] <= 10^6 16 | 3. A is a mountain, as defined above. 17 | """ 18 | #Difficulty: Easy 19 | #32 / 32 test cases passed. 20 | #Runtime: 76 ms 21 | #Memory Usage: 15.4 MB 22 | 23 | #Runtime: 76 ms, faster than 82.37% of Python3 online submissions for Peak Index in a Mountain Array. 24 | #Memory Usage: 15.4 MB, less than 5.19% of Python3 online submissions for Peak Index in a Mountain Array. 25 | 26 | class Solution: 27 | def peakIndexInMountainArray(self, A: List[int]) -> int: 28 | s = sorted(set(A), reverse=True) 29 | for n in s: 30 | i = A.index(n) 31 | if A[i-1] < n > A[i+1]: 32 | return i 33 | -------------------------------------------------------------------------------- /Easy/884.UncommonWordsfromTwoSentences.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We are given two sentences A and B. (A sentence is a 3 | string of space separated words. Each word consists 4 | only of lowercase letters.) 5 | 6 | A word is uncommon if it appears exactly once in one 7 | of the sentences, and does not appear in the other 8 | sentence. 9 | 10 | Return a list of all uncommon words. 11 | 12 | You may return the list in any order. 13 | 14 | Example: 15 | Input: A = "this apple is sweet", B = "this apple is sour" 16 | Output: ["sweet","sour"] 17 | 18 | Example: 19 | Input: A = "apple apple", B = "banana" 20 | Output: ["banana"] 21 | 22 | Note: 23 | 1. 0 <= A.length <= 200 24 | 2. 0 <= B.length <= 200 25 | 3. A and B both contain only spaces and lowercase 26 | letters. 27 | ''' 28 | #Difficulty: Easy 29 | #53 / 53 test cases passed. 30 | #Runtime: 20 ms 31 | #Memory Usage: 14.1 MB 32 | 33 | #Runtime: 20 ms, faster than 98.73% of Python3 online submissions for Uncommon Words from Two Sentences. 34 | #Memory Usage: 14.1 MB, less than 91.89% of Python3 online submissions for Uncommon Words from Two Sentences. 35 | 36 | class Solution: 37 | def uncommonFromSentences(self, A: str, B: str) -> List[str]: 38 | B = f'{A} {B}'.split(' ') 39 | A = set(B) 40 | return [a for a in A if B.count(a) == 1] 41 | -------------------------------------------------------------------------------- /Easy/896.MonotonicArray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | An array is monotonic if it is either monotone increasing 3 | or monotone decreasing. 4 | 5 | An array A is monotone increasing if for all i <= j, 6 | A[i] <= A[j]. An array A is monotone decreasing if for 7 | all i <= j, A[i] >= A[j]. 8 | 9 | Return true if and only if the given array A is monotonic. 10 | 11 | Example: 12 | Input: [1,2,2,3] 13 | Output: true 14 | 15 | Example: 16 | Input: [6,5,4,4] 17 | Output: true 18 | 19 | Example: 20 | Input: [1,3,2] 21 | Output: false 22 | 23 | Example: 24 | Input: [1,2,4,5] 25 | Output: true 26 | 27 | Example: 28 | Input: [1,1,1] 29 | Output: true 30 | 31 | Note: 32 | 1. 1 <= A.length <= 50000 33 | 2. -100000 <= A[i] <= 100000 34 | ''' 35 | #Difficulty: Easy 36 | #366 / 366 test cases passed. 37 | #Runtime: 440 ms 38 | #Memory Usage: 20.6 MB 39 | 40 | #Runtime: 440 ms, faster than 93.04% of Python3 online submissions for Monotonic Array. 41 | #Memory Usage: 20.6 MB, less than 14.35% of Python3 online submissions for Monotonic Array. 42 | 43 | class Solution: 44 | def isMonotonic(self, A: List[int]) -> bool: 45 | return sorted(A) in [A, A[::-1]] 46 | -------------------------------------------------------------------------------- /Easy/9.PalindromeNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Determine whether an integer is a palindrome. An integer is a palindrome 3 | when it reads the same backward as forward. 4 | 5 | Example: 6 | Input: 121 7 | Output: true 8 | 9 | Example: 10 | Input: -121 11 | Output: false 12 | Explanation: From left to right, it reads -121. From right to left, 13 | it becomes 121-. Therefore it is not a palindrome. 14 | 15 | Follow up: 16 | Coud you solve it without converting the integer to a string? # Done 17 | """ 18 | #Difficulty: Easy 19 | #11509 / 11509 test cases passed. 20 | #Runtime: 56 ms 21 | #Memory Usage: 13.9 MB 22 | 23 | #Runtime: 56 ms, faster than 79.26 % of Python3 online submissions for Palindrome Number. 24 | #Memory Usage: 13.9 MB, less than 6.50% of Python3 online submissions for Palindrome Number. 25 | 26 | class Solution: 27 | def isPalindrome(self, x: int) -> bool: 28 | if x < 0: return False 29 | return self.reverse(x) == x 30 | 31 | def reverse(self, x): 32 | y = 0 33 | while x: 34 | d = x % 10 35 | y = y * 10 + d 36 | x //= 10 37 | return y 38 | -------------------------------------------------------------------------------- /Easy/905.SortArrayByParity.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array A of non-negative integers, return an array consisting of 3 | all the even elements of A, followed by all the odd elements of A. 4 | 5 | You may return any answer array that satisfies this condition. 6 | 7 | Example: 8 | Input: [3,1,2,4] 9 | Output: [2,4,3,1] 10 | The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 11 | 12 | Note: 13 | 1 <= A.length <= 5000 14 | 0 <= A[i] <= 5000 15 | """ 16 | #Difficulty: Easy 17 | #285 / 285 test cases passed. 18 | #Runtime: 76 ms 19 | #Memory Usage: 14.2 MB 20 | 21 | #Runtime: 76 ms, faster than 91.94% of Python3 online submissions for Sort Array By Parity. 22 | #Memory Usage: 14.2 MB, less than 5.19% of Python3 online submissions for Sort Array By Parity. 23 | 24 | class Solution: 25 | def sortArrayByParity(self, A: List[int]) -> List[int]: 26 | even = list() 27 | odd = list() 28 | for n in A: 29 | if n % 2 == 0: 30 | even.append(n) 31 | else: 32 | odd.append(n) 33 | return even + odd 34 | -------------------------------------------------------------------------------- /Easy/908.SmallestRangeI.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of integers, for each integer A[i] we 3 | may choose any x with -K <= x <= K, and add x to A[i]. 4 | 5 | After this process, we have some array B. 6 | 7 | Return the smallest possible difference between the 8 | maximum value of B and the minimum value of B. 9 | 10 | Example: 11 | Input: A = [1], K = 0 12 | Output: 0 13 | Explanation: B = [1] 14 | 15 | Example: 16 | Input: A = [0,10], K = 2 17 | Output: 6 18 | Explanation: B = [2,8] 19 | 20 | Example: 21 | Input: A = [1,3,6], K = 3 22 | Output: 0 23 | Explanation: B = [3,3,3] or B = [4,4,4] 24 | 25 | Note: 26 | 1. 1 <= A.length <= 10000 27 | 2. 0 <= A[i] <= 10000 28 | 3. 0 <= K <= 10000 29 | ''' 30 | #Difficulty: Easy 31 | #68 / 68 test cases passed. 32 | #Runtime: 128 ms 33 | #Memory Usage: 15.2 MB 34 | 35 | #Runtime: 112 ms, faster than 57.39% of Python3 online submissions for Smallest Range I. 36 | #Memory Usage: 15.2 MB, less than 82.08% of Python3 online submissions for Smallest Range I. 37 | 38 | class Solution: 39 | def smallestRangeI(self, A: List[int], K: int) -> int: 40 | A.sort() 41 | if A[0] + K >= A[-1] - K: 42 | return 0 43 | return A[-1] - A[0] - K*2 44 | -------------------------------------------------------------------------------- /Easy/922.SortArrayByParityII(Dictionary).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array A of non-negative integers, half of the integers in A are 3 | odd, and half of the integers are even. 4 | Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] 5 | is even, i is even. 6 | You may return any answer array that satisfies this condition. 7 | 8 | Example: 9 | Input: [4,2,5,7] 10 | Output: [4,5,2,7] 11 | Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. 12 | 13 | Note: 14 | 1. 2 <= A.length <= 20000 15 | 2. A.length % 2 == 0 16 | 3. 0 <= A[i] <= 1000 17 | """ 18 | #Difficulty: Easy 19 | #61 / 61 test cases passed. 20 | #Runtime: 228 ms 21 | #Memory Usage: 16.5 MB 22 | 23 | #Runtime: 228 ms, faster than 54.40% of Python3 online submissions for Sort Array By Parity II. 24 | #Memory Usage: 16.5 MB, less than 11.57% of Python3 online submissions for Sort Array By Parity II. 25 | 26 | class Solution: 27 | def sortArrayByParityII(self, A: List[int]) -> List[int]: 28 | db = {'odd' : [], 'even' : []} 29 | B = [] 30 | l = len(A) 31 | for a in A: 32 | if a % 2: 33 | db['odd'].append(a) 34 | else: 35 | db['even'].append(a) 36 | for i in range(l // 2): 37 | B.append(db['even'][i]) 38 | B.append(db['odd'][i]) 39 | return B 40 | -------------------------------------------------------------------------------- /Easy/922.SortArrayByParityII(List).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array A of non-negative integers, half of the integers in A are 3 | odd, and half of the integers are even. 4 | Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] 5 | is even, i is even. 6 | You may return any answer array that satisfies this condition. 7 | 8 | Example: 9 | Input: [4,2,5,7] 10 | Output: [4,5,2,7] 11 | Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. 12 | 13 | Note: 14 | 1. 2 <= A.length <= 20000 15 | 2. A.length % 2 == 0 16 | 3. 0 <= A[i] <= 1000 17 | """ 18 | #Difficulty: Easy 19 | #61 / 61 test cases passed. 20 | #Runtime: 212 ms 21 | #Memory Usage: 16.4 MB 22 | 23 | #Runtime: 212 ms, faster than 92.97% of Python3 online submissions for Sort Array By Parity II. 24 | #Memory Usage: 16.4 MB, less than 39.20% of Python3 online submissions for Sort Array By Parity II. 25 | 26 | class Solution: 27 | def sortArrayByParityII(self, A: List[int]) -> List[int]: 28 | even = 0 29 | odd = 1 30 | l = len(A) 31 | B = [None] * l 32 | for i in range(l): 33 | if A[i] % 2: 34 | B[odd] = A[i] 35 | odd += 2 36 | else: 37 | B[even] = A[i] 38 | even += 2 39 | return B 40 | -------------------------------------------------------------------------------- /Easy/922.SortArrayByParityII(TwoPointers).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array A of non-negative integers, half of the integers in A are 3 | odd, and half of the integers are even. 4 | Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] 5 | is even, i is even. 6 | You may return any answer array that satisfies this condition. 7 | 8 | Example: 9 | Input: [4,2,5,7] 10 | Output: [4,5,2,7] 11 | Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. 12 | 13 | Note: 14 | 1. 2 <= A.length <= 20000 15 | 2. A.length % 2 == 0 16 | 3. 0 <= A[i] <= 1000 17 | """ 18 | #Difficulty: Easy 19 | #61 / 61 test cases passed. 20 | #Runtime: 204 ms 21 | #Memory Usage: 16 MB 22 | 23 | #Runtime: 204 ms, faster than 99.17% of Python3 online submissions for Sort Array By Parity II. 24 | #Memory Usage: 16 MB, less than 98.98% of Python3 online submissions for Sort Array By Parity II. 25 | 26 | class Solution: 27 | def sortArrayByParityII(self, A: List[int]) -> List[int]: 28 | l = len(A) 29 | j = 1 30 | for i in range(0, l, 2): 31 | if A[i] % 2: 32 | while A[j] % 2: 33 | j += 2 34 | A[i], A[j] = A[j], A[i] 35 | return A 36 | -------------------------------------------------------------------------------- /Easy/938.RangeSumofBST(Optimized).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root node of a binary search tree, return the sum of values of 3 | all nodes with value between L and R (inclusive). 4 | The binary search tree is guaranteed to have unique values. 5 | 6 | Example: 7 | Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 8 | Output: 32 9 | 10 | Note: 11 | 1. The number of nodes in the tree is at most 10000. 12 | 2. The final answer is guaranteed to be less than 2^31. 13 | """ 14 | #Difficulty: Easy 15 | #42 / 42 test cases passed. 16 | #Runtime: 240 ms 17 | #Memory Usage: 22 MB 18 | 19 | #Runtime: 240 ms, faster than 62.37% of Python3 online submissions for Range Sum of BST. 20 | #Memory Usage: 22 MB, less than 38.97% of Python3 online submissions for Range Sum of BST. 21 | 22 | class Solution: 23 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 24 | summ = 0 25 | if not root: 26 | return 0 27 | if L <= root.val <= R: 28 | summ += root.val 29 | if root.val > L: 30 | summ += self.rangeSumBST(root.left, L, R) 31 | if root.val < R: 32 | summ += self.rangeSumBST(root.right, L, R) 33 | return summ 34 | -------------------------------------------------------------------------------- /Easy/938.RangeSumofBST.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root node of a binary search tree, return the sum of values of 3 | all nodes with value between L and R (inclusive). 4 | The binary search tree is guaranteed to have unique values. 5 | 6 | Example: 7 | Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 8 | Output: 32 9 | 10 | Note: 11 | 1. The number of nodes in the tree is at most 10000. 12 | 2. The final answer is guaranteed to be less than 2^31. 13 | """ 14 | #Difficulty: Easy 15 | #42 / 42 test cases passed. 16 | #Runtime: 316 ms 17 | #Memory Usage: 21.7 MB 18 | 19 | #Runtime: 316 ms, faster than 20.89% of Python3 online submissions for Range Sum of BST. 20 | #Memory Usage: 21.7 MB, less than 94.93% of Python3 online submissions for Range Sum of BST. 21 | 22 | class Solution: 23 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 24 | summ = 0 25 | if not root: 26 | return 0 27 | if L <= root.val <= R: 28 | summ += root.val 29 | summ += self.rangeSumBST(root.left, L, R) 30 | summ += self.rangeSumBST(root.right, L, R) 31 | return summ 32 | -------------------------------------------------------------------------------- /Easy/941.ValidMountainArray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers arr, return true if and only if it is a 3 | valid mountain array. 4 | 5 | Recall that arr is a mountain array if and only if: 6 | - arr.length >= 3 7 | - There exists some i with 0 < i < arr.length - 1 such that: 8 | = arr[0] < arr[1] < ... < arr[i - 1] < A[i] 9 | = arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 10 | 11 | Example: 12 | Input: arr = [2,1] 13 | Output: false 14 | 15 | Example: 16 | Input: arr = [3,5,5] 17 | Output: false 18 | 19 | Example: 20 | Input: arr = [0,3,2,1] 21 | Output: true 22 | 23 | Constraints: 24 | - 1 <= arr.length <= 10^4 25 | - 0 <= arr[i] <= 10^4 26 | ''' 27 | #Difficulty: Easy 28 | #52 / 52 test cases passed. 29 | #Runtime: 188 ms 30 | #Memory Usage: 15.6 MB 31 | 32 | #Runtime: 188 ms, faster than 93.89% of Python3 online submissions for Valid Mountain Array. 33 | #Memory Usage: 15.6 MB, less than 16.18% of Python3 online submissions for Valid Mountain Array. 34 | 35 | class Solution: 36 | def validMountainArray(self, arr: List[int]) -> bool: 37 | prev = arr[0] 38 | left = False 39 | top = False 40 | for nxt in arr[1:]: 41 | if not top and prev < nxt: 42 | left = True 43 | elif prev > nxt: 44 | top = True 45 | else: 46 | return False 47 | prev = nxt 48 | return left and top 49 | -------------------------------------------------------------------------------- /Easy/949.LargestTimeforGivenDigits.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of 4 digits, return the largest 24 hour time that can be 3 | made. 4 | The smallest 24 hour time is 00:00, and the largest is 23:59. Starting 5 | from 00:00, a time is larger if more time has elapsed since midnight. 6 | Return the answer as a string of length 5. If no valid time can be made, 7 | return an empty string. 8 | 9 | Example: 10 | Input: [1,2,3,4] 11 | Output: "23:41" 12 | 13 | Example: 14 | Input: [5,5,5,5] 15 | Output: "" 16 | 17 | Note: 18 | 1. A.length == 4 19 | 2. 0 <= A[i] <= 9 20 | """ 21 | #Difficulty: Easy 22 | #172 / 172 test cases passed. 23 | #Runtime: 28 ms 24 | #Memory Usage: 13.9 MB 25 | 26 | #Runtime: 28 ms, faster than 92.89% of Python3 online submissions for Largest Time for Given Digits. 27 | #Memory Usage: 13.9 MB, less than 50.65% of Python3 online submissions for Largest Time for Given Digits. 28 | 29 | import itertools 30 | 31 | class Solution: 32 | def largestTimeFromDigits(self, A: List[int]) -> str: 33 | result = '' 34 | combinations = itertools.permutations(A, 4) 35 | for combo in combinations: 36 | if combo[0] * 10 + combo[1] < 24 and combo[2] * 10 + combo[3] < 60: 37 | result = max(result, str(combo[0]) + str(combo[1]) + ':' + str(combo[2]) + str(combo[3])) 38 | return result 39 | -------------------------------------------------------------------------------- /Easy/961.N-RepeatedElementinSize2NArray(BruteForce).py: -------------------------------------------------------------------------------- 1 | """ 2 | In a array A of size 2N, there are N+1 unique elements, and exactly one of 3 | these elements is repeated N times. 4 | 5 | Return the element repeated N times. 6 | 7 | Example: 8 | Input: [1,2,3,3] 9 | Output: 3 10 | 11 | Example: 12 | Input: [2,1,2,5,3,2] 13 | Output: 2 14 | 15 | Example: 16 | Input: [5,1,5,2,5,3,5,4] 17 | Output: 5 18 | 19 | Note: 20 | - 4 <= A.length <= 10000 21 | - 0 <= A[i] < 10000 22 | - A.length is even 23 | """ 24 | #Difficulty: Easy 25 | #102 / 102 test cases passed. 26 | #Runtime: 7548 ms 27 | #Memory Usage: 15.7 MB 28 | 29 | #Runtime: 7548 ms, faster than 5.06% of Python3 online submissions for N-Repeated Element in Size 2N Array. 30 | #Memory Usage: 15.7 MB, less than 5.01% of Python3 online submissions for N-Repeated Element in Size 2N Array. 31 | 32 | class Solution: 33 | def repeatedNTimes(self, A: List[int]) -> int: 34 | N = len(A) // 2 35 | digits = set(A) 36 | for digit in digits: 37 | if A.count(digit) == N: 38 | return digit 39 | -------------------------------------------------------------------------------- /Easy/961.N-RepeatedElementinSize2NArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | In a array A of size 2N, there are N+1 unique elements, and exactly one of 3 | these elements is repeated N times. 4 | 5 | Return the element repeated N times. 6 | 7 | Example: 8 | Input: [1,2,3,3] 9 | Output: 3 10 | 11 | Example: 12 | Input: [2,1,2,5,3,2] 13 | Output: 2 14 | 15 | Example: 16 | Input: [5,1,5,2,5,3,5,4] 17 | Output: 5 18 | 19 | Note: 20 | - 4 <= A.length <= 10000 21 | - 0 <= A[i] < 10000 22 | - A.length is even 23 | """ 24 | #Difficulty: Easy 25 | #102 / 102 test cases passed. 26 | #Runtime: 320 ms 27 | #Memory Usage: 15.2 MB 28 | 29 | #Runtime: 320 ms, faster than 27.67% of Python3 online submissions for N-Repeated Element in Size 2N Array. 30 | #Memory Usage: 15.2 MB, less than 22.20% of Python3 online submissions for N-Repeated Element in Size 2N Array. 31 | 32 | class Solution: 33 | def repeatedNTimes(self, A: List[int]) -> int: 34 | digits = {} 35 | for d in A: 36 | if d not in digits: 37 | digits[d] = 0 38 | digits[d] += 1 39 | return max(digits, key=digits.get) 40 | -------------------------------------------------------------------------------- /Easy/977.SquaresofaSortedArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers A sorted in non-decreasing order, return an 3 | array of the squares of each number, also in sorted non-decreasing order. 4 | 5 | Example: 6 | Input: [-4,-1,0,3,10] 7 | Output: [0,1,9,16,100] 8 | """ 9 | #Difficulty: Easy 10 | #132 / 132 test cases passed. 11 | #Runtime: 228 ms 12 | #Memory Usage: 15.1 MB 13 | 14 | #Runtime: 228 ms, faster than 78.60% of Python3 online submissions for Squares of a Sorted Array. 15 | #Memory Usage: 15.1 MB, less than 44.05% of Python3 online submissions for Squares of a Sorted Array. 16 | 17 | class Solution: 18 | def sortedSquares(self, A: List[int]) -> List[int]: 19 | for i, n in enumerate(A): 20 | A[i] = n**2 21 | A.sort() 22 | return A 23 | -------------------------------------------------------------------------------- /Hard/145.BinaryTreePostorderTraversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, return the postorder traversal of its nodes' values. 3 | 4 | Example: 5 | Input: [1,null,2,3] 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | 12 | Output: [3,2,1] 13 | Follow up: Recursive solution is trivial, could you do it iteratively? 14 | """ 15 | #Difficulty: Hard 16 | #68 / 68 test cases passed. 17 | #Runtime: 44 ms 18 | #Memory Usage: 14.1 MB 19 | 20 | #Runtime: 44 ms, faster than 14.41% of Python3 online submissions for Binary Tree Postorder Traversal. 21 | #Memory Usage: 14.1 MB, less than 5.40% of Python3 online submissions for Binary Tree Postorder Traversal. 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, val=0, left=None, right=None): 26 | # self.val = val 27 | # self.left = left 28 | # self.right = right 29 | 30 | class Solution: 31 | def postorderTraversal(self, root: TreeNode) -> List[int]: 32 | postorder = [] 33 | self.traverse(root, postorder) 34 | return postorder 35 | 36 | def traverse(self, root, postorder): 37 | if not root: 38 | return 0 39 | self.traverse(root.left, postorder) 40 | self.traverse(root.right, postorder) 41 | postorder.append(root.val) 42 | -------------------------------------------------------------------------------- /Hard/154.FindMinimuminRotatedSortedArrayII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose an array sorted in ascending order is rotated at some pivot unknown 3 | to you beforehand. 4 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 5 | Find the minimum element. 6 | The array may contain duplicates. 7 | 8 | Example: 9 | Input: [2,2,2,0,1] 10 | Output: 0 11 | 12 | Note: 13 | - This is a follow up problem to Find Minimum in Rotated Sorted Array. 14 | - Would allow duplicates affect the run-time complexity? How and why? 15 | """ 16 | #Difficulty: Hard 17 | #192 / 192 test cases passed. 18 | #Runtime: 48 ms 19 | #Memory Usage: 14.3 MB 20 | 21 | #Runtime: 48 ms, faster than 92.02% of Python3 online submissions for Find Minimum in Rotated Sorted Array II. 22 | #Memory Usage: 14.3 MB, less than 5.88% of Python3 online submissions for Find Minimum in Rotated Sorted Array II. 23 | 24 | class Solution: 25 | def findMin(self, nums: List[int]) -> int: 26 | for i in range(1, len(nums)): 27 | if nums[i] < nums[0]: 28 | return nums[i] 29 | return nums[0] 30 | -------------------------------------------------------------------------------- /Hard/164.MaximumGap.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, return the maximum difference 3 | between two successive elements in its sorted form. If 4 | the array contains less than two elements, return 0. 5 | 6 | You must write an algorithm that runs in linear time and 7 | uses linear extra space. 8 | 9 | Example: 10 | Input: nums = [3,6,9,1] 11 | Output: 3 12 | Explanation: The sorted form of the array is [1,3,6,9], 13 | either (3,6) or (6,9) has the maximum 14 | difference 3. 15 | 16 | Example: 17 | Input: nums = [10] 18 | Output: 0 19 | Explanation: The array contains less than 2 elements, 20 | therefore return 0. 21 | 22 | Constraints: 23 | - 1 <= nums.length <= 10^4 24 | - 0 <= nums[i] <= 10^9 25 | ''' 26 | #Difficulty: Hard 27 | #17 / 17 test cases passed. 28 | #Runtime: 56 ms 29 | #Memory Usage: 14.9 MB 30 | 31 | #Runtime: 56 ms, faster than 61.19% of Python3 online submissions for Maximum Gap. 32 | #Memory Usage: 14.9 MB, less than 99.25% of Python3 online submissions for Maximum Gap. 33 | 34 | class Solution: 35 | def maximumGap(self, nums: List[int]) -> int: 36 | nums.sort() 37 | difference = 0 38 | for i in range(1,len(nums)): 39 | difference = max(difference, abs(nums[i]-nums[i-1])) 40 | return difference 41 | -------------------------------------------------------------------------------- /Hard/41.FirstMissingPositive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an unsorted integer array, find the smallest missing positive integer. 3 | 4 | Example: 5 | Input: [1,2,0] 6 | Output: 3 7 | """ 8 | #Difficulty: Hard 9 | #165 / 165 test cases passed. 10 | #Runtime: 32 ms 11 | #Memory Usage: 13.6 MB 12 | 13 | #Runtime: 32 ms, faster than 81.62% of Python3 online submissions for First Missing Positive. 14 | #Memory Usage: 13.6 MB, less than 8.70% of Python3 online submissions for First Missing Positive. 15 | 16 | class Solution: 17 | def firstMissingPositive(self, nums: List[int]) -> int: 18 | if not nums: return 1 19 | nums = sorted(nums) 20 | length = len(nums) -1 21 | index = 0 22 | for i, n in enumerate(nums): 23 | if n >= 0: 24 | index = i 25 | break 26 | d = nums[index] 27 | if d > 1: return 1 28 | for i, n in enumerate(nums[index + 1:]): 29 | if d + 1 == n or d == n: 30 | d = n 31 | else: break 32 | return d + 1 if d + 1 > 0 else 1 33 | -------------------------------------------------------------------------------- /Hard/MedianofTwoSortedArrays.py: -------------------------------------------------------------------------------- 1 | """ 2 | There are two sorted arrays nums1 and nums2 of size m and n respectively. 3 | Find the median of the two sorted arrays. 4 | The overall run time complexity should be O(log (m+n)). 5 | You may assume nums1 and nums2 cannot be both empty. 6 | 7 | Example 1: 8 | nums1 = [1, 3] 9 | nums2 = [2] 10 | The median is 2.0 11 | Example 2: 12 | nums1 = [1, 2] 13 | nums2 = [3, 4] 14 | The median is (2 + 3)/2 = 2.5 15 | """ 16 | #Difficulty: Hard 17 | #2085 / 2085 test cases passed. 18 | #Runtime: 84 ms 19 | #Memory Usage: 14.1 MB 20 | 21 | #Runtime: 84 ms, faster than 97.56% of Python3 online submissions for Median of Two Sorted Arrays. 22 | #Memory Usage: 14.1 MB, less than 5.71% of Python3 online submissions for Median of Two Sorted Arrays. 23 | 24 | class Solution: 25 | #def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 26 | def findMedianSortedArrays(nums1, nums2): 27 | n = sorted(nums1+nums2) 28 | return (n[(len(n)//2)-1]+n[len(n)//2])/2 if len(n)%2 == 0 else n[len(n)//2] 29 | 30 | #Tests 31 | nums1 = [1, 2] 32 | nums2 = [3, 4] 33 | print(Solution.findMedianSortedArrays(nums1, nums2),'2,5') 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2021 Yuri Spiridonov 4 | 5 | Permission is hereby granted, free of charge, to any person 6 | obtaining a copy of this software and associated documentation 7 | files (the "Software"), to deal in the Software without 8 | restriction, including without limitation the rights to use, 9 | copy, modify, merge, publish, distribute, sublicense, and/or 10 | sell copies of the Software, and to permit persons to whom 11 | the Software is furnished to do so, subject to the following 12 | conditions: 13 | 14 | The above copyright notice and this permission notice shall 15 | be included in all copies or substantial portions of the 16 | Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 19 | KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 20 | WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 21 | PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 22 | OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 23 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 24 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 25 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /Medium/1015.SmallestIntegerDivisiblebyK.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer K, you need to find the length of the smallest 3 | positive integer N such that N is divisible by K, and N only contains 4 | the digit 1. 5 | 6 | Return the length of N. If there is no such N, return -1. 7 | 8 | Note: N may not fit in a 64-bit signed integer. 9 | 10 | Example: 11 | Input: K = 1 12 | Output: 1 13 | Explanation: The smallest answer is N = 1, which has length 1. 14 | 15 | Example: 16 | Input: K = 2 17 | Output: -1 18 | Explanation: There is no such positive integer N divisible by 2. 19 | 20 | Example: 21 | Input: K = 3 22 | Output: 3 23 | Explanation: The smallest answer is N = 111, which has length 3. 24 | 25 | Constraints: 26 | - 1 <= K <= 105 27 | """ 28 | #Difficulty: Medium 29 | #70 / 70 test cases passed. 30 | #Runtime: 2020 ms 31 | #Memory Usage: 14.3 MB 32 | 33 | #Runtime: 2020 ms, faster than 22.62% of Python3 online submissions for Smallest Integer Divisible by K. 34 | #Memory Usage: 14.3 MB, less than 50.60% of Python3 online submissions for Smallest Integer Divisible by K. 35 | 36 | class Solution: 37 | def smallestRepunitDivByK(self, K: int) -> int: 38 | n = 1 39 | count = 1 40 | if not K % 2 or not K % 5: 41 | return -1 42 | while n % K: 43 | n = n*10 + 1 44 | count += 1 45 | return count 46 | -------------------------------------------------------------------------------- /Medium/1079.LetterTilePossibilities.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You have n tiles, where each tile has one letter tiles[i] 3 | printed on it. 4 | 5 | Return the number of possible non-empty sequences of 6 | letters you can make using the letters printed on those 7 | tiles. 8 | 9 | Example: 10 | Input: tiles = "AAB" 11 | Output: 8 12 | Explanation: The possible sequences are "A", "B", "AA", 13 | "AB", "BA", "AAB", "ABA", "BAA". 14 | 15 | Example: 16 | Input: tiles = "AAABBC" 17 | Output: 188 18 | 19 | Example: 20 | Input: tiles = "V" 21 | Output: 1 22 | 23 | Constraints: 24 | - 1 <= tiles.length <= 7 25 | - tiles consists of uppercase English letters. 26 | ''' 27 | #Difficulty: Medium 28 | #86 / 86 test cases passed. 29 | #Runtime: 80 ms 30 | #Memory Usage: 15.3 MB 31 | 32 | #Runtime: 80 ms, faster than 63.69% of Python3 online submissions for Letter Tile Possibilities. 33 | #Memory Usage: 15.3 MB, less than 57.87% of Python3 online submissions for Letter Tile Possibilities. 34 | 35 | from itertools import permutations 36 | 37 | class Solution: 38 | def numTilePossibilities(self, tiles: str) -> int: 39 | n = 0 40 | for i in range(1, len(tiles)+1): 41 | n += len(set(permutations(tiles, i))) 42 | return n 43 | -------------------------------------------------------------------------------- /Medium/11.ContainerWithMostWater.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given n non-negative integers a1, a2, ..., an , where each represents 3 | a point at coordinate (i, ai). n vertical lines are drawn such that 4 | the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, 5 | which together with x-axis forms a container, such that the container 6 | contains the most water. 7 | Note: You may not slant the container and n is at least 2. 8 | 9 | Example: 10 | Input: [1,8,6,2,5,4,8,3,7] 11 | Output: 49 12 | """ 13 | #Difficulty: Medium 14 | #50 / 50 test cases passed. 15 | #Runtime: 128 ms 16 | #Memory Usage: 15.2 MB 17 | 18 | #Runtime: 128 ms, faster than 79.12% of Python3 online submissions for Container With Most Water. 19 | #Memory Usage: 15.2 MB, less than 5.26% of Python3 online submissions for Container With Most Water. 20 | 21 | class Solution: 22 | def maxArea(self, height: List[int]) -> int: 23 | i = 0 24 | j = len(height) - 1 25 | most_water = 0 26 | while i <= j: 27 | most_water = max(most_water, min(height[i], height[j]) * (j - i)) 28 | if height[i] < height[j]: 29 | i += 1 30 | else: 31 | j -= 1 32 | return most_water 33 | -------------------------------------------------------------------------------- /Medium/120.Triangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a triangle, find the minimum path sum from top to bottom. Each step 3 | you may move to adjacent numbers on the row below. 4 | 5 | For example, given the following triangle 6 | [ 7 | [2], 8 | [3,4], 9 | [6,5,7], 10 | [4,1,8,3] 11 | ] 12 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 13 | 14 | Note: 15 | Bonus point if you are able to do this using only O(n) extra space, 16 | where n is the total number of rows in the triangle. 17 | """ 18 | #Difficulty: Medium 19 | #43 / 43 test cases passed. 20 | #Runtime: 64 ms 21 | #Memory Usage: 14.2 MB 22 | 23 | #Runtime: 64 ms, faster than 69.24% of Python3 online submissions for Triangle. 24 | #Memory Usage: 14.2 MB, less than 100.00% of Python3 online submissions for Triangle. 25 | 26 | class Solution: 27 | def minimumTotal(self, triangle: List[List[int]]) -> int: 28 | path = triangle.pop(0) 29 | while triangle: 30 | level = triangle.pop(0) 31 | for i in range(len(level)): 32 | if i-1 >= 0 and i+1 <= len(path): 33 | level[i] += min(path[i-1], path[i]) 34 | elif i-1 < 0: 35 | level[i] += path[i] 36 | elif i+1 >= len(path): 37 | level[i] += path[i-1] 38 | path = level 39 | return min(path) 40 | -------------------------------------------------------------------------------- /Medium/1227.AirplaneSeatAssignmentProbability.py: -------------------------------------------------------------------------------- 1 | ''' 2 | n passengers board an airplane with exactly n seats. The 3 | first passenger has lost the ticket and picks a seat 4 | randomly. But after that, the rest of passengers will: 5 | - Take their own seat if it is still available, 6 | - Pick other seats randomly when they find their 7 | seat occupied 8 | 9 | What is the probability that the n-th person can get his 10 | own seat? 11 | 12 | Example: 13 | Input: n = 1 14 | Output: 1.00000 15 | Explanation: The first person can only get the first seat. 16 | 17 | Example: 18 | Input: n = 2 19 | Output: 0.50000 20 | Explanation: The second person has a probability of 0.5 21 | to get the second seat (when first person 22 | gets the first seat). 23 | 24 | Constraints: 25 | - 1 <= n <= 10^5 26 | ''' 27 | #Difficulty: Medium 28 | #100 / 100 test cases passed. 29 | #Runtime: 32 ms 30 | #Memory Usage: 14.2 MB 31 | 32 | #Runtime: 32 ms, faster than 49.09% of Python3 online submissions for Airplane Seat Assignment Probability. 33 | #Memory Usage: 14.2 MB, less than 23.33% of Python3 online submissions for Airplane Seat Assignment Probability. 34 | 35 | class Solution: 36 | def nthPersonGetsNthSeat(self, n: int) -> float: 37 | return 0.5 if n > 1 else 1 38 | -------------------------------------------------------------------------------- /Medium/128.LongestConsecutiveSequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array of integers nums, return the 3 | length of the longest consecutive elements sequence. 4 | 5 | You must write an algorithm that runs in O(n) time. 6 | 7 | Example: 8 | Input: nums = [100,4,200,1,3,2] 9 | Output: 4 10 | Explanation: The longest consecutive elements sequence 11 | is [1, 2, 3, 4]. Therefore its length is 4. 12 | 13 | Example: 14 | Input: nums = [0,3,7,2,5,8,4,6,0,1] 15 | Output: 9 16 | 17 | Constraints: 18 | - 0 <= nums.length <= 10^5 19 | - -10^9 <= nums[i] <= 10^9 20 | ''' 21 | #Difficulty: Medium 22 | #70 / 70 test cases passed. 23 | #Runtime: 216 ms 24 | #Memory Usage: 25.9 MB 25 | 26 | #Runtime: 216 ms, faster than 30.78% of Python3 online submissions for Longest Consecutive Sequence. 27 | #Memory Usage: 25.9 MB, less than 15.32% of Python3 online submissions for Longest Consecutive Sequence. 28 | 29 | class Solution: 30 | def longestConsecutive(self, nums: List[int]) -> int: 31 | if not nums: 32 | return 0 33 | 34 | nums = sorted(set(nums)) 35 | length = 0 36 | prev = nums[0] 37 | sub_length = 1 38 | 39 | for num in nums[1:]: 40 | if num-1 == prev: 41 | sub_length += 1 42 | else: 43 | length = max(length, sub_length) 44 | sub_length = 1 45 | prev = num 46 | return max(length, sub_length) 47 | -------------------------------------------------------------------------------- /Medium/1291.SequentialDigits.py: -------------------------------------------------------------------------------- 1 | """ 2 | An integer has sequential digits if and only if each digit in the number is 3 | one more than the previous digit. 4 | Return a sorted list of all the integers in the range [low, high] inclusive 5 | that have sequential digits. 6 | 7 | Example: 8 | Input: low = 100, high = 300 9 | Output: [123,234] 10 | 11 | Example: 12 | Input: low = 1000, high = 13000 13 | Output: [1234,2345,3456,4567,5678,6789,12345] 14 | 15 | Constraints: 16 | - 10 <= low <= high <= 10^9 17 | """ 18 | #Difficulty: Medium 19 | #21 / 21 test cases passed. 20 | #Runtime: 28 ms 21 | #Memory Usage: 13.8 MB 22 | 23 | #Runtime: 28 ms, faster than 77.18% of Python3 online submissions for Sequential Digits. 24 | #Memory Usage: 13.8 MB, less than 52.82% of Python3 online submissions for Sequential Digits. 25 | 26 | class Solution: 27 | def sequentialDigits(self, low: int, high: int) -> List[int]: 28 | i = 0 29 | j = len(str(low)) 30 | num = 0 31 | result = [] 32 | digits = "1234567890" 33 | length = len(digits) 34 | while num < high: 35 | num = int(digits[i:i+j]) 36 | if num in range(low, high+1): 37 | result.append(num) 38 | i += 1 39 | if i + j >= length: 40 | j += 1 41 | i = 0 42 | return result 43 | -------------------------------------------------------------------------------- /Medium/137.SingleNumberII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-empty array of integers, every element appears three times 3 | except for one, which appears exactly once. Find that single one. 4 | 5 | Note: 6 | Your algorithm should have a linear runtime complexity. Could you 7 | implement it without using extra memory? 8 | 9 | Example: 10 | Input: [2,2,3,2] 11 | Output: 3 12 | 13 | Example: 14 | Input: [0,1,0,1,0,1,99] 15 | Output: 99 16 | """ 17 | #Difficulty: Medium 18 | #11 / 11 test cases passed. 19 | #Runtime: 1756 ms 20 | #Memory Usage: 15.6 MB 21 | 22 | #Runtime: 1756 ms, faster than 5.09% of Python3 online submissions for Single Number II. 23 | #Memory Usage: 15.6 MB, less than 69.25% of Python3 online submissions for Single Number II. 24 | 25 | class Solution: 26 | def singleNumber(self, nums: List[int]) -> int: 27 | nums_set = set(nums) 28 | for num in nums_set: 29 | if nums.count(num) == 1: 30 | return num 31 | -------------------------------------------------------------------------------- /Medium/143.ReorderList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a singly linked list L: L0→L1→…→Ln-1→Ln, 3 | reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 4 | 5 | You may not modify the values in the list's nodes, only nodes itself may 6 | be changed. 7 | 8 | Example: 9 | Given 1->2->3->4, reorder it to 1->4->2->3. 10 | 11 | Example: 12 | Given 1->2->3->4->5, reorder it to 1->5->2->4->3. 13 | """ 14 | #Difficulty: Medium 15 | #13 / 13 test cases passed. 16 | #Runtime: 132 ms 17 | #Memory Usage: 23.1 MB 18 | 19 | #Runtime: 132 ms, faster than 30.76% of Python3 online submissions for Reorder List. 20 | #Memory Usage: 23.1 MB, less than 79.26% of Python3 online submissions for Reorder List. 21 | 22 | # Definition for singly-linked list. 23 | # class ListNode: 24 | # def __init__(self, val=0, next=None): 25 | # self.val = val 26 | # self.next = next 27 | 28 | class Solution: 29 | def reorderList(self, head: ListNode) -> None: 30 | """ 31 | Do not return anything, modify head in-place instead. 32 | """ 33 | stack = [] 34 | node = head 35 | while node: 36 | stack.append(node.val) 37 | node = node.next 38 | while stack: 39 | head.val = stack.pop(0) 40 | head = head.next 41 | if stack: 42 | head.val = stack.pop() 43 | head = head.next 44 | -------------------------------------------------------------------------------- /Medium/144.BinaryTreePreorderTraversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, return the preorder traversal of its nodes' values. 3 | 4 | Example: 5 | Input: [1,null,2,3] 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | 12 | Output: [1,2,3] 13 | Follow up: Recursive solution is trivial, could you do it iteratively? 14 | """ 15 | #Difficulty: Medium 16 | #68 / 68 test cases passed. 17 | #Runtime: 32 ms 18 | #Memory Usage: 13.9 MB 19 | 20 | #Runtime: 32 ms, faster than 52.63% of Python3 online submissions for Binary Tree Preorder Traversal. 21 | #Memory Usage: 13.9 MB, less than 26.23% of Python3 online submissions for Binary Tree Preorder Traversal. 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, val=0, left=None, right=None): 26 | # self.val = val 27 | # self.left = left 28 | # self.right = right 29 | 30 | class Solution: 31 | def preorderTraversal(self, root: TreeNode) -> List[int]: 32 | preorder = [] 33 | self.traverse(root, preorder) 34 | return preorder 35 | 36 | def traverse(self, root, preorder): 37 | if not root: 38 | return 0 39 | preorder.append(root.val) 40 | self.traverse(root.left, preorder) 41 | self.traverse(root.right, preorder) 42 | -------------------------------------------------------------------------------- /Medium/152.MaximumProductSubarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums, find the contiguous subarray within an array 3 | (containing at least one number) which has the largest product. 4 | 5 | Example: 6 | Input: [2,3,-2,4] 7 | Output: 6 8 | Explanation: [2,3] has the largest product 6. 9 | 10 | Example: 11 | Input: [-2,0,-1] 12 | Output: 0 13 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 14 | """ 15 | #Difficulty: Medium 16 | #187 / 187 test cases passed. 17 | #Runtime: 56 ms 18 | #Memory Usage: 14 MB 19 | 20 | #Runtime: 56 ms, faster than 78.26% of Python3 online submissions for Maximum Product Subarray. 21 | #Memory Usage: 14 MB, less than 59.43% of Python3 online submissions for Maximum Product Subarray. 22 | 23 | class Solution: 24 | def maxProduct(self, nums: List[int]) -> int: 25 | maximum_product = maximum = minimum = nums[0] 26 | for i in range(1, len(nums)): 27 | local_maximum = nums[i] * maximum 28 | local_minimum = nums[i] * minimum 29 | maximum = max(nums[i], max(local_maximum, local_minimum)) 30 | minimum = min(nums[i], min(local_maximum, local_minimum)) 31 | maximum_product = max(maximum_product, maximum) 32 | return maximum_product 33 | -------------------------------------------------------------------------------- /Medium/153.FindMinimuminRotatedSortedArray(BinarySearch).py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose an array sorted in ascending order is rotated at some pivot unknown 3 | to you beforehand. 4 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 5 | Find the minimum element. 6 | 7 | You may assume no duplicate exists in the array. 8 | 9 | Example: 10 | Input: [3,4,5,1,2] 11 | Output: 1 12 | """ 13 | #Difficulty: Medium 14 | #146 / 146 test cases passed. 15 | #Runtime: 36 ms 16 | #Memory Usage: 14 MB 17 | 18 | #Runtime: 36 ms, faster than 88.91% of Python3 online submissions for Find Minimum in Rotated Sorted Array. 19 | #Memory Usage: 14 MB, less than 6.00% of Python3 online submissions for Find Minimum in Rotated Sorted Array. 20 | 21 | class Solution: 22 | def findMin(self, nums: List[int]) -> int: 23 | l = 0 24 | r = len(nums) - 1 25 | while l <= r: 26 | m = (l + r) // 2 27 | if nums[l] <= nums[m] <= nums[r]: 28 | return nums[l] 29 | if nums[m] < nums[l]: 30 | r = m 31 | else: 32 | l = m + 1 33 | -------------------------------------------------------------------------------- /Medium/153.FindMinimuminRotatedSortedArray(forLoop).py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose an array sorted in ascending order is rotated at some pivot unknown 3 | to you beforehand. 4 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 5 | Find the minimum element. 6 | 7 | You may assume no duplicate exists in the array. 8 | 9 | Example: 10 | Input: [3,4,5,1,2] 11 | Output: 1 12 | """ 13 | #Difficulty: Medium 14 | #146 / 146 test cases passed. 15 | #Runtime: 36 ms 16 | #Memory Usage: 14 MB 17 | 18 | #Runtime: 36 ms, faster than 88.91% of Python3 online submissions for Find Minimum in Rotated Sorted Array. 19 | #Memory Usage: 14 MB, less than 6.00% of Python3 online submissions for Find Minimum in Rotated Sorted Array. 20 | 21 | class Solution: 22 | def findMin(self, nums: List[int]) -> int: 23 | for i in range(1, len(nums)): 24 | if nums[i] < nums[0]: 25 | return nums[i] 26 | return nums[0] 27 | -------------------------------------------------------------------------------- /Medium/1689.PartitioningIntoMinimumNumberOfDeci-BinaryNumbers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A decimal number is called deci-binary if each of its 3 | digits is either 0 or 1 without any leading zeros. 4 | For example, 101 and 1100 are deci-binary, while 112 5 | and 3001 are not. 6 | 7 | Given a string n that represents a positive decimal 8 | integer, return the minimum number of positive deci-binary 9 | numbers needed so that they sum up to n. 10 | 11 | Example: 12 | Input: n = "32" 13 | Output: 3 14 | Explanation: 10 + 11 + 11 = 32 15 | 16 | Example: 17 | Input: n = "82734" 18 | Output: 8 19 | 20 | Example: 21 | Input: n = "27346209830709182346" 22 | Output: 9 23 | 24 | Constraints: 25 | - 1 <= n.length <= 10^5 26 | - n consists of only digits. 27 | - n does not contain any leading zeros and represents 28 | a positive integer. 29 | ''' 30 | #Difficulty: Medium 31 | #94 / 94 test cases passed. 32 | #Runtime: 64 ms 33 | #Memory Usage: 14.7 MB 34 | 35 | #Runtime: 64 ms, faster than 50.00% of Python3 online submissions for Partitioning Into Minimum Number Of Deci-Binary Numbers. 36 | #Memory Usage: 14.7 MB, less than 25.00% of Python3 online submissions for Partitioning Into Minimum Number Of Deci-Binary Numbers. 37 | 38 | class Solution: 39 | def minPartitions(self, n: str) -> int: 40 | return max(n) 41 | -------------------------------------------------------------------------------- /Medium/179.LargestNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of non negative integers, arrange them such that they form the 3 | largest number. 4 | 5 | Example: 6 | Input: [10,2] 7 | Output: "210" 8 | 9 | Example: 10 | Input: [3,30,34,5,9] 11 | Output: "9534330" 12 | 13 | Note: The result may be very large, so you need to return a string instead 14 | of an integer. 15 | """ 16 | #Difficulty: Medium 17 | #222 / 222 test cases passed. 18 | #Runtime: 40 ms 19 | #Memory Usage: 14.1 MB 20 | 21 | #Runtime: 40 ms, faster than 69.37% of Python3 online submissions for Largest Number. 22 | #Memory Usage: 14.1 MB, less than 7.82% of Python3 online submissions for Largest Number. 23 | 24 | class Solution: 25 | def largestNumber(self, nums: List[int]) -> str: 26 | length = len(nums) 27 | nums = sorted([str(nums[i]) for i in range(length)], reverse=True) 28 | for j in range(1, length): 29 | for i in range(length-j): 30 | if nums[i+1] in nums[i] and nums[i+1] != nums[i]: 31 | if nums[i+1] + nums[i] > nums[i] + nums[i+1]: 32 | nums[i+1], nums[i] = nums[i], nums[i+1] 33 | return ''.join(nums) if nums[0] != '0' else '0' 34 | -------------------------------------------------------------------------------- /Medium/209.MinimumSizeSubarraySum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of n positive integers and a positive integer s, find the 3 | minimal length of a contiguous subarray of which the sum ≥ s. 4 | If there isn't one, return 0 instead. 5 | 6 | Example: 7 | Input: s = 7, nums = [2,3,1,2,4,3] 8 | Output: 2 9 | Explanation: the subarray [4,3] has the minimal length under the problem 10 | constraint. 11 | 12 | Follow up: 13 | If you have figured out the O(n) solution, try coding another solution of 14 | which the time complexity is O(n log n). 15 | """ 16 | #Difficulty: Medium 17 | #15 / 15 test cases passed. 18 | #Runtime: 72 ms 19 | #Memory Usage: 16.2 MB 20 | 21 | #Runtime: 72 ms, faster than 87.67% of Python3 online submissions for Minimum Size Subarray Sum. 22 | #Memory Usage: 16.2 MB, less than 7.69% of Python3 online submissions for Minimum Size Subarray Sum. 23 | 24 | class Solution: 25 | def minSubArrayLen(self, s: int, nums: List[int]) -> int: 26 | if not nums or sum(nums) < s: return 0 27 | if s in nums or s < max(nums): return 1 28 | i = 0 29 | l = length = len(nums) 30 | summ = 0 31 | for j in range(length): 32 | summ += nums[j] 33 | while summ >= s and i <= j: 34 | l = min(l, 1 + j - i) 35 | summ -= nums[i] 36 | i += 1 37 | return l 38 | -------------------------------------------------------------------------------- /Medium/215.KthLargestElementinanArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find the kth largest element in an unsorted array. Note that it is the kth 3 | largest element in the sorted order, not the kth distinct element. 4 | 5 | Example: 6 | Input: [3,2,1,5,6,4] and k = 2 7 | Output: 5 8 | 9 | Note: 10 | You may assume k is always valid, 1 ≤ k ≤ array's length. 11 | """ 12 | #Difficulty: Medium 13 | #32 / 32 test cases passed. 14 | #Runtime: 68 ms 15 | #Memory Usage: 14.7 MB 16 | 17 | #Runtime: 68 ms, faster than 69.20% of Python3 online submissions for Kth Largest Element in an Array. 18 | #Memory Usage: 14.7 MB, less than 40.96% of Python3 online submissions for Kth Largest Element in an Array. 19 | 20 | class Solution: 21 | def findKthLargest(self, nums: List[int], k: int) -> int: 22 | return sorted(nums)[-k] 23 | -------------------------------------------------------------------------------- /Medium/222.CountCompleteTreeNodes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a complete binary tree, count the number of nodes. 3 | Note: 4 | Definition of a complete binary tree from Wikipedia: 5 | In a complete binary tree every level, except possibly the last, is 6 | completely filled, and all nodes in the last level are as far left as 7 | possible. It can have between 1 and 2h nodes inclusive at the last level h. 8 | 9 | Example: 10 | Input: 11 | 1 12 | / \ 13 | 2 3 14 | / \ / 15 | 4 5 6 16 | 17 | Output: 6 18 | """ 19 | #Difficulty: Medium 20 | #18 / 18 test cases passed. 21 | #Runtime: 100 ms 22 | #Memory Usage: 21.2 MB 23 | 24 | #Runtime: 100 ms, faster than 29.09% of Python3 online submissions for Count Complete Tree Nodes. 25 | #Memory Usage: 21.2 MB, less than 77.01% of Python3 online submissions for Count Complete Tree Nodes. 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode: 29 | # def __init__(self, val=0, left=None, right=None): 30 | # self.val = val 31 | # self.left = left 32 | # self.right = right 33 | 34 | class Solution: 35 | 36 | def countNodes(self, root: TreeNode) -> int: 37 | visited = [] 38 | self.counter(root, visited) 39 | return len(visited) 40 | 41 | def counter(self, root, visited): 42 | if not root: 43 | return 44 | visited.append(root.val) 45 | self.counter(root.left, visited) 46 | self.counter(root.right, visited) 47 | -------------------------------------------------------------------------------- /Medium/229.MajorityElementII(BruteForce).py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array of size n, find all elements that appear more than 3 | [ n/3 ] times. 4 | 5 | Note: The algorithm should run in linear time and in O(1) space. 6 | 7 | Example: 8 | Input: [3,2,3] 9 | Output: [3] 10 | 11 | Example: 12 | Input: [1,1,1,3,3,2,2,2] 13 | Output: [1,2] 14 | """ 15 | #Difficulty: Medium 16 | #66 / 66 test cases passed. 17 | #Runtime: 228 ms 18 | #Memory Usage: 14.8 MB 19 | 20 | #Runtime: 228 ms, faster than 7.70% of Python3 online submissions for Majority Element II. 21 | #Memory Usage: 14.8 MB, less than 94.74% of Python3 online submissions for Majority Element II. 22 | 23 | class Solution: 24 | def majorityElement(self, nums: List[int]) -> List[int]: 25 | counter = {} 26 | for num in nums: 27 | if num not in counter: 28 | counter[num] = 0 29 | counter[num] += 1 30 | return [num for num in counter if counter[num] > len(nums)/3] 31 | -------------------------------------------------------------------------------- /Medium/229.MajorityElementII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array of size n, find all elements that appear more than 3 | [ n/3 ] times. 4 | 5 | Note: The algorithm should run in linear time and in O(1) space. 6 | 7 | Example: 8 | Input: [3,2,3] 9 | Output: [3] 10 | 11 | Example: 12 | Input: [1,1,1,3,3,2,2,2] 13 | Output: [1,2] 14 | """ 15 | #Difficulty: Medium 16 | #66 / 66 test cases passed. 17 | #Runtime: 140 ms 18 | #Memory Usage: 14.8 MB 19 | 20 | #Runtime: 140 ms, faster than 43.68% of Python3 online submissions for Majority Element II. 21 | #Memory Usage: 14.8 MB, less than 95.70% of Python3 online submissions for Majority Element II. 22 | 23 | class Solution: 24 | def majorityElement(self, nums: List[int]) -> List[int]: 25 | limit = len(nums) / 3 26 | s = set(nums) 27 | result = [] 28 | for n in s: 29 | if nums.count(n) > limit: 30 | result.append(n) 31 | if len(result) == 2: 32 | break 33 | return result 34 | -------------------------------------------------------------------------------- /Medium/260.SingleNumberIII.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, in which exactly two elements 3 | appear only once and all the other elements appear exactly 4 | twice. Find the two elements that appear only once. You can 5 | return the answer in any order. 6 | 7 | Follow up: Your algorithm should run in linear runtime 8 | complexity. Could you implement it using only constant 9 | space complexity? 10 | 11 | Example: 12 | Input: nums = [1,2,1,3,2,5] 13 | Output: [3,5] 14 | Explanation: [5, 3] is also a valid answer. 15 | 16 | Example: 17 | Input: nums = [-1,0] 18 | Output: [-1,0] 19 | 20 | Example: 21 | Input: nums = [0,1] 22 | Output: [1,0] 23 | 24 | Constraints: 25 | - 2 <= nums.length <= 3 * 10^4 26 | - -2^31 <= nums[i] <= 2^31 - 1 27 | - Each integer in nums will appear twice, only two 28 | integers will appear once. 29 | ''' 30 | #Difficulty: Medium 31 | #32 / 32 test cases passed. 32 | #Runtime: 56 ms 33 | #Memory Usage: 16.2 MB 34 | 35 | #Runtime: 56 ms, faster than 82.01% of Python3 online submissions for Single Number III. 36 | #Memory Usage: 16.2 MB, less than 21.37% of Python3 online submissions for Single Number III. 37 | 38 | class Solution: 39 | def singleNumber(self, nums: List[int]) -> List[int]: 40 | single = set() 41 | for num in nums: 42 | if num not in single: 43 | single.add(num) 44 | else: 45 | single.remove(num) 46 | return single 47 | -------------------------------------------------------------------------------- /Medium/334.IncreasingTripletSubsequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, return true if there exists 3 | a triple of indices (i, j, k) such that i < j < k and 4 | nums[i] < nums[j] < nums[k]. If no such indices exists, 5 | return false. 6 | 7 | Example: 8 | Input: nums = [1,2,3,4,5] 9 | Output: true 10 | Explanation: Any triplet where i < j < k is valid. 11 | 12 | Example: 13 | Input: nums = [5,4,3,2,1] 14 | Output: false 15 | Explanation: No triplet exists. 16 | 17 | Example: 18 | Input: nums = [2,1,5,0,4,6] 19 | Output: true 20 | Explanation: The triplet (3, 4, 5) is valid because 21 | nums[3] == 0 < nums[4] == 4 < nums[5] == 6. 22 | 23 | Constraints: 24 | 1 <= nums.length <= 10^5 25 | -2^31 <= nums[i] <= 2^31 - 1 26 | ''' 27 | #Difficulty: Medium 28 | #61 / 61 test cases passed. 29 | #Runtime: 4360 ms 30 | #Memory Usage: 14.9 MB 31 | 32 | #Runtime: 4360 ms, faster than 5.22% of Python3 online submissions for Increasing Triplet Subsequence. 33 | #Memory Usage: 14.9 MB, less than 23.89% of Python3 online submissions for Increasing Triplet Subsequence. 34 | 35 | class Solution: 36 | def increasingTriplet(self, nums: List[int]) -> bool: 37 | length = len(nums) 38 | for i in range(length): 39 | for j in range(i+1, length): 40 | if nums[i] < nums[j]: 41 | if nums[j+1:] and max(nums[j+1:]) > nums[j]: 42 | return True 43 | return False 44 | -------------------------------------------------------------------------------- /Medium/347.TopKFrequentElements.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-empty array of integers, return the k most frequent elements. 3 | 4 | Example: 5 | Input: nums = [1,1,1,2,2,3], k = 2 6 | Output: [1,2] 7 | 8 | Note: 9 | - You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 10 | - Your algorithm's time complexity must be better than O(n log n), where 11 | n is the array's size. 12 | - It's guaranteed that the answer is unique, in other words the set of 13 | the top k frequent elements is unique. 14 | - You can return the answer in any order. 15 | """ 16 | #Difficulty: Medium 17 | #21 / 21 test cases passed. 18 | #Runtime: 112 ms 19 | #Memory Usage: 18.5 MB 20 | 21 | #Runtime: 112 ms, faster than 51.73% of Python3 online submissions for Top K Frequent Elements. 22 | #Memory Usage: 18.5 MB, less than 8.25% of Python3 online submissions for Top K Frequent Elements. 23 | 24 | class Solution: 25 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 26 | d = {} 27 | for num in nums: 28 | if num in d.keys(): 29 | d[num] += 1 30 | else: 31 | d[num] = 1 32 | return [key[0] for key in sorted(d.items(), key=lambda item: item[1])][-k:] 33 | -------------------------------------------------------------------------------- /Medium/378.KthSmallestElementinaSortedMatrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a n x n matrix where each of the rows and columns are sorted in 3 | ascending order, find the kth smallest element in the matrix. 4 | Note that it is the kth smallest element in the sorted order, not the 5 | kth distinct element. 6 | 7 | Example: 8 | matrix = [ 9 | [ 1, 5, 9], 10 | [10, 11, 13], 11 | [12, 13, 15] 12 | ], 13 | k = 8, 14 | return 13. 15 | 16 | Note: 17 | You may assume k is always valid, 1 ≤ k ≤ n2. 18 | """ 19 | #Difficulty: Medium 20 | #85 / 85 test cases passed. 21 | #Runtime: 168 ms 22 | #Memory Usage: 19.6 MB 23 | 24 | #Runtime: 168 ms, faster than 96.92% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix. 25 | #Memory Usage: 19.6 MB, less than 88.87% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix. 26 | 27 | class Solution: 28 | def kthSmallest(self, matrix: List[List[int]], k: int) -> int: 29 | x= [] 30 | for row in matrix: 31 | x += row 32 | x.sort() 33 | return x[k-1] 34 | -------------------------------------------------------------------------------- /Medium/421.MaximumXORofTwoNumbersinanArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231. 3 | Find the maximum result of ai XOR aj, where 0 ≤ i, j < n. 4 | Could you do this in O(n) runtime? 5 | 6 | Example: 7 | Input: [3, 10, 5, 25, 2, 8] 8 | Output: 28 9 | Explanation: The maximum result is 5 ^ 25 = 28. 10 | """ 11 | #Difficulty: Medium 12 | #29 / 29 test cases passed. 13 | #Runtime: 188 ms 14 | #Memory Usage: 18 MB 15 | 16 | #Runtime: 188 ms, faster than 72.25% of Python3 online submissions for Maximum XOR of Two Numbers in an Array. 17 | #Memory Usage: 18 MB, less than 89.19% of Python3 online submissions for Maximum XOR of Two Numbers in an Array. 18 | 19 | class Solution: 20 | def findMaximumXOR(self, nums: List[int]) -> int: 21 | maximum = 0 22 | mask = 0 23 | result = set() 24 | length = len(nums) 25 | for i in range(30, -1, -1): 26 | mask |= 1 << i 27 | new = maximum | 1 << i 28 | for i in range(length): 29 | result.add(nums[i] & mask) 30 | for prefix in result: 31 | if new ^ prefix in result: 32 | maximum = new 33 | break 34 | result.clear() 35 | return maximum 36 | -------------------------------------------------------------------------------- /Medium/442.FindAllDuplicatesinanArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, 1 <= a[i] <= n (n = size of array), some 3 | elements appear twice and others appear once. 4 | Find all the elements that appear twice in this array. 5 | Could you do it without extra space and in O(n) runtime? 6 | 7 | Example: 8 | Input: 9 | [4,3,2,7,8,2,3,1] 10 | Output: 11 | [2,3] 12 | """ 13 | #Difficulty: Medium 14 | #28 / 28 test cases passed. 15 | #Runtime: 348 ms 16 | #Memory Usage: 23.5 MB 17 | 18 | #Runtime: 348 ms, faster than 99.23% of Python3 online submissions for Find All Duplicates in an Array. 19 | #Memory Usage: 23.5 MB, less than 5.59% of Python3 online submissions for Find All Duplicates in an Array. 20 | 21 | class Solution: 22 | def findDuplicates(self, nums: List[int]) -> List[int]: 23 | duplicates = set() 24 | visited = set() 25 | for num in nums: 26 | if num in visited: 27 | duplicates.add(num) 28 | visited.add(num) 29 | return duplicates 30 | -------------------------------------------------------------------------------- /Medium/451.SortCharactersByFrequency.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, sort it in decreasing order based on the frequency of 3 | characters. 4 | 5 | Example: 6 | Input: 7 | "Aabb" 8 | Output: 9 | "bbAa" 10 | Explanation: 11 | "bbaA" is also a valid answer, but "Aabb" is incorrect. 12 | Note that 'A' and 'a' are treated as two different characters. 13 | """ 14 | #Difficulty: Medium 15 | #35 / 35 test cases passed. 16 | #Runtime: 20 ms 17 | #Memory Usage: 14.9 MB 18 | 19 | #Runtime: 20 ms, faster than 100.00% of Python3 online submissions for Sort Characters By Frequency. 20 | #Memory Usage: 14.9 MB, less than 14.29% of Python3 online submissions for Sort Characters By Frequency. 21 | 22 | class Solution: 23 | def frequencySort(self, s: str) -> str: 24 | letters = set(s) 25 | d = {} 26 | result = '' 27 | for letter in letters: 28 | count = s.count(letter) 29 | if count not in d: 30 | d[count] = [letter * count] 31 | else: 32 | d[count].append(letter * count) 33 | keys = sorted(d.keys(), reverse=True) 34 | for key in keys: 35 | for letter in d[key]: 36 | result += letter 37 | return result 38 | -------------------------------------------------------------------------------- /Medium/46.Permutations.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a collection of distinct integers, return all possible permutations. 3 | 4 | Example: 5 | Input: [1,2,3] 6 | Output: 7 | [ 8 | [1,2,3], 9 | [1,3,2], 10 | [2,1,3], 11 | [2,3,1], 12 | [3,1,2], 13 | [3,2,1] 14 | ] 15 | """ 16 | #Difficulty: Medium 17 | #25 / 25 test cases passed. 18 | #Runtime: 32 ms 19 | #Memory Usage: 13.7 MB 20 | 21 | #Runtime: 32 ms, faster than 97.95% of Python3 online submissions for Permutations. 22 | #Memory Usage: 13.7 MB, less than 97.13% of Python3 online submissions for Permutations. 23 | 24 | import itertools 25 | 26 | class Solution: 27 | def permute(self, nums: List[int]) -> List[List[int]]: 28 | return itertools.permutations(nums) 29 | -------------------------------------------------------------------------------- /Medium/462.MinimumMovestoEqualArrayElementsII.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums of size n, return the 3 | minimum number of moves required to make all array 4 | elements equal. 5 | 6 | In one move, you can increment or decrement an element 7 | of the array by 1. 8 | 9 | Example: 10 | Input: nums = [1,2,3] 11 | Output: 2 12 | Explanation: Only two moves are needed (remember each 13 | move increments or decrements one element): 14 | [1,2,3] => [2,2,3] => [2,2,2] 15 | 16 | Example: 17 | Input: nums = [1,10,2,9] 18 | Output: 16 19 | 20 | Constraints: 21 | - n == nums.length 22 | - 1 <= nums.length <= 10^5 23 | - -10^9 <= nums[i] <= 10^9 24 | ''' 25 | #Difficulty: Medium 26 | #30 / 30 test cases passed. 27 | #Runtime: 68 ms 28 | #Memory Usage: 15.4 MB 29 | 30 | #Runtime: 68 ms, faster than 88.44% of Python3 online submissions for Minimum Moves to Equal Array Elements II. 31 | #Memory Usage: 15.4 MB, less than 43.75% of Python3 online submissions for Minimum Moves to Equal Array Elements II. 32 | 33 | class Solution: 34 | def minMoves2(self, nums: List[int]) -> int: 35 | median = sorted(nums)[len(nums)//2] 36 | return sum(abs(num-median) for num in nums) 37 | -------------------------------------------------------------------------------- /Medium/47.PermutationsII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a collection of numbers, nums, that might contain duplicates, 3 | return all possible unique permutations in any order. 4 | 5 | Example: 6 | Input: nums = [1,1,2] 7 | Output: 8 | [[1,1,2], 9 | [1,2,1], 10 | [2,1,1]] 11 | 12 | Example: 13 | Input: nums = [1,2,3] 14 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 15 | 16 | Constraints: 17 | - 1 <= nums.length <= 8 18 | - -10 <= nums[i] <= 10 19 | """ 20 | #Difficulty: Medium 21 | #33 / 33 test cases passed. 22 | #Runtime: 60 ms 23 | #Memory Usage: 14.3 MB 24 | 25 | #Runtime: 60 ms, faster than 51.59% of Python3 online submissions for Permutations II. 26 | #Memory Usage: 14.3 MB, less than 10.37% of Python3 online submissions for Permutations II. 27 | 28 | import itertools 29 | 30 | class Solution: 31 | def permuteUnique(self, nums: List[int]) -> List[List[int]]: 32 | return set(itertools.permutations(nums)) 33 | -------------------------------------------------------------------------------- /Medium/50.Pow(x,n).py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement pow(x, n), which calculates x raised to the power n (x**n). 3 | 4 | Example: 5 | Input: 2.10000, 3 6 | Output: 9.26100 7 | 8 | Example: 9 | Input: 2.00000, -2 10 | Output: 0.25000 11 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 12 | 13 | Note: 14 | - -100.0 < x < 100.0 15 | - n is a 32-bit signed integer, within the range [−231, 231 − 1] 16 | """ 17 | #Difficulty: Medium 18 | #304 / 304 test cases passed. 19 | #Runtime: 24 ms 20 | #Memory Usage: 14 MB 21 | 22 | #Runtime: 24 ms, faster than 92.57% of Python3 online submissions for Pow(x, n). 23 | #Memory Usage: 14 MB, less than 15.17% of Python3 online submissions for Pow(x, n). 24 | 25 | class Solution: 26 | def myPow(self, x: float, n: int) -> float: 27 | if not n: return 1 28 | power = self.myPow(x, int(n/2)) 29 | if n % 2 == 0: 30 | return power * power 31 | else: 32 | return power * power / x if n < 0 else power * power * x 33 | -------------------------------------------------------------------------------- /Medium/513.FindBottomLeftTreeValue.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, find the leftmost value in the last row of the tree. 3 | 4 | Example: 5 | Input: 6 | 1 7 | / \ 8 | 2 3 9 | / / \ 10 | 4 5 6 11 | / 12 | 7 13 | 14 | Output: 7 15 | Note: You may assume the tree (i.e., the given root node) is not NULL. 16 | """ 17 | #Difficulty: Medium 18 | #74 / 74 test cases passed. 19 | #Runtime: 40 ms 20 | #Memory Usage: 15.8 MB 21 | 22 | #Runtime: 40 ms, faster than 92.04% of Python3 online submissions for Find Bottom Left Tree Value. 23 | #Memory Usage: 15.8 MB, less than 100.00% of Python3 online submissions for Find Bottom Left Tree Value. 24 | 25 | # Definition for a binary tree node. 26 | # class TreeNode: 27 | # def __init__(self, val=0, left=None, right=None): 28 | # self.val = val 29 | # self.left = left 30 | # self.right = right 31 | 32 | class Solution: 33 | def findBottomLeftValue(self, root: TreeNode) -> int: 34 | queue = [root] 35 | left = root.val 36 | while queue: 37 | level = [] 38 | length = len(queue) 39 | while length: 40 | node = queue.pop(0) 41 | level.append(node.val) 42 | length -= 1 43 | if node.left: 44 | queue.append(node.left) 45 | if node.right: 46 | queue.append(node.right) 47 | left = level[0] 48 | return left 49 | -------------------------------------------------------------------------------- /Medium/515.FindLargestValueinEachTreeRow.py: -------------------------------------------------------------------------------- 1 | """ 2 | You need to find the largest value in each row of a binary tree. 3 | 4 | Example: 5 | Input: 6 | 1 7 | / \ 8 | 3 2 9 | / \ \ 10 | 5 3 9 11 | 12 | Output: [1, 3, 9] 13 | """ 14 | #Difficulty: Medium 15 | #78 / 78 test cases passed. 16 | #Runtime: 48 ms 17 | #Memory Usage: 16 MB 18 | 19 | #Runtime: 48 ms, faster than 80.31% of Python3 online submissions for Find Largest Value in Each Tree Row. 20 | #Memory Usage: 16 MB, less than 61.86% of Python3 online submissions for Find Largest Value in Each Tree Row. 21 | 22 | # Definition for a binary tree node. 23 | # class TreeNode: 24 | # def __init__(self, val=0, left=None, right=None): 25 | # self.val = val 26 | # self.left = left 27 | # self.right = right 28 | 29 | class Solution: 30 | def largestValues(self, root: TreeNode) -> List[int]: 31 | if not root: return root 32 | queue = [root] 33 | max_in_row = [] 34 | while queue: 35 | length = len(queue) 36 | max_num = float(-inf) 37 | while length: 38 | length -= 1 39 | node = queue.pop(0) 40 | max_num = max(max_num, node.val) 41 | if node.left: 42 | queue.append(node.left) 43 | if node.right: 44 | queue.append(node.right) 45 | max_in_row.append(max_num) 46 | return max_in_row 47 | -------------------------------------------------------------------------------- /Medium/56.MergeIntervals.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | Example: 5 | Input: [[1,3],[2,6],[8,10],[15,18]] 6 | Output: [[1,6],[8,10],[15,18]] 7 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into 8 | [1,6]. 9 | 10 | NOTE: input types have been changed on April 15, 2019. Please reset to 11 | default code definition to get new method signature. 12 | """ 13 | #Difficulty: Medium 14 | #169 / 169 test cases passed. 15 | #Runtime: 100 ms 16 | #Memory Usage: 15.6 MB 17 | 18 | #Runtime: 100 ms, faster than 28.72% of Python3 online submissions for Merge Intervals. 19 | #Memory Usage: 15.6 MB, less than 6.52% of Python3 online submissions for Merge Intervals. 20 | 21 | class Solution: 22 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 23 | intervals.sort() 24 | i = 1 25 | while i < len(intervals): 26 | if intervals[i][0] <= intervals[i-1][-1]: 27 | intervals[i-1] = [min(intervals[i][0], intervals[i-1][0]), max(intervals[i][-1], intervals[i-1][-1])] 28 | intervals.pop(i) 29 | else: 30 | i += 1 31 | return intervals 32 | -------------------------------------------------------------------------------- /Medium/581.ShortestUnsortedContinuousSubarray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, you need to find one 3 | continuous subarray that if you only sort this subarray 4 | in ascending order, then the whole array will be sorted 5 | in ascending order. 6 | 7 | Return the shortest such subarray and output its length. 8 | 9 | Example: 10 | Input: nums = [2,6,4,8,10,9,15] 11 | Output: 5 12 | Explanation: You need to sort [6, 4, 8, 10, 9] in 13 | ascending order to make the whole array 14 | sorted in ascending order. 15 | 16 | Example: 17 | Input: nums = [1,2,3,4] 18 | Output: 0 19 | 20 | Example: 21 | Input: nums = [1] 22 | Output: 0 23 | 24 | Constraints: 25 | - 1 <= nums.length <= 10^4 26 | - -10^5 <= nums[i] <= 10^5 27 | 28 | Follow up: Can you solve it in O(n) time complexity? 29 | ''' 30 | #Difficulty: Medium 31 | #307 / 307 test cases passed. 32 | #Runtime: 204 ms 33 | #Memory Usage: 15.5 MB 34 | 35 | #Runtime: 204 ms, faster than 68.88% of Python3 online submissions for Shortest Unsorted Continuous Subarray. 36 | #Memory Usage: 15.5 MB, less than 34.34% of Python3 online submissions for Shortest Unsorted Continuous Subarray. 37 | 38 | class Solution: 39 | def findUnsortedSubarray(self, nums: List[int]) -> int: 40 | array = sorted(nums) 41 | indices = [] 42 | for i in range(len(nums)): 43 | if nums[i] != array[i]: 44 | indices.append(i) 45 | return 1 + indices[-1] - indices[0] if indices else 0 -------------------------------------------------------------------------------- /Medium/593.ValidSquare.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the coordinates of four points in 2D space, return whether the four 3 | points could construct a square. 4 | 5 | The coordinate (x,y) of a point is represented by an integer array with 6 | two integers. 7 | 8 | Example: 9 | Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] 10 | Output: True 11 | 12 | Note: 13 | 1. All the input integers are in the range [-10000, 10000]. 14 | 2. A valid square has four equal sides with positive length and four 15 | equal angles (90-degree angles). 16 | 3. Input points have no order. 17 | """ 18 | #Difficulty: Medium 19 | #244 / 244 test cases passed. 20 | #Runtime: 36 ms 21 | #Memory Usage: 14 MB 22 | 23 | #Runtime: 36 ms, faster than 44.00% of Python3 online submissions for Valid Square. 24 | #Memory Usage: 14 MB, less than 99.78% of Python3 online submissions for Valid Square. 25 | 26 | class Solution: 27 | def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool: 28 | points = [p1, p2, p3, p4] 29 | result = {} 30 | for i in range(3): 31 | x1 = points[i][0] 32 | y1 = points[i][1] 33 | for j in range(i+1, 4): 34 | x2 = points[j][0] 35 | y2 = points[j][1] 36 | diagonal = ((x1-x2)**2 + (y1-y2)**2)**0.5 37 | if diagonal not in result: 38 | result[diagonal] = 0 39 | result[diagonal] += 1 40 | return 2 in result.values() and 4 in result.values() 41 | -------------------------------------------------------------------------------- /Medium/713.SubarrayProductLessThanK.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your are given an array of positive integers nums. 3 | 4 | Count and print the number of (contiguous) subarrays where the product of 5 | all the elements in the subarray is less than k. 6 | 7 | Example: 8 | Input: nums = [10, 5, 2, 6], k = 100 9 | Output: 8 10 | Explanation: The 8 subarrays that have product less than 100 are: 11 | [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. 12 | Note that [10, 5, 2] is not included as the product of 100 is 13 | not strictly less than k. 14 | 15 | Note: 16 | - 0 < nums.length <= 50000. 17 | - 0 < nums[i] < 1000. 18 | - 0 <= k < 10^6. 19 | """ 20 | #Difficulty: Medium 21 | #84 / 84 test cases passed. 22 | #Runtime: 1048 ms 23 | #Memory Usage: 18.4 MB 24 | 25 | #Runtime: 1048 ms, faster than 100.00% of Python3 online submissions for Subarray Product Less Than K. 26 | #Memory Usage: 18.4 MB, less than 5.02% of Python3 online submissions for Subarray Product Less Than K. 27 | 28 | class Solution: 29 | def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: 30 | i = 0 31 | prod = 1 32 | count = 0 33 | length = len(nums) 34 | for j in range(length): 35 | prod *= nums[j] 36 | while i < j and prod >= k: 37 | prod //= nums[i] 38 | i += 1 39 | if prod < k: 40 | count += j - i + 1 41 | return count 42 | -------------------------------------------------------------------------------- /Medium/775.GlobalandLocalInversions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We have some permutation A of [0, 1, ..., N - 1], where 3 | N is the length of A. 4 | 5 | The number of (global) inversions is the number of i < j 6 | with 0 <= i < j < N and A[i] > A[j]. 7 | 8 | The number of local inversions is the number of i with 9 | 0 <= i < N and A[i] > A[i+1]. 10 | 11 | Return true if and only if the number of global inversions 12 | is equal to the number of local inversions. 13 | 14 | Example: 15 | Input: A = [1,0,2] 16 | Output: true 17 | Explanation: There is 1 global inversion, and 1 local 18 | inversion. 19 | 20 | Example: 21 | Input: A = [1,2,0] 22 | Output: false 23 | Explanation: There are 2 global inversions, and 1 local 24 | inversion. 25 | 26 | Note: 27 | - A will be a permutation of [0, 1, ..., A.length - 1]. 28 | - A will have length in range [1, 5000]. 29 | - The time limit for this problem has been reduced. 30 | ''' 31 | #Difficulty: Medium 32 | #208 / 208 test cases passed. 33 | #Runtime: 324 ms 34 | #Memory Usage: 15.1 MB 35 | 36 | #Runtime: 324 ms, faster than 86.59% of Python3 online submissions for Global and Local Inversions. 37 | #Memory Usage: 15.1 MB, less than 44.06% of Python3 online submissions for Global and Local Inversions. 38 | 39 | class Solution: 40 | def isIdealPermutation(self, A: List[int]) -> bool: 41 | for i in range(len(A)): 42 | if abs(A[i] - i) > 1: 43 | return False 44 | return True -------------------------------------------------------------------------------- /Medium/78.Subsets.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, return all possible subsets 3 | (the power set). 4 | 5 | The solution set must not contain duplicate subsets. 6 | 7 | Example: 8 | Input: nums = [1,2,3] 9 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 10 | 11 | Example: 12 | Input: nums = [0] 13 | Output: [[],[0]] 14 | 15 | Constraints: 16 | - 1 <= nums.length <= 10 17 | - -10 <= nums[i] <= 10 18 | ''' 19 | #Difficulty: Medium 20 | #10 / 10 test cases passed. 21 | #Runtime: 28 ms 22 | #Memory Usage: 14.2 MB 23 | 24 | #Runtime: 28 ms, faster than 93.50% of Python3 online submissions for Subsets. 25 | #Memory Usage: 14.2 MB, less than 75.87% of Python3 online submissions for Subsets. 26 | 27 | from itertools import combinations 28 | 29 | class Solution: 30 | def subsets(self, nums: List[int]) -> List[List[int]]: 31 | result = [[]] 32 | for i in range(1, 1+len(nums)): 33 | result += combinations(nums, i) 34 | return result 35 | -------------------------------------------------------------------------------- /Medium/80.RemoveDuplicatesfromSortedArrayII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sorted array nums, remove the duplicates in-place such that 3 | duplicates appeared at most twice and return the new length. 4 | Do not allocate extra space for another array, you must do this by 5 | modifying the input array in-place with O(1) extra memory. 6 | 7 | Example: 8 | Given nums = [0,0,1,1,1,1,2,3,3], 9 | Your function should return length = 7, with the first seven elements of 10 | nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. 11 | It doesn't matter what values are set beyond the returned length. 12 | 13 | Clarification: 14 | Confused why the returned value is an integer but your answer is an array? 15 | Note that the input array is passed in by reference, which means 16 | modification to the input array will be known to the caller as well. 17 | """ 18 | #Difficulty: Medium 19 | #166 / 166 test cases passed. 20 | #Runtime: 76 ms 21 | #Memory Usage: 14.1 MB 22 | 23 | #Runtime: 76 ms, faster than 16.97% of Python3 online submissions for Remove Duplicates from Sorted Array II. 24 | #Memory Usage: 14.1 MB, less than 5.41% of Python3 online submissions for Remove Duplicates from Sorted Array II. 25 | 26 | class Solution: 27 | def removeDuplicates(self, nums: List[int]) -> int: 28 | s = set(nums) 29 | for num in s: 30 | index = nums.index(num) 31 | count = nums.count(num) 32 | if count >= 2: 33 | nums[:] = nums[:index] + nums[index:index+2] + nums[index+count:] 34 | -------------------------------------------------------------------------------- /Medium/81.SearchinRotatedSortedArrayII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose an array sorted in ascending order is rotated at some pivot unknown 3 | to you beforehand. 4 | (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). 5 | You are given a target value to search. If found in the array return true, 6 | otherwise return false. 7 | 8 | Example: 9 | Input: nums = [2,5,6,0,0,1,2], target = 0 10 | Output: true 11 | 12 | Input: nums = [2,5,6,0,0,1,2], target = 3 13 | Output: false 14 | 15 | Follow up: 16 | - This is a follow up problem to Search in Rotated Sorted Array, where 17 | nums ay contain duplicates. 18 | - Would this affect the run-time complexity? How and why? 19 | """ 20 | #Difficulty: Medium 21 | #275 / 275 test cases passed. 22 | #Runtime: 52 ms 23 | #Memory Usage: 14.2 MB 24 | 25 | #Runtime: 52 ms, faster than 77.59% of Python3 online submissions for Search in Rotated Sorted Array II. 26 | #Memory Usage: 14.2 MB, less than 5.72% of Python3 online submissions for Search in Rotated Sorted Array II. 27 | 28 | class Solution: 29 | def search(self, nums: List[int], target: int) -> bool: 30 | for i in range(len(nums)): 31 | if nums[i] == target: 32 | return True 33 | return False 34 | -------------------------------------------------------------------------------- /Medium/86.PartitionList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a linked list and a value x, partition it such that all nodes less 3 | than x come before nodes greater than or equal to x. 4 | 5 | You should preserve the original relative order of the nodes in each of 6 | the two partitions. 7 | 8 | Example: 9 | Input: head = 1->4->3->2->5->2, x = 3 10 | Output: 1->2->2->4->3->5 11 | """ 12 | #Difficulty: Medium 13 | #166 / 166 test cases passed. 14 | #Runtime: 36 ms 15 | #Memory Usage: 14.2 MB 16 | 17 | #Runtime: 36 ms, faster than 57.43% of Python3 online submissions for Partition List. 18 | #Memory Usage: 14.2 MB, less than 100.00% of Python3 online submissions for Partition List. 19 | 20 | # Definition for singly-linked list. 21 | # class ListNode: 22 | # def __init__(self, val=0, next=None): 23 | # self.val = val 24 | # self.next = next 25 | 26 | class Solution: 27 | def partition(self, head: ListNode, x: int) -> ListNode: 28 | left = [0] 29 | right = [] 30 | curr = head 31 | while curr: 32 | if curr.val < x: 33 | left.append(curr.val) 34 | else: 35 | right.append(curr.val) 36 | curr = curr.next 37 | left.extend(right) 38 | head = ListNode(left.pop(0)) 39 | node = head 40 | while left: 41 | node.next = ListNode(left.pop(0)) 42 | node = node.next 43 | return head.next 44 | -------------------------------------------------------------------------------- /Medium/869.ReorderedPowerof2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Starting with a positive integer N, we reorder the 3 | digits in any order (including the original order) such 4 | that the leading digit is not zero. 5 | 6 | Return true if and only if we can do this in a way such 7 | that the resulting number is a power of 2. 8 | 9 | Example: 10 | Input: 1 11 | Output: true 12 | 13 | Example: 14 | Input: 10 15 | Output: false 16 | 17 | Example: 18 | Input: 16 19 | Output: true 20 | 21 | Example: 22 | Input: 24 23 | Output: false 24 | 25 | Example: 26 | Input: 46 27 | Output: true 28 | 29 | Note: 30 | 1. 1 <= N <= 10^9 31 | ''' 32 | #Difficulty: Medium 33 | #135 / 135 test cases passed. 34 | #Runtime: 32 ms 35 | #Memory Usage: 14.2 MB 36 | 37 | #Runtime: 32 ms, faster than 81.85% of Python3 online submissions for Reordered Power of 2. 38 | #Memory Usage: 14.2 MB, less than 52.82% of Python3 online submissions for Reordered Power of 2. 39 | 40 | class Solution: 41 | def reorderedPowerOf2(self, N: int) -> bool: 42 | N = sorted(str(N)) 43 | for x in range(30): 44 | if N == sorted(str(2**x)): 45 | return True 46 | return False -------------------------------------------------------------------------------- /Medium/912.SortanArray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers nums, sort the array in 3 | ascending order. 4 | 5 | Example: 6 | Input: nums = [5,2,3,1] 7 | Output: [1,2,3,5] 8 | 9 | Example: 10 | Input: nums = [5,1,1,2,0,0] 11 | Output: [0,0,1,1,2,5] 12 | 13 | Constraints: 14 | - 1 <= nums.length <= 50000 15 | - -50000 <= nums[i] <= 50000 16 | ''' 17 | #Difficulty: Medium 18 | #11 / 11 test cases passed. 19 | #Runtime: 124 ms 20 | #Memory Usage: 20.4 MB 21 | 22 | #Runtime: 124 ms, faster than 97.55% of Python3 online submissions for Sort an Array. 23 | #Memory Usage: 20.4 MB, less than 54.14% of Python3 online submissions for Sort an Array. 24 | 25 | class Solution: 26 | def sortArray(self, nums: List[int]) -> List[int]: 27 | return sorted(nums) 28 | -------------------------------------------------------------------------------- /Medium/92.ReverseLinkedListII.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse a linked list from position m to n. Do it in one-pass. 3 | 4 | Note: 1 ≤ m ≤ n ≤ length of list. 5 | 6 | Example: 7 | Input: 1->2->3->4->5->NULL, m = 2, n = 4 8 | Output: 1->4->3->2->5->NULL 9 | """ 10 | #Difficulty: Medium 11 | #44 / 44 test cases passed. 12 | #Runtime: 24 ms 13 | #Memory Usage: 14.2 MB 14 | 15 | #Runtime: 24 ms, faster than 95.46% of Python3 online submissions for Reverse Linked List II. 16 | #Memory Usage: 14.2 MB, less than 100.00% of Python3 online submissions for Reverse Linked List II. 17 | 18 | # Definition for singly-linked list. 19 | # class ListNode: 20 | # def __init__(self, val=0, next=None): 21 | # self.val = val 22 | # self.next = next 23 | 24 | class Solution: 25 | def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: 26 | count = 1 27 | node = head 28 | stack = [] 29 | while count != m: 30 | node = node.next 31 | count += 1 32 | reverse = node 33 | while count <= n: 34 | stack.append(reverse.val) 35 | reverse = reverse.next 36 | count += 1 37 | while stack: 38 | node.val = stack.pop() 39 | node = node.next 40 | return head 41 | -------------------------------------------------------------------------------- /Medium/94.BinaryTreeInorderTraversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, return the inorder traversal of its nodes' values. 3 | 4 | Example: 5 | Input: [1,null,2,3] 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | 12 | Output: [1,3,2] 13 | Follow up: Recursive solution is trivial, could you do it iteratively? 14 | """ 15 | #Difficulty: Medium 16 | #68 / 68 test cases passed. 17 | #Runtime: 40 ms 18 | #Memory Usage: 13.9 MB 19 | 20 | #Runtime: 40 ms, faster than 19.72% of Python3 online submissions for Binary Tree Inorder Traversal. 21 | #Memory Usage: 13.9 MB, less than 27.97% of Python3 online submissions for Binary Tree Inorder Traversal. 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, val=0, left=None, right=None): 26 | # self.val = val 27 | # self.left = left 28 | # self.right = right 29 | 30 | class Solution: 31 | def inorderTraversal(self, root: TreeNode) -> List[int]: 32 | inorder = [] 33 | self.traverse(root, inorder) 34 | return inorder 35 | 36 | def traverse(self, root, inorder): 37 | if not root: 38 | return 0 39 | self.traverse(root.left, inorder) 40 | inorder.append(root.val) 41 | self.traverse(root.right, inorder) 42 | --------------------------------------------------------------------------------