Sorting Coding Problems: 274 Questions with Solutions
274 sorting coding problems — 67 easy · 155 medium · 52 hard — with solutions in 13 languages. Plus a step-by-step walkthrough and a 8-day plan.
- Problems: 274
- By difficulty: 67 easy · 155 medium · 52 hard
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
- Cost: Free on every plan; sign in to run and submit
Sorting is often the first step that makes a problem tractable — once the input is in order, duplicates sit together, the closest pair sits adjacent, intervals can be merged in one pass, and a two-pointer walk replaces a nested loop. These problems practise choosing a sort key, sorting by several keys, using a custom comparator, and knowing when a counting sort or a partial sort beats the general O(n log n).
New to sorting? Read the Sorting Algorithms tutorial first.
How sorting works, step by step
nums = [19, 4, 27, 11, 8, 33]- The smallest difference between two of these 6 numbers could hide in any of the 15 pairs, and checking every pair is O(n²). Sorting first changes that.
- Sorted, in O(n log n). Now each number's closest partner is right next to it: anything further along is past that neighbour, so it is at least as far away. Only 5 neighbouring pairs are left to check.
- 4 and 8 are the first neighbours: 8 − 4 = 4, the best so far. The gap is written under the space between them.
- 8 and 11 differ by 3, smaller than 4, so the best becomes 3.
- 11 and 19 differ by 8, not below the best 3, which stays. Any pair further apart spans two or more of these gaps, so the smallest gap is the answer.
- 19 and 27 differ by 8, not below the best 3, which stays.
- 27 and 33 differ by 6, not below the best 3, which stays.
- The smallest difference is 3, between 8 and 11. Sorting cost O(n log n) and the scan 5 comparisons, so O(n log n) in all, against 15 checks unsorted.
Sorting study plan
14 of the 274 Sorting problems (4 easy, 7 medium and 3 hard) over 8 days, about 8 h 10 min in all — the pattern first, then easiest to hardest. After that, the other 260 in the full list below are practice at your own pace. Then move on to Counting Sort.
Day 1
Learn the pattern: read the essentials and step through the walkthrough above, then solve these 3.
Day 2
Medium problems: the same pattern with one twist each. Name the twist before you code.
Day 3
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Car Pooling Medium
- Sort Colors Medium
Day 4
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Merge Intervals Medium
- Non-overlapping Intervals Medium
Day 5
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
Day 6
Hard problems: the pattern combined with a second idea. Give each a full attempt before reading the editorial.
Day 7
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Day 8
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Sorting: the essentials
When to reach for it
The answer would not change if the input were shuffled — the question is about a collection of values, not their positions — and the brute force compares every pair. "Closest", "minimum difference", "assign each … to a …", "merge the overlapping" and "largest arrangement" all point at sorting first. If the output needs original positions, sort indices or (value, index) pairs instead of the values.
The pattern
Sort once, then scan. A custom comparator must define a consistent order: negative, zero or positive, never a bare boolean, with ties broken explicitly when the output must be deterministic. When a key is costly to compute, compute it once per element rather than inside every comparison.
from functools import cmp_to_key
def largest_number(nums): # a before b when a+b > b+a
s = [str(n) for n in nums]
s.sort(key=cmp_to_key(lambda a, b: (b + a > a + b) - (b + a < a + b)))
out = "".join(s)
return "0" if out[0] == "0" else out
Cost
Comparison sorts take O(n log n), and no comparison sort can do better in the worst case. Library sorts in Python, Java (for objects) and JavaScript are stable; C++'s std::sort is not, so use std::stable_sort when equal keys must keep their order.
Common mistakes
- A comparator written as
a - boverflows on largeintvalues in Java or C++; useInteger.compare(a, b). - JavaScript's default
sort()compares as strings, so[10, 9, 1]sorts to[1, 10, 9]; pass(a, b) => a - b. - An inconsistent comparator such as JavaScript's
(a, b) => a > b, which never returns a negative and gives an engine-dependent order. - Sorting the input in place when a later step needs the original order.
Start with
- Contains Duplicate: equal values end up adjacent.
- Merge Intervals: sort by start, then one sweep.
- Largest Number: a custom comparator decides everything.
All sorting problems
Easy (67)
- Sort a Linked List of 0s, 1s and 2s Linked List, Counting
- Smallest Missing Integer Greater Than Sequential Prefix Sum Array, Hash Table
- Merge Similar Items Array, Hash Table, Ordered Set
- Make Array Zero by Subtracting Equal Amounts Array, Hash Table, Greedy
- Maximize Sum Of Array After K Negations Array, Greedy
- Find Resultant Array After Removing Anagrams Array, Hash Table, String
- Keep Multiplying Found Values by Two Array, Hash Table, Simulation
- Count Elements With Strictly Smaller and Greater Elements Array, Counting
- Minimum Cost of Buying Candies With Discount Array, Greedy
- Finding 3-Digit Even Numbers Array, Hash Table, Enumeration
- Find Target Indices After Sorting Array Array, Binary Search
- Check if Array Is Sorted and Rotated Array
- Make Two Arrays Equal by Reversing Subarrays Array, Hash Table
- Largest Number At Least Twice of Others Array
- Type of Triangle Array, Math
- Delete Greatest Value in Each Row Array, Matrix, Simulation
- Apple Redistribution into Boxes Array, Greedy
- Check if Array is Good Array, Hash Table
- Neither Minimum nor Maximum Array
- Pair With Given Difference Array, Two Pointers
- Two Sum Less Than K Array, Two Pointers
- Split With Minimum Sum Math, Greedy
- Number of Distinct Averages Array, Hash Table, Two Pointers
- Largest Unique Number Hash Table, Array
- Minimum Number Game Array, Simulation
- Sort the People Array, Hash Table
- Wave Array Array
- Rank Transform of an Array Array, Hash Table
- Minimum Sum of Four Digit Number After Splitting Digits Math, Greedy
- Chocolate Distribution Problem Array, Sliding Window
- Minimum Subsequence in Non-Increasing Order Array, Greedy
- Find the Difference Hash Table, String, Bit Manipulation
- Sort Even and Odd Indices Independently Array
- Sort Integers by The Number of 1 Bits Array, Bit Manipulation, Counting
- Maximum Product of Three Numbers Array, Math
- Minimum Absolute Difference Array
- Sort Array by Increasing Frequency Array, Hash Table
- Largest Perimeter Triangle Array, Math, Greedy
- Sort Array By Parity II Array, Two Pointers
- Maximum Units on a Truck Array, Greedy
- Assign Cookies Array, Two Pointers, Greedy
- Matrix Cells in Distance Order Array, Math, Matrix
- The K Weakest Rows in a Matrix Array, Binary Search, Heap
- Count Pairs Whose Sum is Less than Target Array, Two Pointers, Binary Search
- Minimum Number of Moves to Seat Everyone Array, Greedy, Counting Sort
- Maximum Product Difference Between Two Pairs Array, Greedy
- Special Array With X Elements Greater Than or Equal X Array, Binary Search, Counting Sort
- Maximum Product of Two Elements in an Array Array, Heap
- Array Partition Array, Greedy, Counting Sort
- Minimum Difference Between Highest and Lowest of K Scores Array, Sliding Window
- Check If N and Its Double Exist Array, Hash Table, Two Pointers
- Can Make Arithmetic Progression From Sequence Array
- Sorting the Sentence String
- Relative Sort Array Array, Hash Table, Counting Sort
- Height Checker Array, Counting Sort
- Sort Array By Parity Array, Two Pointers
- Longest Harmonious Subsequence Array, Hash Table, Sliding Window
- Third Maximum Number Array
- Set Mismatch Array, Hash Table, Bit Manipulation
- Intersection of Two Arrays II Array, Hash Table, Two Pointers
- Intersection of Two Arrays Array, Hash Table, Two Pointers
- Meeting Rooms Array, Intervals
- Relative Ranks Array, Heap
- Squares of a Sorted Array Array, Two Pointers
- Merge Sorted Array Array, Two Pointers
- Contains Duplicate Array, Hash Table
- Valid Anagram Hash Table, String, Counting
Medium (155)
- Tweet Counts Per Frequency Hash Table, Binary Search, Ordered Set
- Merge Two Sorted Linked Lists in Reverse Order Linked List, Two Pointers
- Union of Two Linked Lists Linked List, Hash Table
- Sort List Linked List, Merge Sort, Divide and Conquer
- Insertion Sort List Linked List
- K-th Largest Perfect Subtree Size in Binary Tree Tree, Depth-First Search
- Kth Largest Sum in a Binary Tree Tree, Breadth-First Search, Heap (Priority Queue)
- Minimum Number of Operations to Sort a Binary Tree by Level Tree, Breadth-First Search
- All Elements in Two Binary Search Trees Tree, Depth-First Search
- Count Covered Buildings Array, Hash Table
- Rearrange K Substrings to Form Target String Hash Table, String
- Count Almost Equal Pairs I Array, Hash Table, Counting
- Check if Strings Can be Made Equal With Operations II Hash Table, String
- Minimum Index of a Valid Split Array, Hash Table
- Relocate Marbles Array, Hash Table, Simulation
- Max Sum of a Pair With Equal Sum of Digits Array, Hash Table, Heap (Priority Queue)
- Invalid Transactions Array, Hash Table, String
- Longest Uncommon Subsequence II Array, Hash Table, Two Pointers
- Minimize Maximum Component Cost Binary Search, Union Find, Graph
- Minimum Time for K Connected Components Binary Search, Union Find, Graph
- K Highest Ranked Items Within a Price Range Array, Breadth-First Search, Heap (Priority Queue)
- Maximum Total Damage With Spell Casting Array, Hash Table, Two Pointers
- Best Team With No Conflicts Array, Dynamic Programming
- Permutations II Array, Backtracking
- Largest Submatrix With Rearrangements Array, Greedy, Matrix
- Get Biggest Three Rhombus Sums in a Grid Array, Matrix, Prefix Sum
- Diagonal Traverse II Array, Matrix
- Maximize the Profit as the Salesman Array, Dynamic Programming, Binary Search
- Maximum Earnings From Taxi Array, Hash Table, Dynamic Programming
- Stone Game VI Array, Greedy, Game Theory
- Binary Trees With Factors Array, Hash Table, Dynamic Programming
- Minimize Maximum Pair Sum in Array Array, Two Pointers, Greedy
- Maximum Strength of a Group Array, Greedy, Enumeration
- Minimum Cost to Make Array Equalindromic Array, Math, Greedy
- Maximum Matching of Players With Trainers Array, Two Pointers, Greedy
- Maximum Element After Decreasing and Rearranging Array, Greedy
- Minimum Number of Coins to be Added Array, Greedy
- Two Best Non-Overlapping Events Array, Binary Search, Dynamic Programming
- Divide Intervals Into Minimum Number of Groups Array, Greedy, Heap (Priority Queue)
- Describe the Painting Array, Hash Table, Prefix Sum
- Range Sum of Sorted Subarray Sums Array, Two Pointers, Binary Search
- Choose K Elements With Maximum Sum Array, Heap (Priority Queue)
- Reward Top K Students Hash Table, String, Heap (Priority Queue)
- Mark Elements on Array by Performing Queries Array, Hash Table, Heap (Priority Queue)
- Minimum Sum of Squared Difference Array, Binary Search, Greedy
- Minimum Operations to Make All Array Elements Equal Array, Binary Search, Prefix Sum
- Minimum Absolute Sum Difference Array, Binary Search, Ordered Set
- Count Number of Rectangles Containing Each Point Array, Hash Table, Binary Search
- Maximum Tastiness of Candy Basket Array, Binary Search, Greedy
- Sum of Mutated Array Closest to Target Array, Binary Search
- Heaters Array, Binary Search, Two Pointers
- Maximum White Tiles Covered by a Carpet Array, Sliding Window, Prefix Sum
- Count the Number of Fair Pairs Array, Two Pointers, Binary Search
- Maximum Sum Obtained of Any Permutation Array, Greedy, Prefix Sum
- Maximum Number of Consecutive Values You Can Make Array, Greedy
- Smallest Range II Array, Math, Greedy
- Rearrange Words in a Sentence String
- Reorder Data in Log Files Array, String
- Find And Replace in String Array, Hash Table, String
- Minimum Time Difference Array, Math, String
- Groups of Special-Equivalent Strings Array, Hash Table, String
- Find Score of an Array After Marking All Elements Array, Hash Table, Heap (Priority Queue)
- Maximize Greatness of an Array Array, Two Pointers, Greedy
- Rearrange Array to Maximize Prefix Score Array, Greedy, Prefix Sum
- Divide Players Into Teams of Equal Skill Array, Hash Table, Two Pointers
- Minimum Lines to Represent a Line Chart Array, Math, Geometry
- Maximum Bags With Full Capacity of Rocks Array, Greedy
- Minimum Operations to Make a Uni-Value Grid Array, Math, Matrix
- Reduction Operations to Make the Array Elements Equal Array
- Array of Doubled Pairs Array, Hash Table, Greedy
- Minimum Increment to Make Array Unique Array, Greedy, Counting
- Friends Of Appropriate Ages Array, Counting
- Longest Subsequence With Limited Sum Array, Binary Search, Greedy
- Count Ways to Group Overlapping Ranges Array, Math
- Sort Vowels in a String String
- Find the Integer Added to Array II Array, Two Pointers, Enumeration
- Count Days Without Meetings Array
- Find the Value of the Partition Array
- K-th Smallest Prime Fraction Array, Binary Search, Heap (Priority Queue)
- Maximum Subsequence Score Array, Greedy, Heap (Priority Queue)
- Single-Threaded CPU Array, Heap (Priority Queue)
- Most Beautiful Item for Each Query Array, Binary Search
- Maximum Number of Events That Can Be Attended Array, Greedy, Heap (Priority Queue)
- Find the Kth Largest Integer in the Array Array, String, Heap (Priority Queue)
- Maximum Star Sum of a Graph Array, Graph, Greedy
- Minimum Operations to Make Median of Array Equal to K Array, Greedy
- Find the Maximum Number of Marked Indices Array, Two Pointers, Greedy
- Maximum Consecutive Floors Without Special Floors Array, Greedy
- Eliminate Maximum Number of Monsters Array, Greedy
- Minimum Number of Arrows to Burst Balloons Array, Greedy, Intervals
- Successful Pairs of Spells and Potions Array, Binary Search, Two Pointers
- Find Right Interval Array, Binary Search
- Minimize the Maximum Difference of Pairs Array, Binary Search, Greedy
- Magnetic Force Between Two Balls Array, Binary Search, Greedy
- Maximum Beauty of an Array After Applying Operation Array, Sliding Window, Binary Search
- Frequency of the Most Frequent Element Array, Sliding Window, Greedy
- Number of Subsequences That Satisfy the Given Sum Condition Array, Two Pointers, Binary Search
- The k Strongest Values in an Array Array, Two Pointers
- Most Profit Assigning Work Array, Two Pointers, Greedy
- Partition Array Such That Maximum Difference Is K Array, Greedy, Two Pointers
- Sort Transformed Array Array, Two Pointers, Math
- Bag of Tokens Array, Two Pointers, Greedy
- Max Number of K-Sum Pairs Array, Two Pointers, Hash Table
- 4Sum Array, Two Pointers
- Find Players With Zero or One Losses Hash Table, Array, Counting
- Determine if Two Strings Are Close Hash Table, String, Counting
- Smallest String With Swaps Union Find, Hash Table, String
- Check If a String Can Break Another String String, Greedy
- Longest Word in Dictionary Through Deleting String, Two Pointers
- Count Triplets With Sum Smaller Than X Array, Two Pointers
- Kth Smallest Element Array, Quickselect
- Minimum Swaps to Sort Array, Graph
- Divide Array Into Arrays With Max Difference Array, Greedy
- Smallest Value of the Rearranged Number Math
- Find Original Array From Doubled Array Array, Greedy, Hash Table
- Minimum Moves to Equal Array Elements II Array, Math
- Maximum Total Importance of Roads Graph, Greedy, Heap
- The Earliest Moment When Everyone Become Friends Array, Union Find
- Sort Integers by The Power Value Dynamic Programming, Memoization
- The Number of Weak Characters in the Game Array, Greedy, Stack
- Max Chunks To Make Sorted Array, Stack, Greedy
- Reveal Cards In Increasing Order Array, Queue, Simulation
- Minimum Number of Platforms Array, Greedy, Two Pointers
- Find K Closest Elements Array, Two Pointers, Binary Search
- Kth Smallest Element in a Sorted Matrix Array, Binary Search, Heap
- Top K Frequent Words Array, Hash Table, String
- K Closest Points to Origin Array, Math, Divide and Conquer
- Valid Triangle Number Array, Two Pointers, Binary Search
- Maximum Number of Coins You Can Get Array, Math, Greedy
- Largest Number Array, String, Greedy
- Maximum Ice Cream Bars Array, Greedy, Counting Sort
- Remove Covered Intervals Array, Greedy
- Minimum Deletions to Make Character Frequencies Unique String, Hash Table, Greedy
- Reduce Array Size to The Half Array, Hash Table, Greedy
- Queue Reconstruction by Height Array, Greedy, Binary Indexed Tree
- Two City Scheduling Array, Greedy
- Maximum Length of Pair Chain Array, Dynamic Programming, Greedy
- Sort the Matrix Diagonally Array, Matrix
- Custom Sort String Hash Table, String
- Majority Element II Array, Hash Table, Counting
- H-Index Array, Counting Sort
- Shortest Unsorted Continuous Subarray Array, Two Pointers, Monotonic Stack
- 3Sum Closest Array, Two Pointers
- 3Sum Array, Two Pointers
- Car Pooling Array, Prefix Sum, Intervals
- Minimum Number of Arrows to Burst Balloons Array, Greedy, Intervals
- Meeting Rooms II Array, Heap, Intervals
- Non-overlapping Intervals Array, Greedy, Intervals
- Merge Intervals Array, Intervals
- Sort an Array Array, Heap, Divide and Conquer
- Kth Largest Element in an Array Array, Heap, Quickselect
- Boats to Save People Array, Greedy, Two Pointers
- Hand of Straights Array, Greedy, Hash Table
- Car Fleet Array, Stack, Monotonic Stack
- Sort Colors Array, Two Pointers
Hard (52)
- Vertical Order Traversal of a Binary Tree Tree, Depth-First Search, Breadth-First Search
- GCD Sort of an Array Array, Math, Union Find
- Rank Transform of a Matrix Array, Union Find, Graph
- Maximum Score of a Node Sequence Array, Graph, Enumeration
- Find the Sum of Subsequence Powers Array, Dynamic Programming
- Maximize Consecutive Elements in an Array After Modification Array, Dynamic Programming
- Maximum Strictly Increasing Cells in a Matrix Array, Hash Table, Binary Search
- Minimum Total Distance Traveled Array, Dynamic Programming
- Closest Subsequence Sum Array, Two Pointers, Bitmask
- Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree Graph, Union Find, Minimum Spanning Tree
- Jump Game V Array, Dynamic Programming
- Maximum Profit in Job Scheduling Array, Binary Search, Dynamic Programming
- Rearranging Fruits Array, Hash Table, Greedy
- Minimum Number of Operations to Make Arrays Similar Array, Greedy
- Minimum Initial Energy to Finish Tasks Array, Greedy
- Orderly Queue Math, String
- Minimum Deletions to Make Array Divisible Array, Math, Number Theory
- Set Intersection Size At Least Two Array, Greedy
- Minimum Amount of Damage Dealt to Bob Array, Greedy
- Maximum Spending After Buying Items Array, Greedy, Heap (Priority Queue)
- Earliest Possible Day of Full Bloom Array, Greedy
- Course Schedule III Array, Greedy, Heap (Priority Queue)
- Minimum Interval to Include Each Query Array, Binary Search, Heap (Priority Queue)
- Number of Atoms Hash Table, String, Stack
- Robot Collisions Array, Stack, Simulation
- Next Greater Element IV Array, Stack, Monotonic Stack
- Maximum Sum Queries Array, Binary Search, Monotonic Stack
- Minimum Cost to Make Array Equal Array, Binary Search, Greedy
- Number of Flowers in Full Bloom Array, Binary Search, Prefix Sum
- Apply Operations to Maximize Frequency Score Array, Sliding Window, Prefix Sum
- Maximum XOR With an Element From Array Array, Bit Manipulation, Trie
- Rectangle Area II Array, Math, Geometry
- Make Array Strictly Increasing Array, Binary Search, Dynamic Programming
- Maximum Number of Events That Can Be Attended II Array, Binary Search, Dynamic Programming
- Allocate Mailboxes Array, Math, Dynamic Programming
- Maximum Height by Stacking Cuboids Array, Dynamic Programming
- Apply Operations to Maximize Score Array, Math, Stack
- Meeting Rooms III Array, Simulation, Heap (Priority Queue)
- Smallest Range Covering Elements from K Lists Array, Hash Table, Greedy
- Maximum Performance of a Team Array, Greedy, Heap (Priority Queue)
- Put Marbles in Bags Array, Greedy, Heap (Priority Queue)
- Checking Existence of Edge Length Limited Paths Array, Union Find, Graph
- Find All People With Secret Graph, Union Find, Depth-First Search
- Number of Good Paths Array, Tree, Graph
- Minimum Cost to Cut a Stick Array, Dynamic Programming
- Maximum Number of Groups With Increasing Length Array, Greedy, Binary Search
- Minimum Time to Complete All Tasks Array, Greedy
- IPO Array, Greedy, Heap
- Maximum Number of Tasks You Can Assign Array, Binary Search, Greedy
- Russian Doll Envelopes Array, Binary Search, Dynamic Programming
- Maximum Running Time of N Computers Array, Binary Search, Greedy
- Find K-th Smallest Pair Distance Array, Two Pointers, Binary Search
Companies that ask sorting problems
- Amazon 243 problems on sorting
- Google 182 problems on sorting
- Microsoft 42 problems on sorting
- Adobe 35 problems on sorting
- Meta 24 problems on sorting
- Bloomberg 14 problems on sorting
- TCS 11 problems on sorting
- Uber 10 problems on sorting
- Flipkart 9 problems on sorting
- Infosys 7 problems on sorting
- PhonePe 6 problems on sorting
- Atlassian 5 problems on sorting
Next topic: Counting Sort