Search⌘ K
AI Features

Sort Colors

Explore how to efficiently sort an array containing red, white, and blue objects represented as 0, 1, and 2. Learn to implement a one-pass, constant space algorithm using the two pointers technique to solve this common interview problem in JavaScript.

Statement

You are given an array nums of length n, where each element represents an object colored either red, white, or blue. The integers 01, 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:

  • nn ==== colors.length

  • 11 \leq nn 300\leq 300

  • colors[i] is either 0, 1, or 2

Examples

canvasAnimation-image
1 / 5

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

1.

Given the input nums = [0], what will the array look like after sorting?

A.

[1][1]

B.

[0,0][0, 0]

C.

[0][0]

D.

[0,1,2][0, 1, 2]


1 / 5

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.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

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.

JavaScript
usercode > Solution.js
function sortColors(colors){
// Replace this placeholder return statement with your code
return colors;
}
export { sortColors }
Sort Colors