Sorting Pattern: Template + 401 LeetCode Problems

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial.

  • 80 Easy
  • 227 Medium
  • 94 Hard
  • O(n log n) time

What the sorting pattern is

Sorting is rarely the answer on its own; it is the setup that makes the answer obvious, and the skill being tested is choosing the key. Sorting intervals by start time puts every overlap next to its partner, so merging becomes one linear pass. Sorting by finishing time is what makes the greedy interval choice correct. Sorting an array before a two-pointer scan is what lets a comparison decide which pointer to move. Once the input is ordered, duplicates are adjacent, the median is at a known index, and binary search becomes available — three capabilities that between them dissolve a lot of problems. The cost is worth watching: O(n log n) is usually the cheap part next to whatever follows, but when the values are small integers, counting or bucket sort does it in linear time, and when only the kth element is wanted, quickselect gets it in expected linear time without sorting the rest. In Python the `key` argument, and tuples as keys for multi-level ordering, express nearly all of this without a comparator.

When to use it

  • Adjacency in sorted order is what makes the answer visible: overlaps, duplicates, closest pairs.
  • A greedy choice depends on processing items in a specific order.
  • Grouping is by a canonical form that sorting produces, such as sorted letters for anagrams.
  • Only the kth largest is needed and n is large — that is quickselect, not a full sort.
  • Values are bounded small integers, where counting sort beats the comparison lower bound.

The sorting template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 401 problems listed below.

Sorting — Python template
def merge_intervals(intervals):
    intervals.sort(key=lambda pair: pair[0])   # sorting makes overlaps adjacent
    merged = []

    for start, finish in intervals:
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], finish)   # extend the open interval
        else:
            merged.append([start, finish])

    return merged

Complexity characteristics

Time
O(n log n)
Auxiliary space
O(n) for Python's Timsort

Comparison sorts cannot beat n log n, and that bound is usually the cheap part next to whatever the sorted order then enables. Two escapes exist when the input allows them: counting, bucket and radix sort run in linear time when the values are bounded small integers, and quickselect finds the kth element in expected O(n) without ordering the rest. Python's sort is stable and allocates a temporary buffer, so it costs O(n) space rather than the O(log n) an in-place quicksort would suggest.

All 401 sorting LeetCode problems

Every problem in the library the sorting pattern applies to, grouped by LeetCode's own difficulty rating. 346 of the 401 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Easy (80)

