medium +20 pts

Sort Colors (Dutch National Flag)

Sort an array of 0s, 1s, and 2s in-place with a single pass.

Given a list of integers where each element is either 0, 1, or 2, sort the list in-place in ascending order (0s first, then 1s, then 2s). You must do this with a single pass (O(n) time) and O(1) extra space. Write a function `sort_colors(nums)` that modifies the input list and returns the modified list. The grader will check the return value.

Constraints

1 ≤ len(nums) ≤ 1000; each element is exactly 0, 1, or 2. Expected time O(n), space O(1).

Example

>>> nums = [2,0,2,1,1,0]
>>> sort_colors(nums)
[0,0,1,1,2,2]
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Keep three pointers: low, mid, high.
If nums[mid] is 0, swap it with nums[low] and advance both low and mid.
If nums[mid] is 1, just advance mid.
If nums[mid] is 2, swap it with nums[high] and decrement high (do not advance mid yet).
After the loop, return the modified list.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.