Sort Colors
Try to solve the Sort Colors problem.
We'll cover the following
Statement
Given an array, colors
, which contains a combination of the following three elements:
-
(representing red)
-
(representing white)
-
(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:
-
colors.length
300 colors[i]
can only contain s, s, or s.
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
What is the output if the following array is given as input?
colors = [2, 2, 1, 1, 0]
[0, 1, 1, 2, 2]
[0, 2, 2, 1, 1]
[0, 1, 2, 1, 2]
[2, 2, 0, 1, 1]
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:
Note: Leave the
return
statement intact while adding your code.
def sort_colors(colors):# Replace this placeholder return statement with your codereturn colors