Solution Review: Partitioning of 0s, 1s and 2s

Let's look at the solution to the challenge posed in the previous lesson.

Solution

The basic approach is to use three indices. The first is left, the second is right, and the third is i that is used to traverse the array. The index on the left begins at 0, while the index on the right begins at n-1. When we discover a 0 in the array, we swap it with the start and increment start. And anytime we come across a 2, we decrease right by swapping this value with the right. When traversal is complete, and we reach the right, then the array is sorted.

Code

Now, letā€™s look at the code of the solution

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