Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Sort Colors

Sortingmedium

Course · Section 11: Working With Arrays · Lecture 172: Sorting Arrays

Given `arr` containing only `0`, `1`, and `2`, implement `sortColors(arr)` to sort it ascending in one pass (Dutch national flag). Return the array.

Sample tests

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

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Advancing the mid pointer after swapping from the high side can skip an unprocessed value.

Learning resources

  • MDN: Array.prototype.sort
Approach & explanation (try first)

The Dutch national flag scan sorts three values in a single O(n) pass, O(1) space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.