Prepin
Log in

Arrange an array that consists solely of 0s, 1s, and 2s.

Approach / Explanation

This question requires you to develop an algorithm to sort an array, but with a specific condition: the array consists solely of 0s, 1s, and 2s. Your goal is to arrange the elements so that all the 0s come first, followed by all the 1s, and then all the 2s. To assist you in addressing this question, it's essential to concentrate on sorting algorithms that are effective for a limited range of inputs, such as counting sort or bucket sort. Additionally, consider the single pass algorithm known as the Dutch National Flag Algorithm, which provides an efficient linear time solution for this task.

Suggested Answer

A straightforward method to tackle this issue is to tally the occurrences of 0s, 1s, and 2s in the array, and then populate the array with the corresponding quantities of each. This will yield a sorted array. Below is a Python code example that demonstrates this method: def sortArray ( nums ) : count = [ 0 , 0 , 0 ] for num in nums : count [ num ] += 1 i = 0 for num in range ( 3 ) : for _ in range ( count [ num ] ) : nums [ i ] = num i += 1 return nums This code first counts the occurrences of each of the three numbers and then fills the array with the correct amounts of each, resulting in a sorted array.

Alternative Answer

Another method employs the Dutch National Flag Algorithm, which sorts the array in a single traversal. It utilizes three pointers: one for the next position of 0, another for the next position of 2, and a third to iterate through the array. Below is the Python code implementing this technique: def sortArray ( nums ) : low , mid , high = 0 , 0 , len ( nums ) - 1 while mid <= high : if nums [ mid ] == 0 : nums [ low ] , nums [ mid ] = nums [ mid ] , nums [ low ] low += 1 mid += 1 elif nums [ mid ] == 1 : mid += 1 else : nums [ mid ] , nums [ high ] = nums [ high ] , nums [ mid ] high -= 1 return nums In this implementation, the mid pointer advances, swapping the current element with the high pointer if it equals 2, or with the low pointer if it is 0. If the element is 1, the pointer simply moves forward. This method effectively sorts the array in a single pass.

Question Details

Difficulty & Category

Medium
algorithms

Companies

LinkedIn

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.