Sort Colors

Medium

Topics
ArrayTwo PointersSorting

Given an array nums with n objects colored red, white, or blue (0, 1, 2), sort them in-place so objects of the same color are adjacent, in the order 0, 1, 2. Return the sorted array. Use the one-pass Dutch National Flag algorithm.

Example 1

before202110
after001122
012
The array holds nothing but 0, 1 and 2, standing for three colours, and they must end up grouped in that order. The rearranging has to happen inside the given array rather than in a new one.
Top row is the input, bottom row the sorted result.
Input:  nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2

before201
after012
012
Input:  nums = [2,0,1]
Output: [0,1,2]

Constraints

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is 0, 1, or 2.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Three distinct values and one pass is the Dutch national flag partition. Maintain three regions with two boundaries: everything below lo is a 0, everything above hi is a 2, and the span between lo and mid is all 1s. The unexamined region is between mid and hi.

The asymmetry is the whole trick. A 0 is swapped in from a region already known to hold 1s, so the incoming value is a 1 and mid can advance safely. A 2 is swapped in from the unexamined region, so the incoming value is unknown and mid must stay put to inspect it.

Approach

  1. Set lo = mid = 0 and hi = len(nums) - 1.
  2. While mid <= hi, look at nums[mid].
  3. On 0, swap with lo and advance both lo and mid.
  4. On 1, advance mid only.
  5. On 2, swap with hi, decrement hi, and leave mid alone.

Dry Run

nums = [2,0,2,1,1,0]

  lo mid hi  array after         action
  0  0   5   [2,0,2,1,1,0]       start
  0  0   4   [0,0,2,1,1,2]       2 -> swap to the high end, mid does NOT advance
  1  1   4   [0,0,2,1,1,2]       0 -> swap to the low end, both advance
  2  2   4   [0,0,2,1,1,2]       0 -> swap to the low end, both advance
  2  2   3   [0,0,1,1,2,2]       2 -> swap to the high end, mid does NOT advance
  2  3   3   [0,0,1,1,2,2]       1 -> in place, advance mid
  2  4   3   [0,0,1,1,2,2]       1 -> in place, mid passes hi, loop ends

answer [0,0,1,1,2,2]

Complexity

  • Time — O(n): every iteration either advances mid or decreases hi, and they meet after at most n steps. Strictly one pass.
  • Space — O(1): three indices, swapping in place.

Common Pitfalls

  • Advancing mid after swapping a 2. The value swapped in came from the unexamined region and has not been looked at; advancing skips it, and a 0 landing there is lost.
  • Using mid < hi instead of mid <= hi, which leaves the final unexamined cell unsorted.
  • Counting the three values and overwriting the array. That is the two-pass counting sort, it is correct and O(n), but the problem asks for one pass.
  • Calling a library sort. It is O(n log n) on an input whose bounded alphabet admits O(n), and it sidesteps the thing being tested.
  • Swapping with lo when lo == mid and treating it as a bug. It is a self-swap, harmless, and avoiding it with a branch costs more than it saves.
  • Generalising to k colours with the same two pointers. Dutch flag handles exactly three regions; more colours need counting sort or a different partition scheme.

Full Solution — all languages

class Solution:
    def sortColors(self, nums):
        lo, mid, hi = 0, 0, len(nums) - 1
        while mid <= hi:
            if nums[mid] == 0:
                nums[lo], nums[mid] = nums[mid], nums[lo]
                lo += 1; mid += 1
            elif nums[mid] == 1:
                mid += 1
            else:
                nums[mid], nums[hi] = nums[hi], nums[mid]
                hi -= 1
        return nums
SensAI
Beta
Tap the mic to stop voice mode