Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Sort Colors (Dutch National Flag)

Sortingmedium

An array contains only the integers `0`, `1`, and `2`. Implement `sortColors(nums)` that sorts it in a single pass and returns the sorted array. (This is the Dutch national flag problem.)

Examples

Input: [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Input: [1, 0]
Output: [0, 1]

Sample tests

Input: sortColors([2,0,2,1,1,0])
Output: [0,0,1,1,2,2]
Input: sortColors([1,0])
Output: [0,1]

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Incrementing `mid` after swapping with `high` skips an unexamined element.

Learning resources

  • Wikipedia: Array data structure
Approach & explanation (try first)

Three pointers partition the array into 0s, 1s, and 2s in one pass. A 0 is swapped to the low region, a 2 is swapped to the high region, and a 1 stays in place. O(n) time, O(1) space — faster than a comparison sort because the value range is fixed.

Loading...
⌘/Ctrl + Enter

Run your code to see results.