Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Sort colors in one pass

Sort an array containing 0s, 1s, and 2s in a single pass using constant extra space.

Python practice22 minSearching & SortingAdvancedLast updated March 25, 2026

Problem statement

Given an array nums with n objects colored red, white, or blue (represented by 0, 1, and 2), sort them in-place so that objects of the same color are adjacent, with the colors in the order 0, 1, and 2. You must solve this in one pass with constant extra space. Return the array after sorting.

Task

Use the Dutch National Flag algorithm to sort an array of 0s, 1s, and 2s in one pass (O(n) time, O(1) space).

Examples

Typical example

Input

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

Output

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

A single-pass in-place algorithm groups 0s, then 1s, then 2s.

Input format

A Python list nums consisting only of integers 0, 1, and 2.

Output format

The input list nums after in-place sorting (returned as a list).

Constraints

1 <= n <= 10^5 typically. Only values 0, 1, and 2 appear. Use O(n) time and O(1) extra space.

Samples

Sample 1

Input

nums = [2, 0, 1]

Output

[0, 1, 2]

Sorted in-place to [0,1,2].