Asked at

Sort Colors

Medium
Verified
Two PointersSortingArray~20 min

Given an array nums of 0s, 1s, and 2s, sort it so the colors group in order.

The Dutch-national-flag scan keeps three pointers — low, mid, high — and swaps in one pass.

The input arrives as a single array nums. Return the sorted array.

Examples

in[2, 0, 2, 1, 1, 0]
out[0, 0, 1, 1, 2, 2]

All 0s, then 1s, then 2s.

in[2, 0, 1]
out[0, 1, 2]

Three colors sorted in place.

Constraints

  • 1 ≤ nums.length ≤ 300
  • nums[i] is 0, 1, or 2.
  • Target: one pass, constant extra space

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.