Sort an Array of 0s and 1s

viaGlassdoor

Problem: Given an array containing only 0s and 1s, sort it in place so all 0s come before all 1s.

Constraints: In-place, single pass preferred.

Example: [1,0,1,0,0,1] -> [0,0,0,1,1,1].

Approach: Two-pointer partitioning: maintain a pointer for the next position to place a 0; iterate through the array, and whenever a 0 is found, swap it into place and advance the pointer. O(n) time, O(1) space - a special case of the Dutch National Flag algorithm with two buckets instead of three.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account