Pattern 07 of 22

Sorting Pattern: Template + 401 LeetCode Problems

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

Easy
80
Medium
227
Hard
94
Time
O(n log n)

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.

PythonSorting 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.

Eyes only

Meet the sorting problem you did not practise.

In the live round, Stealth Interview reads the 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 says. It's a desktop app for macOS and Windows, invisible to screen sharing.

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)

Easy problems
No.Problem
0088Merge Sorted Array
0169Majority Element
0217Contains Duplicate
0242Valid Anagram
0268Missing Number
0349Intersection of Two Arrays
0350Intersection of Two Arrays II
0389Find the Difference
0414Third Maximum Number
0455Assign Cookies
0506Relative Ranks
0561Array Partition
0594Longest Harmonious Subsequence
0628Maximum Product of Three Numbers
0645Set Mismatch
0747Largest Number At Least Twice of Others
0252Meeting RoomsPremium
0888Fair Candy Swap
0905Sort Array By Parity
0922Sort Array By Parity II
0976Largest Perimeter Triangle
0977Squares of a Sorted Array
1005Maximize Sum Of Array After K Negations
1030Matrix Cells in Distance Order
1051Height Checker
1065Index Pairs of a StringPremium
1086High FivePremium
1099Two Sum Less Than KPremium
1122Relative Sort Array
1133Largest Unique NumberPremium
1196How Many Apples Can You Put into the BasketPremium
1200Minimum Absolute Difference
1331Rank Transform of an Array
1337The K Weakest Rows in a Matrix
1346Check If N and Its Double Exist
1356Sort Integers by The Number of 1 Bits
1365How Many Numbers Are Smaller Than the Current Number
1385Find the Distance Value Between Two Arrays
1403Minimum Subsequence in Non-Increasing Order
1460Make Two Arrays Equal by Reversing Subarrays
1464Maximum Product of Two Elements in an Array
1491Average Salary Excluding the Minimum and Maximum Salary
1502Can Make Arithmetic Progression From Sequence
1608Special Array With X Elements Greater Than or Equal X
1619Mean of Array After Removing Some Elements
1636Sort Array by Increasing Frequency
1637Widest Vertical Area Between Two Points Containing No Points
1710Maximum Units on a Truck
1859Sorting the Sentence
1913Maximum Product Difference Between Two Pairs
1984Minimum Difference Between Highest and Lowest of K Scores
2037Minimum Number of Moves to Seat Everyone
2089Find Target Indices After Sorting Array
2094Finding 3-Digit Even Numbers
2099Find Subsequence of Length K With the Largest Sum
2144Minimum Cost of Buying Candies With Discount
2148Count Elements With Strictly Smaller and Greater Elements
2154Keep Multiplying Found Values by Two
2160Minimum Sum of Four Digit Number After Splitting Digits
2164Sort Even and Odd Indices Independently
2229Check if an Array Is ConsecutivePremium
2231Largest Number After Digit Swaps by Parity
2248Intersection of Multiple Arrays
2273Find Resultant Array After Removing Anagrams
2335Minimum Amount of Time to Fill Cups
2357Make Array Zero by Subtracting Equal Amounts
2363Merge Similar Items
2389Longest Subsequence With Limited Sum
2418Sort the People
2441Largest Positive Integer That Exists With Its Negative
2465Number of Distinct Averages
2475Number of Unequal Triplets in Array
2500Delete Greatest Value in Each Row
2578Split With Minimum Sum
2706Buy Two Chocolates
2733Neither Minimum nor Maximum
2784Check if Array is Good
2824Count Pairs Whose Sum is Less than Target
2974Minimum Number Game
2996Smallest Missing Integer Greater Than Sequential Prefix Sum

Medium (227)