#ProblemDifficultyTopics
88Merge Sorted ArrayEasyArray, Two Pointers, Sorting
169Majority ElementEasyArray, Hash Table, Divide and Conquer +2
217Contains DuplicateEasyArray, Hash Table, Sorting
242Valid AnagramEasyHash Table, String, Sorting
268Missing NumberEasyBit Manipulation, Array, Hash Table +3
349Intersection of Two ArraysEasyArray, Hash Table, Two Pointers +2
350Intersection of Two Arrays IIEasyArray, Hash Table, Two Pointers +2
389Find the DifferenceEasyBit Manipulation, Hash Table, String +1
414Third Maximum NumberEasyArray, Sorting
455Assign CookiesEasyGreedy, Array, Two Pointers +1
506Relative RanksEasyArray, Sorting, Heap (Priority Queue)
561Array PartitionEasyGreedy, Array, Counting Sort +1
594Longest Harmonious SubsequenceEasyArray, Hash Table, Counting +2
628Maximum Product of Three NumbersEasyArray, Math, Sorting
645Set MismatchEasyBit Manipulation, Array, Hash Table +1
747Largest Number At Least Twice of OthersEasyArray, Sorting
252Meeting RoomsPremiumEasyArray, Sorting
888Fair Candy SwapEasyArray, Hash Table, Binary Search +1
905Sort Array By ParityEasyArray, Two Pointers, Sorting
922Sort Array By Parity IIEasyArray, Two Pointers, Sorting
976Largest Perimeter TriangleEasyGreedy, Array, Math +1
977Squares of a Sorted ArrayEasyArray, Two Pointers, Sorting
1005Maximize Sum Of Array After K NegationsEasyGreedy, Array, Sorting
1030Matrix Cells in Distance OrderEasyGeometry, Array, Math +2
1051Height CheckerEasyArray, Counting Sort, Sorting
1065Index Pairs of a StringPremiumEasyTrie, Array, String +1
1086High FivePremiumEasyArray, Hash Table, Sorting +1
1099Two Sum Less Than KPremiumEasyArray, Two Pointers, Binary Search +1
1122Relative Sort ArrayEasyArray, Hash Table, Counting Sort +1
1133Largest Unique NumberPremiumEasyArray, Hash Table, Sorting
1196How Many Apples Can You Put into the BasketPremiumEasyGreedy, Array, Sorting
1200Minimum Absolute DifferenceEasyArray, Sorting
1331Rank Transform of an ArrayEasyArray, Hash Table, Sorting
1337The K Weakest Rows in a MatrixEasyArray, Binary Search, Matrix +2
1346Check If N and Its Double ExistEasyArray, Hash Table, Two Pointers +2
1356Sort Integers by The Number of 1 BitsEasyBit Manipulation, Array, Counting +1
1365How Many Numbers Are Smaller Than the Current NumberEasyArray, Hash Table, Counting Sort +1
1385Find the Distance Value Between Two ArraysEasyArray, Two Pointers, Binary Search +1
1403Minimum Subsequence in Non-Increasing OrderEasyGreedy, Array, Sorting
1460Make Two Arrays Equal by Reversing SubarraysEasyArray, Hash Table, Sorting
1464Maximum Product of Two Elements in an ArrayEasyArray, Sorting, Heap (Priority Queue)
1491Average Salary Excluding the Minimum and Maximum SalaryEasyArray, Sorting
1502Can Make Arithmetic Progression From SequenceEasyArray, Sorting
1608Special Array With X Elements Greater Than or Equal XEasyArray, Binary Search, Sorting
1619Mean of Array After Removing Some ElementsEasyArray, Sorting
1636Sort Array by Increasing FrequencyEasyArray, Hash Table, Sorting
1637Widest Vertical Area Between Two Points Containing No PointsEasyArray, Sorting
1710Maximum Units on a TruckEasyGreedy, Array, Sorting
1859Sorting the SentenceEasyString, Sorting
1913Maximum Product Difference Between Two PairsEasyArray, Sorting
1984Minimum Difference Between Highest and Lowest of K ScoresEasyArray, Sorting, Sliding Window
2037Minimum Number of Moves to Seat EveryoneEasyGreedy, Array, Counting Sort +1
2089Find Target Indices After Sorting ArrayEasyArray, Binary Search, Sorting
2094Finding 3-Digit Even NumbersEasyRecursion, Array, Hash Table +2
2099Find Subsequence of Length K With the Largest SumEasyArray, Hash Table, Sorting +1
2144Minimum Cost of Buying Candies With DiscountEasyGreedy, Array, Sorting
2148Count Elements With Strictly Smaller and Greater ElementsEasyArray, Counting, Sorting
2154Keep Multiplying Found Values by TwoEasyArray, Hash Table, Sorting +1
2160Minimum Sum of Four Digit Number After Splitting DigitsEasyGreedy, Math, Sorting
2164Sort Even and Odd Indices IndependentlyEasyArray, Sorting
2229Check if an Array Is ConsecutivePremiumEasyArray, Hash Table, Sorting
2231Largest Number After Digit Swaps by ParityEasySorting, Heap (Priority Queue)
2248Intersection of Multiple ArraysEasyArray, Hash Table, Counting +1
2273Find Resultant Array After Removing AnagramsEasyArray, Hash Table, String +1
2335Minimum Amount of Time to Fill CupsEasyGreedy, Array, Sorting +1
2357Make Array Zero by Subtracting Equal AmountsEasyGreedy, Array, Hash Table +3
2363Merge Similar ItemsEasyArray, Hash Table, Ordered Set +1
2389Longest Subsequence With Limited SumEasyGreedy, Array, Binary Search +2
2418Sort the PeopleEasyArray, Hash Table, String +1
2441Largest Positive Integer That Exists With Its NegativeEasyArray, Hash Table, Two Pointers +1
2465Number of Distinct AveragesEasyArray, Hash Table, Two Pointers +1
2475Number of Unequal Triplets in ArrayEasyArray, Hash Table, Sorting
2500Delete Greatest Value in Each RowEasyArray, Matrix, Sorting +2
2578Split With Minimum SumEasyGreedy, Math, Sorting
2706Buy Two ChocolatesEasyGreedy, Array, Sorting
2733Neither Minimum nor MaximumEasyArray, Sorting
2784Check if Array is GoodEasyArray, Hash Table, Sorting
2824Count Pairs Whose Sum is Less than TargetEasyArray, Two Pointers, Binary Search +1
2974Minimum Number GameEasyArray, Sorting, Simulation +1
2996Smallest Missing Integer Greater Than Sequential Prefix SumEasyArray, Hash Table, Sorting

Medium (227)

