Loading...
Loading...
At a college fest, every volunteer wears a T-shirt with a colour code: 0 for red, 1 for white and 2 for blue. For the group photo, all red shirts must stand first, then white, then blue. Rearrange the list of codes in one pass, using swaps inside the same array, and print the final order.
Example
Input
7 2 0 1 2 1 0 0
Output
0 0 0 1 1 2 2
Three 0s, then two 1s, then two 2s.
Try the problem first. Open one hint at a time.
Counting the 0s, 1s and 2s works, but try to do it in one pass with swaps.
Keep three indexes: low (where the next 0 goes), mid (the code you are checking) and high (where the next 2 goes).
A 0 at mid is swapped to low, and both move forward. A 1 just lets mid move forward.
A 2 at mid is swapped to high, and only high moves back. The code that arrived at mid has not been checked yet.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor