Sort Colors

Try to solve the Sort Colors problem.

Statement

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

  • 00 (representing red)

  • 11 (representing white)

  • 22 (representing blue)

Sort the array in place so that the elements of the same color are adjacent, with the colors in the order of red, white, and blue. To improve your problem-solving skills, do not utilize the built-in sort function.

Constraints:

  • 11 \leq colors.length \leq 300
  • colors[i] can only contain 00s, 11s, or 22s.

Examples

1 of 3

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.

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

Try it yourself

Implement your solution in the following coding playground:

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

Press + to interact
Python
usercode > main.py
def sort_colors(colors):
# Replace this placeholder return statement with your code
return colors
Sort Colors