#ProblemDifficultyTopics
153SumMediumArray, Two Pointers, Sorting
163Sum ClosestMediumArray, Two Pointers, Sorting
184SumMediumArray, Two Pointers, Sorting
47Permutations IIMediumArray, Backtracking, Sorting
49Group AnagramsMediumArray, Hash Table, String +1
56Merge IntervalsMediumArray, Sorting
75Sort ColorsMediumArray, Two Pointers, Sorting
147Insertion Sort ListMediumLinked List, Sorting
148Sort ListMediumLinked List, Two Pointers, Divide and Conquer +2
164Maximum GapMediumArray, Bucket Sort, Radix Sort +1
179Largest NumberMediumGreedy, Array, String +1
215Kth Largest Element in an ArrayMediumArray, Divide and Conquer, Quickselect +2
229Majority Element IIMediumArray, Hash Table, Counting +1
274H-IndexMediumArray, Counting Sort, Sorting
324Wiggle Sort IIMediumGreedy, Array, Divide and Conquer +2
347Top K Frequent ElementsMediumArray, Hash Table, Divide and Conquer +5
368Largest Divisible SubsetMediumArray, Math, Dynamic Programming +1
378Kth Smallest Element in a Sorted MatrixMediumArray, Binary Search, Matrix +2
406Queue Reconstruction by HeightMediumBinary Indexed Tree, Segment Tree, Array +1
435Non-overlapping IntervalsMediumGreedy, Array, Dynamic Programming +1
436Find Right IntervalMediumArray, Binary Search, Sorting
442Find All Duplicates in an ArrayMediumArray, Hash Table, Sorting
451Sort Characters By FrequencyMediumHash Table, String, Bucket Sort +3
452Minimum Number of Arrows to Burst BalloonsMediumGreedy, Array, Sorting
462Minimum Moves to Equal Array Elements IIMediumArray, Math, Sorting
475HeatersMediumArray, Two Pointers, Binary Search +1
522Longest Uncommon Subsequence IIMediumArray, Hash Table, Two Pointers +2
524Longest Word in Dictionary through DeletingMediumArray, Two Pointers, String +1
532K-diff Pairs in an ArrayMediumArray, Hash Table, Two Pointers +2
539Minimum Time DifferenceMediumArray, Math, String +1
581Shortest Unsorted Continuous SubarrayMediumStack, Greedy, Array +3
611Valid Triangle NumberMediumGreedy, Array, Two Pointers +2
621Task SchedulerMediumGreedy, Array, Hash Table +3
646Maximum Length of Pair ChainMediumGreedy, Array, Dynamic Programming +1
658Find K Closest ElementsMediumArray, Two Pointers, Binary Search +3
692Top K Frequent WordsMediumTrie, Array, Hash Table +5
720Longest Word in DictionaryMediumTrie, Array, Hash Table +2
721Accounts MergeMediumDepth-First Search, Breadth-First Search, Union Find +4
846Hand of StraightsMediumGreedy, Array, Hash Table +1
853Car FleetMediumStack, Array, Sorting +1
973K Closest Points to OriginMediumGeometry, Array, Math +4
1268Search Suggestions SystemMediumTrie, Array, String +3
1657Determine if Two Strings Are CloseMediumHash Table, String, Counting +1
1679Max Number of K-Sum PairsMediumArray, Hash Table, Two Pointers +1
2300Successful Pairs of Spells and PotionsMediumArray, Two Pointers, Binary Search +1
2542Maximum Subsequence ScoreMediumGreedy, Array, Sorting +1
253Meeting Rooms IIPremiumMediumGreedy, Array, Two Pointers +3
2593Sum SmallerPremiumMediumArray, Two Pointers, Binary Search +1
280Wiggle SortPremiumMediumGreedy, Array, Sorting
314Binary Tree Vertical Order TraversalPremiumMediumTree, Depth-First Search, Breadth-First Search +3
360Sort Transformed ArrayPremiumMediumArray, Math, Two Pointers +1
767Reorganize StringMediumGreedy, Hash Table, String +3
769Max Chunks To Make SortedMediumStack, Greedy, Array +2
786K-th Smallest Prime FractionMediumArray, Two Pointers, Binary Search +2
791Custom Sort StringMediumHash Table, String, Sorting
792Number of Matching SubsequencesMediumTrie, Array, Hash Table +4
823Binary Trees With FactorsMediumArray, Hash Table, Dynamic Programming +1
825Friends Of Appropriate AgesMediumArray, Two Pointers, Binary Search +1
826Most Profit Assigning WorkMediumGreedy, Array, Two Pointers +2
833Find And Replace in StringMediumArray, Hash Table, String +1
869Reordered Power of 2MediumHash Table, Math, Counting +2
870Advantage ShuffleMediumGreedy, Array, Two Pointers +1
881Boats to Save PeopleMediumGreedy, Array, Two Pointers +1
893Groups of Special-Equivalent StringsMediumArray, Hash Table, String +1
910Smallest Range IIMediumGreedy, Array, Math +1
912Sort an ArrayMediumArray, Divide and Conquer, Bucket Sort +5
9233Sum With MultiplicityMediumArray, Hash Table, Two Pointers +2
937Reorder Data in Log FilesMediumArray, String, Sorting
939Minimum Area RectangleMediumGeometry, Array, Hash Table +2
945Minimum Increment to Make Array UniqueMediumGreedy, Array, Counting +1
948Bag of TokensMediumGreedy, Array, Two Pointers +1
950Reveal Cards In Increasing OrderMediumQueue, Array, Sorting +1
954Array of Doubled PairsMediumGreedy, Array, Hash Table +1
969Pancake SortingMediumGreedy, Array, Two Pointers +1
1029Two City SchedulingMediumGreedy, Array, Sorting
1040Moving Stones Until Consecutive IIMediumArray, Math, Sorting +1
1048Longest String ChainMediumArray, Hash Table, Two Pointers +3
1054Distant BarcodesMediumGreedy, Array, Hash Table +3
1057Campus BikesPremiumMediumArray, Sorting, Heap (Priority Queue)
1058Minimize Rounding Error to Meet TargetPremiumMediumGreedy, Array, Math +2
1087Brace ExpansionPremiumMediumStack, Breadth-First Search, String +2
1090Largest Values From LabelsMediumGreedy, Array, Hash Table +2
1094Car PoolingMediumArray, Prefix Sum, Sorting +2
1101The Earliest Moment When Everyone Become FriendsPremiumMediumUnion Find, Array, Sorting
1152Analyze User Website Visit PatternPremiumMediumArray, Hash Table, String +1
1169Invalid TransactionsMediumArray, Hash Table, String +1
1170Compare Strings by Frequency of the Smallest CharacterMediumArray, Hash Table, String +2
1181Before and After PuzzlePremiumMediumArray, Hash Table, String +1
1202Smallest String With SwapsMediumDepth-First Search, Breadth-First Search, Union Find +4
1229Meeting SchedulerPremiumMediumArray, Two Pointers, Sorting
1244Design A LeaderboardPremiumMediumDesign, Hash Table, Sorting
1262Greatest Sum Divisible by ThreeMediumGreedy, Array, Dynamic Programming +1
1288Remove Covered IntervalsMediumArray, Sorting
1296Divide Array in Sets of K Consecutive NumbersMediumGreedy, Array, Hash Table +1
1300Sum of Mutated Array Closest to TargetMediumArray, Binary Search, Sorting
1305All Elements in Two Binary Search TreesMediumTree, Depth-First Search, Binary Search Tree +2
1311Get Watched Videos by Your FriendsMediumBreadth-First Search, Graph, Array +2
1329Sort the Matrix DiagonallyMediumArray, Matrix, Sorting
1333Filter Restaurants by Vegan-Friendly, Price and DistanceMediumArray, Sorting
1338Reduce Array Size to The HalfMediumGreedy, Array, Hash Table +2
1348Tweet Counts Per FrequencyMediumDesign, Hash Table, String +3
1353Maximum Number of Events That Can Be AttendedMediumGreedy, Array, Sorting +1
1366Rank Teams by VotesMediumArray, Hash Table, String +2
1387Sort Integers by The Power ValueMediumMemoization, Dynamic Programming, Sorting
1418Display Table of Food Orders in a RestaurantMediumArray, Hash Table, String +2
1424Diagonal Traverse IIMediumArray, Sorting, Heap (Priority Queue)
1433Check If a String Can Break Another StringMediumGreedy, String, Sorting
1451Rearrange Words in a SentenceMediumString, Sorting
1465Maximum Area of a Piece of Cake After Horizontal and Vertical CutsMediumGreedy, Array, Sorting
1471The k Strongest Values in an ArrayMediumArray, Two Pointers, Sorting
1481Least Number of Unique Integers after K RemovalsMediumGreedy, Array, Hash Table +2
1498Number of Subsequences That Satisfy the Given Sum ConditionMediumArray, Two Pointers, Binary Search +1
1500Design a File Sharing SystemPremiumMediumDesign, Hash Table, Data Stream +2
1508Range Sum of Sorted Subarray SumsMediumArray, Two Pointers, Binary Search +2
1509Minimum Difference Between Largest and Smallest Value in Three MovesMediumGreedy, Array, Sorting
1552Magnetic Force Between Two BallsMediumArray, Binary Search, Sorting
1561Maximum Number of Coins You Can GetMediumGreedy, Array, Math +2
1564Put Boxes Into the Warehouse IPremiumMediumGreedy, Array, Sorting
1580Put Boxes Into the Warehouse IIPremiumMediumGreedy, Array, Sorting
1589Maximum Sum Obtained of Any PermutationMediumGreedy, Array, Prefix Sum +1
1604Alert Using Same Key-Card Three or More Times in a One Hour PeriodMediumArray, Hash Table, String +1
1626Best Team With No ConflictsMediumArray, Dynamic Programming, Sorting
1630Arithmetic SubarraysMediumArray, Hash Table, Sorting
1647Minimum Deletions to Make Character Frequencies UniqueMediumGreedy, Hash Table, String +1
1648Sell Diminishing-Valued Colored BallsMediumGreedy, Array, Math +3
1686Stone Game VIMediumGreedy, Array, Math +3
1727Largest Submatrix With RearrangementsMediumGreedy, Array, Matrix +1
1738Find Kth Largest XOR Coordinate ValueMediumBit Manipulation, Array, Divide and Conquer +5
1772Sort Features by PopularityPremiumMediumArray, Hash Table, String +1
1798Maximum Number of Consecutive Values You Can MakeMediumGreedy, Array, Sorting
1818Minimum Absolute Sum DifferenceMediumArray, Binary Search, Ordered Set +1
1833Maximum Ice Cream BarsMediumGreedy, Array, Counting Sort +1
1834Single-Threaded CPUMediumArray, Sorting, Heap (Priority Queue)
1838Frequency of the Most Frequent ElementMediumGreedy, Array, Binary Search +3
1846Maximum Element After Decreasing and RearrangingMediumGreedy, Array, Sorting
1874Minimize Product Sum of Two ArraysPremiumMediumGreedy, Array, Sorting
1877Minimize Maximum Pair Sum in ArrayMediumGreedy, Array, Two Pointers +1
1878Get Biggest Three Rhombus Sums in a GridMediumArray, Math, Matrix +3
1885Count Pairs in Two ArraysPremiumMediumArray, Two Pointers, Binary Search +1
1887Reduction Operations to Make the Array Elements EqualMediumArray, Sorting
1921Eliminate Maximum Number of MonstersMediumGreedy, Array, Sorting
1943Describe the PaintingMediumArray, Hash Table, Prefix Sum +1
1968Array With Elements Not Equal to Average of NeighborsMediumGreedy, Array, Sorting
1985Find the Kth Largest Integer in the ArrayMediumArray, String, Divide and Conquer +3
1996The Number of Weak Characters in the GameMediumStack, Greedy, Array +2
2007Find Original Array From Doubled ArrayMediumGreedy, Array, Hash Table +1
2008Maximum Earnings From TaxiMediumArray, Hash Table, Binary Search +2
2015Average Height of Buildings in Each SegmentPremiumMediumGreedy, Array, Sorting +1
2021Brightest Position on StreetPremiumMediumArray, Ordered Set, Prefix Sum +1
2031Count Subarrays With More Ones Than ZerosPremiumMediumBinary Indexed Tree, Segment Tree, Array +5
2033Minimum Operations to Make a Uni-Value GridMediumArray, Math, Matrix +1
2046Sort Linked List Already Sorted Using Absolute ValuesPremiumMediumLinked List, Two Pointers, Sorting
2054Two Best Non-Overlapping EventsMediumArray, Binary Search, Dynamic Programming +2
2070Most Beautiful Item for Each QueryMediumArray, Binary Search, Sorting
2098Subsequence of Size K With the Largest Even SumPremiumMediumGreedy, Array, Sorting
2126Destroying AsteroidsMediumGreedy, Array, Sorting
2135Count Words Obtained After Adding a LetterMediumBit Manipulation, Array, Hash Table +2
2146K Highest Ranked Items Within a Price RangeMediumBreadth-First Search, Array, Matrix +2
2165Smallest Value of the Rearranged NumberMediumMath, Sorting
2171Removing Minimum Number of Magic BeansMediumGreedy, Array, Enumeration +2
2191Sort the Jumbled NumbersMediumArray, Sorting
2195Append K Integers With Minimal SumMediumGreedy, Array, Math +1
2225Find Players With Zero or One LossesMediumArray, Hash Table, Counting +1
2250Count Number of Rectangles Containing Each PointMediumBinary Indexed Tree, Array, Hash Table +2
2268Minimum Number of KeypressesPremiumMediumGreedy, Hash Table, String +2
2271Maximum White Tiles Covered by a CarpetMediumGreedy, Array, Binary Search +3
2274Maximum Consecutive Floors Without Special FloorsMediumArray, Sorting
2279Maximum Bags With Full Capacity of RocksMediumGreedy, Array, Sorting
2280Minimum Lines to Represent a Line ChartMediumGeometry, Array, Math +2
2285Maximum Total Importance of RoadsMediumGreedy, Graph, Sorting +1
2294Partition Array Such That Maximum Difference Is KMediumGreedy, Array, Sorting
2323Find Minimum Time to Finish All Jobs IIPremiumMediumGreedy, Array, Sorting
2332The Latest Time to Catch a BusMediumArray, Two Pointers, Binary Search +1
2333Minimum Sum of Squared DifferenceMediumGreedy, Array, Binary Search +2
2342Max Sum of a Pair With Equal Sum of DigitsMediumArray, Hash Table, Sorting +1
2343Query Kth Smallest Trimmed NumberMediumArray, String, Divide and Conquer +4
2345Finding the Number of Visible MountainsPremiumMediumStack, Array, Sorting +1
2406Divide Intervals Into Minimum Number of GroupsMediumGreedy, Array, Two Pointers +3
2410Maximum Matching of Players With TrainersMediumGreedy, Array, Two Pointers +1
2456Most Popular Video CreatorMediumArray, Hash Table, String +2
2491Divide Players Into Teams of Equal SkillMediumArray, Hash Table, Two Pointers +1
2497Maximum Star Sum of a GraphMediumGreedy, Graph, Array +2
2501Longest Square Streak in an ArrayMediumArray, Hash Table, Binary Search +2
2512Reward Top K StudentsMediumArray, Hash Table, String +2
2517Maximum Tastiness of Candy BasketMediumGreedy, Array, Binary Search +1
2545Sort the Students by Their Kth ScoreMediumArray, Matrix, Sorting
2548Maximum Price to Fill a BagPremiumMediumGreedy, Array, Sorting
2554Maximum Number of Integers to Choose From a Range IMediumGreedy, Array, Hash Table +2
2557Maximum Number of Integers to Choose From a Range IIPremiumMediumGreedy, Array, Binary Search +1
2563Count the Number of Fair PairsMediumArray, Two Pointers, Binary Search +1
2567Minimum Score by Changing Two ElementsMediumGreedy, Array, Sorting
2576Find the Maximum Number of Marked IndicesMediumGreedy, Array, Two Pointers +2
2580Count Ways to Group Overlapping RangesMediumArray, Sorting
2583Kth Largest Sum in a Binary TreeMediumTree, Breadth-First Search, Binary Tree +1
2587Rearrange Array to Maximize Prefix ScoreMediumGreedy, Array, Prefix Sum +1
2590Design a Todo ListPremiumMediumDesign, Array, Hash Table +2
2592Maximize Greatness of an ArrayMediumGreedy, Array, Two Pointers +1
2593Find Score of an Array After Marking All ElementsMediumArray, Hash Table, Sorting +2
2597The Number of Beautiful SubsetsMediumArray, Hash Table, Math +4
2602Minimum Operations to Make All Array Elements EqualMediumArray, Binary Search, Prefix Sum +1
2607Make K-Subarray Sums EqualMediumGreedy, Array, Math +2
2611Mice and CheeseMediumGreedy, Array, Sorting +1
2616Minimize the Maximum Difference of PairsMediumGreedy, Array, Binary Search +2
2638Count the Number of K-Free SubsetsPremiumMediumArray, Math, Dynamic Programming +2
2655Find Maximal Uncovered RangesPremiumMediumArray, Sorting
2679Sum in a MatrixMediumArray, Matrix, Sorting +2
2708Maximum Strength of a GroupMediumGreedy, Bit Manipulation, Array +4
2731Movement of RobotsMediumBrainteaser, Array, Prefix Sum +1
2740Find the Value of the PartitionMediumArray, Sorting
2747Count Zero Request ServersMediumArray, Hash Table, Sorting +1
2766Relocate MarblesMediumArray, Hash Table, Sorting +1
2779Maximum Beauty of an Array After Applying OperationMediumArray, Binary Search, Sorting +1
2780Minimum Index of a Valid SplitMediumArray, Hash Table, Sorting
2785Sort Vowels in a StringMediumString, Sorting
2830Maximize the Profit as the SalesmanMediumArray, Hash Table, Binary Search +2
2838Maximum Coins Heroes Can CollectPremiumMediumArray, Two Pointers, Binary Search +2
2840Check if Strings Can be Made Equal With Operations IIMediumHash Table, String, Sorting
2860Happy StudentsMediumArray, Enumeration, Sorting
2863Maximum Length of Semi-Decreasing SubarraysPremiumMediumStack, Array, Sorting +1
2895Minimum Processing TimeMediumGreedy, Array, Sorting
2933High-Access EmployeesMediumArray, Hash Table, String +1
2943Maximize Area of Square Hole in GridMediumArray, Sorting
2948Make Lexicographically Smallest Array by Swapping ElementsMediumUnion Find, Array, Sorting
2952Minimum Number of Coins to be AddedMediumGreedy, Array, Sorting
2966Divide Array Into Arrays With Max DifferenceMediumGreedy, Array, Sorting
2967Minimum Cost to Make Array EqualindromicMediumGreedy, Array, Math +2
2971Find Polygon With the Largest PerimeterMediumGreedy, Array, Prefix Sum +1