Medium problems
No.Problem
00153Sum
00163Sum Closest
00184Sum
0047Permutations II
0049Group Anagrams
0056Merge Intervals
0075Sort Colors
0147Insertion Sort List
0148Sort List
0164Maximum Gap
0179Largest Number
0215Kth Largest Element in an Array
0229Majority Element II
0274H-Index
0324Wiggle Sort II
0347Top K Frequent Elements
0368Largest Divisible Subset
0378Kth Smallest Element in a Sorted Matrix
0406Queue Reconstruction by Height
0435Non-overlapping Intervals
0436Find Right Interval
0442Find All Duplicates in an Array
0451Sort Characters By Frequency
0452Minimum Number of Arrows to Burst Balloons
0462Minimum Moves to Equal Array Elements II
0475Heaters
0522Longest Uncommon Subsequence II
0524Longest Word in Dictionary through Deleting
0532K-diff Pairs in an Array
0539Minimum Time Difference
0581Shortest Unsorted Continuous Subarray
0611Valid Triangle Number
0621Task Scheduler
0646Maximum Length of Pair Chain
0658Find K Closest Elements
0692Top K Frequent Words
0720Longest Word in Dictionary
0721Accounts Merge
0846Hand of Straights
0853Car Fleet
0973K Closest Points to Origin
1268Search Suggestions System
1657Determine if Two Strings Are Close
1679Max Number of K-Sum Pairs
2300Successful Pairs of Spells and Potions
2542Maximum Subsequence Score
0253Meeting Rooms IIPremium
02593Sum SmallerPremium
0280Wiggle SortPremium
0314Binary Tree Vertical Order TraversalPremium
0360Sort Transformed ArrayPremium
0767Reorganize String
0769Max Chunks To Make Sorted
0786K-th Smallest Prime Fraction
0791Custom Sort String
0792Number of Matching Subsequences
0823Binary Trees With Factors
0825Friends Of Appropriate Ages
0826Most Profit Assigning Work
0833Find And Replace in String
0869Reordered Power of 2
0870Advantage Shuffle
0881Boats to Save People
0893Groups of Special-Equivalent Strings
0910Smallest Range II
0912Sort an Array
09233Sum With Multiplicity
0937Reorder Data in Log Files
0939Minimum Area Rectangle
0945Minimum Increment to Make Array Unique
0948Bag of Tokens
0950Reveal Cards In Increasing Order
0954Array of Doubled Pairs
0969Pancake Sorting
1029Two City Scheduling
1040Moving Stones Until Consecutive II
1048Longest String Chain
1054Distant Barcodes
1057Campus BikesPremium
1058Minimize Rounding Error to Meet TargetPremium
1087Brace ExpansionPremium
1090Largest Values From Labels
1094Car Pooling
1101The Earliest Moment When Everyone Become FriendsPremium
1152Analyze User Website Visit PatternPremium
1169Invalid Transactions
1170Compare Strings by Frequency of the Smallest Character
1181Before and After PuzzlePremium
1202Smallest String With Swaps
1229Meeting SchedulerPremium
1244Design A LeaderboardPremium
1262Greatest Sum Divisible by Three
1288Remove Covered Intervals
1296Divide Array in Sets of K Consecutive Numbers
1300Sum of Mutated Array Closest to Target
1305All Elements in Two Binary Search Trees
1311Get Watched Videos by Your Friends
1329Sort the Matrix Diagonally
1333Filter Restaurants by Vegan-Friendly, Price and Distance
1338Reduce Array Size to The Half
1348Tweet Counts Per Frequency
1353Maximum Number of Events That Can Be Attended
1366Rank Teams by Votes
1387Sort Integers by The Power Value
1418Display Table of Food Orders in a Restaurant
1424Diagonal Traverse II
1433Check If a String Can Break Another String
1451Rearrange Words in a Sentence
1465Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
1471The k Strongest Values in an Array
1481Least Number of Unique Integers after K Removals
1498Number of Subsequences That Satisfy the Given Sum Condition
1500Design a File Sharing SystemPremium
1508Range Sum of Sorted Subarray Sums
1509Minimum Difference Between Largest and Smallest Value in Three Moves
1552Magnetic Force Between Two Balls
1561Maximum Number of Coins You Can Get
1564Put Boxes Into the Warehouse IPremium
1580Put Boxes Into the Warehouse IIPremium
1589Maximum Sum Obtained of Any Permutation
1604Alert Using Same Key-Card Three or More Times in a One Hour Period
1626Best Team With No Conflicts
1630Arithmetic Subarrays
1647Minimum Deletions to Make Character Frequencies Unique
1648Sell Diminishing-Valued Colored Balls
1686Stone Game VI
1727Largest Submatrix With Rearrangements
1738Find Kth Largest XOR Coordinate Value
1772Sort Features by PopularityPremium
1798Maximum Number of Consecutive Values You Can Make
1818Minimum Absolute Sum Difference
1833Maximum Ice Cream Bars
1834Single-Threaded CPU
1838Frequency of the Most Frequent Element
1846Maximum Element After Decreasing and Rearranging
1874Minimize Product Sum of Two ArraysPremium
1877Minimize Maximum Pair Sum in Array
1878Get Biggest Three Rhombus Sums in a Grid
1885Count Pairs in Two ArraysPremium
1887Reduction Operations to Make the Array Elements Equal
1921Eliminate Maximum Number of Monsters
1943Describe the Painting
1968Array With Elements Not Equal to Average of Neighbors
1985Find the Kth Largest Integer in the Array
1996The Number of Weak Characters in the Game
2007Find Original Array From Doubled Array
2008Maximum Earnings From Taxi
2015Average Height of Buildings in Each SegmentPremium
2021Brightest Position on StreetPremium
2031Count Subarrays With More Ones Than ZerosPremium
2033Minimum Operations to Make a Uni-Value Grid
2046Sort Linked List Already Sorted Using Absolute ValuesPremium
2054Two Best Non-Overlapping Events
2070Most Beautiful Item for Each Query
2098Subsequence of Size K With the Largest Even SumPremium
2126Destroying Asteroids
2135Count Words Obtained After Adding a Letter
2146K Highest Ranked Items Within a Price Range
2165Smallest Value of the Rearranged Number
2171Removing Minimum Number of Magic Beans
2191Sort the Jumbled Numbers
2195Append K Integers With Minimal Sum
2225Find Players With Zero or One Losses
2250Count Number of Rectangles Containing Each Point
2268Minimum Number of KeypressesPremium
2271Maximum White Tiles Covered by a Carpet
2274Maximum Consecutive Floors Without Special Floors
2279Maximum Bags With Full Capacity of Rocks
2280Minimum Lines to Represent a Line Chart
2285Maximum Total Importance of Roads
2294Partition Array Such That Maximum Difference Is K
2323Find Minimum Time to Finish All Jobs IIPremium
2332The Latest Time to Catch a Bus
2333Minimum Sum of Squared Difference
2342Max Sum of a Pair With Equal Sum of Digits
2343Query Kth Smallest Trimmed Number
2345Finding the Number of Visible MountainsPremium
2406Divide Intervals Into Minimum Number of Groups
2410Maximum Matching of Players With Trainers
2456Most Popular Video Creator
2491Divide Players Into Teams of Equal Skill
2497Maximum Star Sum of a Graph
2501Longest Square Streak in an Array
2512Reward Top K Students
2517Maximum Tastiness of Candy Basket
2545Sort the Students by Their Kth Score
2548Maximum Price to Fill a BagPremium
2554Maximum Number of Integers to Choose From a Range I
2557Maximum Number of Integers to Choose From a Range IIPremium
2563Count the Number of Fair Pairs
2567Minimum Score by Changing Two Elements
2576Find the Maximum Number of Marked Indices
2580Count Ways to Group Overlapping Ranges
2583Kth Largest Sum in a Binary Tree
2587Rearrange Array to Maximize Prefix Score
2590Design a Todo ListPremium
2592Maximize Greatness of an Array
2593Find Score of an Array After Marking All Elements
2597The Number of Beautiful Subsets
2602Minimum Operations to Make All Array Elements Equal
2607Make K-Subarray Sums Equal
2611Mice and Cheese
2616Minimize the Maximum Difference of Pairs
2638Count the Number of K-Free SubsetsPremium
2655Find Maximal Uncovered RangesPremium
2679Sum in a Matrix
2708Maximum Strength of a Group
2731Movement of Robots
2740Find the Value of the Partition
2747Count Zero Request Servers
2766Relocate Marbles
2779Maximum Beauty of an Array After Applying Operation
2780Minimum Index of a Valid Split
2785Sort Vowels in a String
2830Maximize the Profit as the Salesman
2838Maximum Coins Heroes Can CollectPremium
2840Check if Strings Can be Made Equal With Operations II
2860Happy Students
2863Maximum Length of Semi-Decreasing SubarraysPremium
2895Minimum Processing Time
2933High-Access Employees
2943Maximize Area of Square Hole in Grid
2948Make Lexicographically Smallest Array by Swapping Elements
2952Minimum Number of Coins to be Added
2966Divide Array Into Arrays With Max Difference
2967Minimum Cost to Make Array Equalindromic
2971Find Polygon With the Largest Perimeter

