Data Structures & AlgorithmsHardGoldman Sachs OA · LeetCode medium-hard
The Dutch National Flag algorithm (single pass, three pointers low/mid/high) partitions [2, 1, 0, 2, 2, 0, 1, 2, 2] (values 0, 1, 2 only) in place. What is the resulting array?
- A. 2, 2, 2, 2, 2, 1, 1, 0, 0
- B. 2, 2, 1, 0, 2, 2, 0, 1, 2
- C. 0, 0, 2, 2, 2, 2, 2, 1, 1
- D. 0, 0, 1, 1, 2, 2, 2, 2, 2
Correct answer: D. 0, 0, 1, 1, 2, 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, 1, 1, 2, 2, 2, 2, 2]. Sorting in descending order, [2, 2, 2, 2, 2, 1, 1, 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
- What is the sum of the minimum element over every contiguous subarray of [3, 6, 5, 3, 8, 4, 9, 1]?
- Two sorted linked lists [7 → 13 → 23 → 40] and [5 → 6 → 9 → 18 → 25] are merged with the standard O(n+m) two-pointer merge (always take…
- The Dutch National Flag algorithm (single pass, three pointers low/mid/high) partitions [2, 0, 2, 2, 1, 0, 1, 1] (values 0, 1, 2 only) in…
- Array [85, 11, 19, 30, 40, 43, 70] is a sorted array rotated at pivot 6. Using the standard O(log n) rotated-array binary search (decide…
- A min-stack (push/pop O(1), getMin O(1) via an auxiliary stack tracking the running minimum) runs this sequence in order: push(-2)…
- Array [1, 2, 3, 4, 5, 6, 7, 8, 9] is left-rotated by d = 6 positions using the reversal algorithm (reverse first d, reverse rest, reverse…