Skip to the solution
MediumDSA8 min read

How do you sort an array of 0s, 1s, and 2s?

826 views

The problem

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 mid does not advance after swapping with high.
  • 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 <= high loop (a for loop cannot hold mid still), the tuple swap, and that nums[:] = [0] * c0 + [1] * c1 + [2] * c2 is 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.

  • arrays
  • sorting
  • dutch-flag

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonDutch national flag, traced step by step
PythonEdge cases, and Dutch flag vs counting sort on 1,000 values

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 62 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the maximum subarray sum?

Continue