Data Structures & AlgorithmsHardGATE CS · DSA
The Dutch National Flag algorithm (single pass, three pointers low/mid/high) partitions [2, 2, 1, 0, 0, 0, 2, 2] (values 0, 1, 2 only) in place. What is the resulting array?
- A. 2, 2, 2, 2, 1, 0, 0, 0
- B. 2, 2, 0, 0, 0, 1, 2, 2
- C. 0, 0, 0, 2, 2, 2, 2, 1
- D. 0, 0, 0, 1, 2, 2, 2, 2
Correct answer: D. 0, 0, 0, 1, 2, 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, 0, 0, 1, 2, 2, 2, 2]. Sorting in descending order, [2, 2, 2, 2, 1, 0, 0, 0], is a different (and wrong) ordering.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Two sorted linked lists [1 → 10 → 11 → 19 → 28] and [12 → 14 → 18 → 27 → 35] are merged with the standard O(n+m) two-pointer merge (always…
- Two sorted linked lists [3 → 14 → 35 → 39] and [9 → 20 → 21 → 27 → 34] are merged with the standard O(n+m) two-pointer merge (always take…
- Floyd's cycle detection runs on a linked list 1 → 2 → ... → 7 whose last node's next pointer points back to node 5 (0-based position 4)…
- Heights [1, 6, 2, 6, 2, 5, 2, 2, 7] represent vertical lines at each index. What is the maximum water area (min(height) × horizontal…
- Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the…
- Elevation map [4, 5, 4, 4, 0, 1, 2, 1, 0, 2] (bar width 1). Using the two-pointer / prefix-max approach for trapping rain water, how much…