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:
colors.length
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
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.
import java.util.*;public class Solution {public static int[] sortColors (int[] colors) {// Write your code herereturn colors;}}