Hard (94)

#ProblemDifficultyTopics
23Merge k Sorted ListsHardLinked List, Divide and Conquer, Heap (Priority Queue) +1
218The Skyline ProblemHardBinary Indexed Tree, Segment Tree, Array +5
220Contains Duplicate IIIHardArray, Bucket Sort, Ordered Set +2
295Find Median from Data StreamHardDesign, Two Pointers, Data Stream +2
315Count of Smaller Numbers After SelfHardBinary Indexed Tree, Segment Tree, Array +4
327Count of Range SumHardBinary Indexed Tree, Segment Tree, Array +4
354Russian Doll EnvelopesHardArray, Binary Search, Dynamic Programming +1
472Concatenated WordsHardDepth-First Search, Trie, Array +3
493Reverse PairsHardBinary Indexed Tree, Segment Tree, Array +4
502IPOHardGreedy, Array, Sorting +1
630Course Schedule IIIHardGreedy, Array, Sorting +1
632Smallest Range Covering Elements from K ListsHardGreedy, Array, Hash Table +3
710Random Pick with BlacklistHardArray, Hash Table, Math +3
719Find K-th Smallest Pair DistanceHardArray, Two Pointers, Binary Search +1
1235Maximum Profit in Job SchedulingHardArray, Binary Search, Dynamic Programming +1
1851Minimum Interval to Include Each QueryHardArray, Binary Search, Sorting +2
296Best Meeting PointPremiumHardArray, Math, Matrix +1
358Rearrange String k Distance ApartPremiumHardGreedy, Hash Table, String +3
527Word AbbreviationPremiumHardGreedy, Trie, Array +2
588Design In-Memory File SystemPremiumHardDesign, Trie, Hash Table +2
642Design Search Autocomplete SystemPremiumHardDepth-First Search, Design, Trie +4
726Number of AtomsHardStack, Hash Table, String +1
757Set Intersection Size At Least TwoHardGreedy, Array, Sorting
759Employee Free TimePremiumHardArray, Sorting, Line Sweep +1
768Max Chunks To Make Sorted IIHardStack, Greedy, Array +2
857Minimum Cost to Hire K WorkersHardGreedy, Array, Sorting +1
891Sum of Subsequence WidthsHardArray, Math, Sorting
899Orderly QueueHardMath, String, Sorting
975Odd Even JumpHardStack, Array, Dynamic Programming +3
987Vertical Order Traversal of a Binary TreeHardTree, Depth-First Search, Breadth-First Search +3
1096Brace Expansion IIHardStack, Breadth-First Search, Hash Table +3
1183Maximum Number of OnesPremiumHardGreedy, Math, Sorting +1
1187Make Array Strictly IncreasingHardArray, Binary Search, Dynamic Programming +1
1340Jump Game VHardArray, Dynamic Programming, Sorting
1363Largest Multiple of ThreeHardGreedy, Array, Math +2
1383Maximum Performance of a TeamHardGreedy, Array, Sorting +1
1402Reducing DishesHardGreedy, Array, Dynamic Programming +1
1478Allocate MailboxesHardArray, Math, Dynamic Programming +1
1489Find Critical and Pseudo-Critical Edges in Minimum Spanning TreeHardUnion Find, Graph, Minimum Spanning Tree +2
1547Minimum Cost to Cut a StickHardArray, Dynamic Programming, Sorting
1585Check If String Is Transformable With Substring Sort OperationsHardGreedy, String, Sorting
1610Maximum Number of Visible PointsHardGeometry, Array, Math +2
1632Rank Transform of a MatrixHardUnion Find, Graph, Topological Sort +3
1649Create Sorted Array through InstructionsHardBinary Indexed Tree, Segment Tree, Array +4
1665Minimum Initial Energy to Finish TasksHardGreedy, Array, Sorting
1691Maximum Height by Stacking CuboidsHardArray, Dynamic Programming, Sorting
1697Checking Existence of Edge Length Limited PathsHardUnion Find, Graph, Array +2
1751Maximum Number of Events That Can Be Attended IIHardArray, Binary Search, Dynamic Programming +1
1755Closest Subsequence SumHardBit Manipulation, Array, Two Pointers +3
1782Count Pairs Of NodesHardGraph, Array, Hash Table +4
1840Maximum Building HeightHardArray, Math, Sorting
1847Closest RoomHardArray, Binary Search, Ordered Set +1
1889Minimum Space Wasted From PackagingHardArray, Binary Search, Prefix Sum +1
1998GCD Sort of an ArrayHardUnion Find, Array, Math +2
2071Maximum Number of Tasks You Can AssignHardGreedy, Queue, Array +4
2092Find All People With SecretHardDepth-First Search, Breadth-First Search, Union Find +2
2122Recover the Original ArrayHardArray, Hash Table, Two Pointers +2
2136Earliest Possible Day of Full BloomHardGreedy, Array, Sorting
2141Maximum Running Time of N ComputersHardGreedy, Array, Binary Search +1
2179Count Good Triplets in an ArrayHardBinary Indexed Tree, Segment Tree, Array +4
2234Maximum Total Beauty of the GardensHardGreedy, Array, Two Pointers +4
2242Maximum Score of a Node SequenceHardGraph, Array, Enumeration +1
2251Number of Flowers in Full BloomHardArray, Hash Table, Binary Search +3
2344Minimum Deletions to Make Array DivisibleHardArray, Math, Number Theory +2
2371Minimize Maximum Value in a GridPremiumHardUnion Find, Graph, Topological Sort +3
2386Find the K-Sum of an ArrayHardArray, Sorting, Heap (Priority Queue)
2402Meeting Rooms IIIHardArray, Hash Table, Sorting +2
2412Minimum Money Required Before TransactionsHardGreedy, Array, Sorting
2421Number of Good PathsHardTree, Union Find, Graph +3
2426Number of Pairs Satisfying InequalityHardBinary Indexed Tree, Segment Tree, Array +4
2448Minimum Cost to Make Array EqualHardGreedy, Array, Binary Search +2
2449Minimum Number of Operations to Make Arrays SimilarHardGreedy, Array, Sorting
2454Next Greater Element IVHardStack, Array, Binary Search +3
2459Sort Array by Moving Items to Empty SpacePremiumHardGreedy, Array, Sorting
2463Minimum Total Distance TraveledHardArray, Dynamic Programming, Sorting
2503Maximum Number of Points From Grid QueriesHardBreadth-First Search, Union Find, Array +4
2519Count the Number of K-Big IndicesPremiumHardBinary Indexed Tree, Segment Tree, Array +4
2551Put Marbles in BagsHardGreedy, Array, Sorting +1
2589Minimum Time to Complete All TasksHardStack, Greedy, Array +2
2604Minimum Time to Eat All GrainsPremiumHardArray, Two Pointers, Binary Search +1
2613Beautiful PairsPremiumHardGeometry, Array, Math +3
2659Make Array EmptyHardGreedy, Binary Indexed Tree, Segment Tree +4
2681Power of HeroesHardArray, Math, Dynamic Programming +2
2713Maximum Strictly Increasing Cells in a MatrixHardMemoization, Array, Hash Table +5
2736Maximum Sum QueriesHardStack, Binary Indexed Tree, Segment Tree +4
2751Robot CollisionsHardStack, Array, Sorting +1
2790Maximum Number of Groups With Increasing LengthHardGreedy, Array, Math +2
2809Minimum Time to Make Array Sum At Most xHardArray, Dynamic Programming, Sorting
2813Maximum Elegance of a K-Length SubsequenceHardStack, Greedy, Array +3
2818Apply Operations to Maximize ScoreHardStack, Greedy, Array +4
2819Minimum Relative Loss After Buying ChocolatesPremiumHardArray, Binary Search, Prefix Sum +1
2931Maximum Spending After Buying ItemsHardGreedy, Array, Matrix +2
2968Apply Operations to Maximize Frequency ScoreHardArray, Binary Search, Prefix Sum +2
2973Find Number of Coins to Place in Tree NodesHardTree, Depth-First Search, Dynamic Programming +2

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

Sorting pattern FAQ

What is the sorting pattern?

Sorting is rarely the answer on its own; it is the setup that makes the answer obvious, and the skill being tested is choosing the key. Sorting intervals by start time puts every overlap next to its partner, so merging becomes one linear pass.

How many LeetCode problems use the sorting pattern?

This page lists 401 LeetCode problems that the sorting pattern applies to: 80 Easy, 227 Medium and 94 Hard. 346 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the sorting pattern?

O(n log n) time and O(n) for Python's Timsort space. Comparison sorts cannot beat n log n, and that bound is usually the cheap part next to whatever the sorted order then enables. Two escapes exist when the input allows them: counting, bucket and radix sort run in linear time when the values are bounded small integers, and quickselect finds the kth element in expected O(n) without ordering the rest. Python's sort is stable and allocates a temporary buffer, so it costs O(n) space rather than the O(log n) an in-place quicksort would suggest.

When should I use the sorting pattern in an interview?

Adjacency in sorted order is what makes the answer visible: overlaps, duplicates, closest pairs. A greedy choice depends on processing items in a specific order.

Which sorting problem should I start with?

LeetCode 88. Merge Sorted Array is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to sorting?

Greedy, Two Pointers, Binary Search, Heap / Priority Queue. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.

Meet the sorting problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer is saying — while staying invisible to screen sharing.