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 pass algorithm using only constant extra space?
Constraints:
colors.lengthcolors[i]is either 0, 1, or 2
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Sort Colors
Given the input nums = [0], what will the array look like after sorting?
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground:
Need a nudge?
Explore these hints—each one is designed to guide you a step closer to the solution.
function sortColors(colors){// Replace this placeholder return statement with your codereturn colors;}export { sortColors }