Prepin
Log in

Arrange the binary array in linear time.

Approach / Explanation

This question requests you to demonstrate a technique for sorting a binary array in linear time. In computer science, a binary array is defined as an array that contains only 0s and 1s. Sorting this array involves arranging its elements in a specific sequence, meaning that all the 0s should precede the 1s, or vice versa. Linear time indicates that the time complexity of your algorithm must be O(n), where n represents the number of elements in the array. This emphasizes the importance of efficiency, as linear time complexity is typically anticipated for tasks that have straightforward and direct solutions. Key points to keep in mind - Explain the rationale behind separating 0s and 1s using a two-pointer or counting technique. Clarify that the two-pointer technique divides the array into four sections. Indicate that the counting method starts by tallying the number of 0s (or 1s). The time complexity must be O(n).

Suggested Answer

A common strategy for addressing this issue is the two-pointer technique. We start with one pointer at the beginning of the array and the other at the end, gradually moving towards the center. When the first pointer finds a 1 and the second pointer finds a 0, we swap these two elements. If that’s not the case, we simply adjust the pointers as needed. We halt the process when the two pointers converge. This approach is effective because it segments the array into four parts: a section of 0s, a section of 1s, and the area where the two pointers are moving . The time complexity for this method is linear, O(n).

Alternative Answer

Another possible solution is the counting method. In this approach, we first go through the array to tally the number of 0s (or 1s). After obtaining the count, we can populate the beginning of the array with 0s (based on the count) and fill the remainder with 1s (or the opposite if we counted 1s initially). This method also has a linear time complexity of O(n), but it necessitates two passes through the array—one for counting and another for filling in the values. Therefore, if I were asked this question, I would initially discuss the two-pointer technique, which only requires a single pass, and then introduce this counting method as an alternative, clearly highlighting the difference in the number of traversals required.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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