Challenge: Partitioning of 0s, 1s, and 2s

Learn how you can solve the problem of partitioning 0s, 1s, and 2s using a sorting algorithm.


Given an array containing 0s, 1s, and 2s, write a program to sort the array so that 0s come first, followed by 1s, and then 2s in the end.


An integer array.


An integer array.

Sample input

array = { 0, 0, 2, 0, 2, 1, 0, 1 }

Sample output

array = { 0, 0, 0, 0, 1, 1, 2, 2 }

Coding exercise

Try to solve this yourself first. If you get stuck or need help, you can always press the “Show Solution” button to see how your problem can be solved. We’ll look at the solution in the next lesson.

Good luck!

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.