Data Structures & AlgorithmsHardProduct company OA

The Dutch National Flag algorithm (single pass, three pointers low/mid/high) partitions [1, 1, 2, 2, 1, 1, 1, 1, 2, 0] (values 0, 1, 2 only) in place. What is the resulting array?

  1. A. 0, 2, 2, 2, 1, 1, 1, 1, 1, 1
  2. B. 2, 2, 2, 1, 1, 1, 1, 1, 1, 0
  3. C. 0, 1, 1, 1, 1, 1, 1, 2, 2, 2
  4. D. 0, 2, 1, 1, 1, 1, 2, 2, 1, 1

Correct answer: C. 0, 1, 1, 1, 1, 1, 1, 2, 2, 2

The algorithm groups all 0s first, then all 1s, then all 2s, in one linear pass without a general comparison sort. For this input that gives [0, 1, 1, 1, 1, 1, 1, 2, 2, 2]. Sorting in descending order, [2, 2, 2, 1, 1, 1, 1, 1, 1, 0], is a different (and wrong) ordering.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic