AAlgoLoopSpaced repetition for LeetCode
MEDIUMTwo PointersLeetCode ↗

Sort Colors

The key idea

Treat the array as three growing regions: the 0s on the left, the 2s on the right, and the unsorted middle. One pass with three pointers (low, mid, high) partitions every value into its region in a single sweep, never needing a second pass or a count.

Problem

You are given an array nums of n objects colored red, white, or blue. Sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

The colors are represented by the integers 0, 1, and 2: 0 for red, 1 for white, and 2 for blue.

You must solve this problem without using the library's built-in sort function.

Constraints

Examples

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

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Two Pointers problems