Question presented to candidate: "You are given a list that contains only 0s, 1s and 2s. Sort it in place, ideally in a single pass and without calling a sort function. Please write it in Python."
What a strong answer should cover:
- Counting sort (two passes, three counters) as the simple O(n) answer, then the one-pass Dutch national flag with
low,mid,high. - The invariant (0s, 1s, unknown, 2s) and why
middoes not advance after swapping withhigh. - O(n) time, O(1) extra space, exactly n loop iterations; versus O(n log n) for
list.sort(). - Edge cases: empty list, all one value, already sorted, reverse sorted.
- Python specifics: a
while mid <= highloop (aforloop cannot holdmidstill), the tuple swap, and thatnums[:] = [0] * c0 + [1] * c1 + [2] * c2is in place for the caller but builds a temporary list.
Clarifying questions expected:
- "Are 0, 1 and 2 the only values, and is a library sort allowed?"
- "Does it have to be a single pass?"
Code / implementation expected: Yes โ sort_colors(nums) in Python with three indices, mutating the list in place.