Search⌘ K
AI Features

Sort Colors

Understand how to apply the two pointers technique to sort an array containing red, white, and blue objects in a single pass. Learn to implement an in-place algorithm without extra space or library sorts, developing a clear approach for similar coding interview challenges.

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.

Java
usercode > Solution.java
import java.util.*;
public class Solution {
public static int[] sortColors (int[] colors) {
// Write your code here
return colors;
}
}
Sort Colors