Search⌘ K
AI Features

Solution: Sort Colors

Explore how to implement the Dutch National Flag algorithm to sort an array of colors represented by 0, 1, and 2 efficiently. Understand how to use three pointers—low, mid, and high—to partition the array in one pass without extra space. This lesson helps you write a constant space, linear time solution by carefully swapping elements to their correct positions while traversing the array.

Statement

You are given an array nums of length n, where each element represents an object colored either red, white, or blue. The integers 0, 1, and 2 are used to represent red, white, and blue, respectively.

Sort the array in place so that all objects of the same color are grouped together, arranged in the order: red (0), white (1), and blue (2).

You must solve this problem without using any library sort function.

Note: Could you come up with a one ...