Hard (94)

Hard problems
No.Problem
0023Merge k Sorted Lists
0218The Skyline Problem
0220Contains Duplicate III
0295Find Median from Data Stream
0315Count of Smaller Numbers After Self
0327Count of Range Sum
0354Russian Doll Envelopes
0472Concatenated Words
0493Reverse Pairs
0502IPO
0630Course Schedule III
0632Smallest Range Covering Elements from K Lists
0710Random Pick with Blacklist
0719Find K-th Smallest Pair Distance
1235Maximum Profit in Job Scheduling
1851Minimum Interval to Include Each Query
0296Best Meeting PointPremium
0358Rearrange String k Distance ApartPremium
0527Word AbbreviationPremium
0588Design In-Memory File SystemPremium
0642Design Search Autocomplete SystemPremium
0726Number of Atoms
0757Set Intersection Size At Least Two
0759Employee Free TimePremium
0768Max Chunks To Make Sorted II
0857Minimum Cost to Hire K Workers
0891Sum of Subsequence Widths
0899Orderly Queue
0975Odd Even Jump
0987Vertical Order Traversal of a Binary Tree
1096Brace Expansion II
1183Maximum Number of OnesPremium
1187Make Array Strictly Increasing
1340Jump Game V
1363Largest Multiple of Three
1383Maximum Performance of a Team
1402Reducing Dishes
1478Allocate Mailboxes
1489Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
1547Minimum Cost to Cut a Stick
1585Check If String Is Transformable With Substring Sort Operations
1610Maximum Number of Visible Points
1632Rank Transform of a Matrix
1649Create Sorted Array through Instructions
1665Minimum Initial Energy to Finish Tasks
1691Maximum Height by Stacking Cuboids
1697Checking Existence of Edge Length Limited Paths
1751Maximum Number of Events That Can Be Attended II
1755Closest Subsequence Sum
1782Count Pairs Of Nodes
1840Maximum Building Height
1847Closest Room
1889Minimum Space Wasted From Packaging
1998GCD Sort of an Array
2071Maximum Number of Tasks You Can Assign
2092Find All People With Secret
2122Recover the Original Array
2136Earliest Possible Day of Full Bloom
2141Maximum Running Time of N Computers
2179Count Good Triplets in an Array
2234Maximum Total Beauty of the Gardens
2242Maximum Score of a Node Sequence
2251Number of Flowers in Full Bloom
2344Minimum Deletions to Make Array Divisible
2371Minimize Maximum Value in a GridPremium
2386Find the K-Sum of an Array
2402Meeting Rooms III
2412Minimum Money Required Before Transactions
2421Number of Good Paths
2426Number of Pairs Satisfying Inequality
2448Minimum Cost to Make Array Equal
2449Minimum Number of Operations to Make Arrays Similar
2454Next Greater Element IV
2459Sort Array by Moving Items to Empty SpacePremium
2463Minimum Total Distance Traveled
2503Maximum Number of Points From Grid Queries
2519Count the Number of K-Big IndicesPremium
2551Put Marbles in Bags
2589Minimum Time to Complete All Tasks
2604Minimum Time to Eat All GrainsPremium
2613Beautiful PairsPremium
2659Make Array Empty
2681Power of Heroes
2713Maximum Strictly Increasing Cells in a Matrix
2736Maximum Sum Queries
2751Robot Collisions
2790Maximum Number of Groups With Increasing Length
2809Minimum Time to Make Array Sum At Most x
2813Maximum Elegance of a K-Length Subsequence
2818Apply Operations to Maximize Score
2819Minimum Relative Loss After Buying ChocolatesPremium
2931Maximum Spending After Buying Items
2968Apply Operations to Maximize Frequency Score
2973Find Number of Coins to Place in Tree Nodes

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.