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 pass algorithm using only constant extra space?
Constraints:
colors.length
colors[i] is either 0, 1, or 2
The key intuition behind this problem is to use the Dutch National Flag algorithm, which partitions the array into three sections in a single pass using three pointers. We maintain a low pointer that tracks where the next high pointer that tracks where the next mid pointer that scans through the array. As mid advances, every element it encounters is either swapped to the front (if it is
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 pass algorithm using only constant extra space?
Constraints:
colors.length
colors[i] is either 0, 1, or 2
The key intuition behind this problem is to use the Dutch National Flag algorithm, which partitions the array into three sections in a single pass using three pointers. We maintain a low pointer that tracks where the next high pointer that tracks where the next mid pointer that scans through the array. As mid advances, every element it encounters is either swapped to the front (if it is