...

/

Sort Colors

Sort Colors

Try to solve the Sort Colors problem.

Statement

Given an array, colors, which contains a combination of the following three elements:

  • 0 (Representing red)

  • 1 (Representing white)

  • 2 (Representing blue)

Sort the array in place so that the elements of the same color are adjacent, and the final order is: red (0), then white (1), and then blue (2).

Note: You are not allowed to use any built-in sorting functions. The goal is to solve this efficiently without extra space.

Constraints:

  • nn ==== colors.length

  • 11 \leq nn 300\leq 300

  • colors[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

1

What is the output if the following array is given as input?

colors = [2, 2, 1, 1, 0]

A)

[0, 1, 1, 2, 2]

B)

[0, 2, 2, 1, 1]

C)

[0, 1, 2, 1, 2]

D)

[2, 2, 0, 1, 1]

Question 1 of 30 attempted

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:

Note: Leave the return statement intact while adding your code.

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

Access this course and 1200+ top-rated courses and projects.