Software interviews
Sorting for coding interviews: which sort and practice problems
Most sorting problems do not ask you to write a sort. They ask you to decide whether sorting helps, say what it costs, and sometimes define the order it should use. This page gives the cost from the Python documentation, a table of how fast the counts grow, three patterns with worked examples, the edge cases that get tested and four original problems with answers a separate program recomputes.
Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.
Book your first hour ($250)Which sort to use and what it costs
Use the sort that comes with your language, and say what it costs. The Python documentation page on the time complexity of built-in types lists sorting a list as O(n log n), and adds that this is the worst case: sorting is adaptive, so input that is already sorted or reverse-sorted takes only O(n) comparisons. One sentence in an interview covers it: "I will sort first, which costs O(n log n), and then one pass."
The MIT OpenCourseWare course 6.006 Introduction to Algorithms gives sorting its own lecture, with a separate lecture on linear sorting, and a lecture on binary heaps, a structure that heap sort is built on. The course describes itself as introducing algorithmic paradigms and data structures along with performance measures and analysis techniques. The reasoning below about how the counts grow is our own, not a figure taken from the course.
Why O(n log n) and not O(n^2)? A simple method that compares every pair, or that moves each item one slot at a time, can make about n(n - 1) / 2 comparisons, which grows with the square of n. A divide and conquer method splits the list in half, sorts each half and merges, so there are about log2(n) levels of splitting, each doing about n work. Multiply the levels by the work per level and you have n log n.
| Items n | n log2(n), about | n squared |
|---|---|---|
| 10 | 33 | 100 |
| 100 | 664 | 10,000 |
| 1,000 | 9,966 | 1,000,000 |
| 1,000,000 | 19,931,569 | 1,000,000,000,000 |
At a million items the gap is a factor of about 50,000. This is the number to have in your head when an interviewer asks why you would sort before you loop.
The problem signals that call for sorting
Sorting is rarely the goal. It is a step that puts related items next to each other so that one pass can finish the job.
| Signal in the statement | What it usually means | Technique |
|---|---|---|
| "Merge overlapping ranges" or "fewest rooms" | Neighbors in order interact | Sort by start, then sweep |
| "Closest pair" or "any two within k" | Close values are adjacent after sorting | Sort, then compare neighbors |
| "Smallest k items" or "k-th largest" | You need rank, not the whole order | Sort, or partition without fully sorting |
| "Arrange so that" a custom rule holds | The order is not the natural one | Sort with a key or a comparison you define |
| "Fewest swaps to sort" | Count how far from sorted | Cycles of the permutation |
| "Sorted by one field, ties by another" | Two keys | Sort by a pair, or a stable sort twice |
Pattern 1: choose the order
Many sorting problems are really about defining the order. Sort by a pair when a tie must be broken, and flip the sign of a number to sort that part in descending order. Problem 3 sorts values by how often they occur, with the most frequent first and the smaller value first among equals: count with a dict, then sort the distinct values by the pair (negative count, value).
Some orders cannot be a key, and need a comparison between two items. Problem 2 joins numbers into the largest possible number. Sorting by value gives the wrong answer, because 34 followed by 30 and 3 is smaller than 34 followed by 3 and 30. The right rule compares two numbers as text: put a before b when a followed by b is larger than b followed by a. That rule is consistent, so a sort that uses it works. The lesson is to test your order on a small case before you trust it.
Pattern 2: count the work a sort would do
Some problems ask how many swaps or moves a sort would need, without asking you to sort. For a list holding each of 1 to n once, follow each position to the position where its value belongs. This splits the list into cycles. A cycle of c entries needs c - 1 swaps to fix, so the fewest swaps overall is n minus the number of cycles. Problem 1 is this problem. The idea transfers: when asked about the cost of a sort, look for a structure in the input that gives the count directly.
Pattern 3: partition without sorting everything
Partitioning takes a pivot and rearranges the list so that everything smaller is before it and everything larger is after it. After one pass the pivot is in its final sorted position, and that position equals the number of smaller items. Quick sort repeats this on each side. If you only need the k-th smallest, you can partition and continue on one side only, which is faster than sorting everything. The worst case is a pivot that is always the smallest or largest item: each pass removes only one item, so the passes cost n, then n - 1, and so on, which adds up to about n squared over 2, the same as the simple methods. Problem 4 asks where a pivot lands after one partition.
Edge cases interviewers probe
- An empty list or a list of one item. Say what you return, and that it is already sorted.
- Duplicates. Say whether you need a stable sort and whether equal items are interchangeable.
- Already sorted input. For the built-in sort it takes only O(n) comparisons, per the Python documentation, but a quick sort with a poor pivot choice can be slow on it.
- Sorting in place or into a new list. Say which you do, and what it costs in space.
- Ties in a custom order. State the rule for ties out loud and test one.
- Mixed types or missing values. Ask whether they can appear, and how to order them if so.
A good habit is to test your solution on the smallest tricky input you can write by hand, such as two equal items, before you call it done.
Four practice problems, in order of difficulty
These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from counting swaps through custom orders to a partition.
Problem 1. A list holds each of the numbers 1 to 9 once: 4, 1, 3, 9, 7, 2, 8, 5, 6. One move swaps any two entries, whether or not they are neighbors. What is the fewest moves that put the list in order 1 to 9? Give an integer.
Show the answer and the working
Answer: 6
- Follow each position to where its value belongs. Position 1 holds 4, so the 4 belongs at position 4, which holds 9, which belongs at position 9, which holds 6, then position 6 holds 2, then position 2 holds 1, which returns to position 1. That cycle has 5 entries: 4, 9, 6, 2, 1.
- Position 3 holds 3 and is already in place: a cycle of 1. Position 5 holds 7, position 7 holds 8, position 8 holds 5: a cycle of 3 entries.
- A cycle of c entries needs c - 1 swaps, because each swap puts one entry in its final place and the last swap fixes two. So 4 + 0 + 2 = 6.
- The same count is the number of entries, 9, minus the number of cycles, 3. Finding the cycles takes O(n).
Problem 2. The numbers 3, 30, 34, 5, 9, 91 are written one after another, in some order, with no gaps, to make one long number. What is the largest number that can be made? Give an integer.
Show the answer and the working
Answer: 991534330
- Sorting by the numbers themselves, largest first, does not work. By value the order of 34, 30 and 3 is 34, 30, 3, which joins to 34303, but the order 34, 3, 30 joins to 34330, which is larger.
- Compare two numbers a and b as text: put a first when the text a + b is larger than b + a. This order is consistent, so a sort with this comparison works.
- The order is 9, 91, 5, 34, 3, 30. For example 9 before 91 because 991 is larger than 919, and 3 before 30 because 330 is larger than 303.
- Joined, they give 991534330. The sort costs O(n log n) comparisons, each on a short string.
Problem 3. The list is 4, 6, 2, 6, 4, 4, 9, 2, 6, 7, 2, 6, 9, 1, 4. It is sorted so that values that occur more often come first, and values that occur equally often are ordered with the smaller value first, and each value is written once for each time it occurs. Which value is at position 14, counting from 1? Give an integer.
Show the answer and the working
Answer: 1
- Count each value with a dictionary: 4 occurs 4 times, 6 occurs 4 times, 2 occurs 3 times, 9 occurs 2 times, and 7 and 1 each occur once.
- Sort the distinct values by the pair (count, value) with count in descending order and value in ascending order. The order is 4, 6, 2, 9, 1, 7, because 4 and 6 tie on 4 occurrences and the smaller goes first, and 1 and 7 tie on 1.
- Write each value as many times as it occurs: 4, 4, 4, 4, 6, 6, 6, 6, 2, 2, 2, 9, 9, 1, 7. That is 15 values.
- Position 14 holds 1, and position 15 holds 7. Counting takes O(n) and sorting the distinct values takes O(d log d) for d distinct values.
Problem 4. A partition step takes the last value of 9, 4, 12, 7, 3, 15, 8, 1, 10, 6, 11, 5 as the pivot and rearranges the list so that every value smaller than the pivot comes before it and every larger value comes after it. At which 0-based index does the pivot end up? Give an integer.
Show the answer and the working
Answer: 3
- The pivot is 5. Scan the first 11 values with a pointer i marking where the next smaller value belongs, starting at 0. Each value below 5 is swapped to position i and i moves up by one.
- The values below 5 are 4 (index 1), 3 (index 4) and 1 (index 7), so there are three swaps and i ends at 3. After the swaps the list reads 4, 3, 1, 7, 9, 15, 8, 12, 10, 6, 11, 5.
- The pivot is then swapped into position i, so it lands at index 3, with 4, 3, 1 before it and everything larger after it.
- The index of the pivot is the number of smaller values, which can be counted without moving anything. The partition costs one pass, O(n).
Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read how the problems are checked.
These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.
A longer ladder of sorting problems
Four worked problems are a start, and a longer list is worth having for the weeks before an interview. The table sorts 23 problem types that interviewers often use for sorting into three sets, with what each set trains. A coaching company that publishes a large question list on this topic sorts its own list by the stage where such questions tend to turn up: simpler ones on a phone screen, harder ones on a video call or onsite round, where you may get more time. We keep that idea and describe each type in our own words.
| Set | Types | Problems to look up | What the set trains |
|---|---|---|---|
| Easy | 7 | whether any value repeats; whether two words are anagrams; whether meetings overlap; pairing numbers to maximize the sum of minimums; sorting by parity; the largest triangle perimeter; how many values are smaller than each value | Sorting as a first step that makes the rest a single pass |
| Medium | 9 | sorting an array without a library call; three values that sum to zero; grouping anagrams; merging intervals; sorting values of three colors; the largest number built from digits; the k-th largest value; rebuilding a line of people by height; removing intervals so none overlap | A custom comparison, or a sort by one key and then another |
| Hard | 7 | the largest gap in a sorted order; merging k sorted lists; counting smaller values to the right; counting reverse pairs; stacking nested envelopes; the fewest chunks that sort an array; scheduling for the highest profit | Merge-based counting and sorting with a data structure beside it |
Do not try to read every solution. New questions appear every season, so the aim is to own the pattern behind a set, not the answer to each item. For each problem, set a timer, write your own attempt with no reference, and only then read a solution. When you get stuck, look at one solution, close it and redo the problem from a blank page the next day. A pile of read solutions teaches far less than a few redone from memory.
Know what your language’s sort promises: its cost, whether equal items keep their order and what it needs to compare. State why sorting first is allowed, because it costs n log n and that may be the cost of the whole answer. Many “medium” problems are solved by the sentence “sort, then scan.”
A short routine to practice
- Ask whether sorting helps: do neighbors in order interact?
- Write down the order, including ties, before you write any code.
- State the cost of the sort and of the pass after it.
- Say whether you need the whole order or only a rank, and whether a partition is enough.
- Trace the order on a case with a tie.
Questions
What does sorting cost in Python?
The Python documentation lists a list sort as O(n log n) in the worst case, and says that input that is already sorted or reverse-sorted takes only O(n) comparisons. That makes sorting a cheap first step for many problems.
Which sorting algorithm should I use in an interview?
Use the built-in sort unless the problem is about the algorithm itself, and state its cost. Be ready to explain how a divide and conquer sort works and why a simple pairwise sort costs O(n^2).
What does it mean for a sort to be stable?
A stable sort keeps equal items in the order they had before sorting. It matters when you sort records by one field after sorting them by another.
How a session helps
A session with George is a place to code a problem aloud and have the reasoning questioned: why sorting helps, what the order is and how ties are broken. You write all the code yourself. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to put the topics on a calendar. See the packages page for the sessions, or book a session.
Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.