Given an array nums with 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.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
n == nums.length1 <= n <= 300nums[i] is either 0, 1, or 2.Follow up: Could you come up with a one-pass algorithm using only constant extra space?
The problem can be solved by first counting the number of occurrences of each color (0s, 1s, and 2s). This information can be used to overwrite the original array by placing the colors consecutively as per the number of occurrences. Although this is not done in one-pass, it is straightforward and efficient.
0s, 1s, and 2s in the array.0s, followed by 1s, and then 2s.This approach utilizes the famous Dutch National Flag algorithm which sorts the array using one pass and constant space by maintaining three pointers: low, mid, and high.
low maintains the boundary of zeros.mid iterates over the array.high maintains the boundary of twos.low at the start, mid at the start, and high at the end of the array.mid is less than or equal to high:mid is 0, swap it with the element at low. Increment both low and mid.mid is 1, just increment mid.mid is 2, swap it with the element at high. Decrement high (do not increment mid because the swapped element from high may need further processing).