Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag).

Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag).
void sort012(vector<int>& a) {
    int lo = 0, mid = 0, hi = a.size() - 1;
    while (mid <= hi) {
        if (a[mid] == 0) swap(a[lo++], a[mid++]);
        else if (a[mid] == 1) mid++;
        else swap(a[mid], a[hi--]);      // mid is NOT advanced
    }
}
// a = {2, 0, 2, 1, 1, 0}
What is a after the call?
  1. A. 0 0 1 2 1 2
  2. B. 0 1 0 1 2 2
  3. C. 0 0 1 1 2 2
  4. D. 2 2 1 1 0 0

Correct answer: C. 0 0 1 1 2 2

Invariant: [0, lo) holds 0s, [lo, mid) 1s, (hi, end] 2s. After swapping a 2 to the back, the element brought to mid is unexamined, so mid must stay – advancing it is the classic bug that leaves a 2 or 0 misplaced. One pass, O(1) space.

More Coding Interview Problems questions

Exams that ask this topic