Data Structures & AlgorithmsVery hardProduct company OA
One Hoare partition with the FIRST element (6) as pivot. What is printed (array after the partition, returned index)?
One Hoare partition with the FIRST element (6) as pivot. What is printed (array after the partition, returned index)?
def hoare(a):
p = a[0]; i, j = -1, len(a)
while True:
i += 1
while a[i] < p: i += 1
j -= 1
while a[j] > p: j -= 1
if i >= j: return a, j
a[i], a[j] = a[j], a[i]
print(hoare([6, 3, 9, 6, 1, 8, 2, 7]))- A. ([2, 3, 1, 6, 6, 8, 9, 7], 4)
- B. ([2, 3, 1, 6, 9, 8, 6, 7], 3)
- C. ([1, 2, 3, 6, 6, 7, 8, 9], 3)
- D. ([2, 3, 1, 6, 9, 8, 6, 7], 4)
Correct answer: B. ([2, 3, 1, 6, 9, 8, 6, 7], 3)
i stops at elements ≥ pivot and j at elements ≤ pivot, then they swap. Round 1: i = 0 (6), j = 6 (2) → swap. Round 2: i = 2 (9), j = 4 (1) → swap. Round 3: i = 3 (6), j = 3 (6) → i ≥ j, return 3. Unlike Lomuto, Hoare does NOT put the pivot in its final place: the result only guarantees a[0..3] ≤ 6 ≤ a[4..7], and an equal 6 is left on each side. Recurse on [lo, j] and [j + 1, hi].
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
- Counting palindromic substrings (by position) with centre expansion over 2n − 1 centres. What is printed? python def pal(s): c = 0 for…
- Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is…
- Merging files costs the size of the result each time. Compare the greedy 'always merge the two smallest' (heap) with merging left to right…
- You must count pairs i < j with a[i] + a[j] ≤ T for n ≤ 2·10⁵ values up to 10⁹ in absolute value (time limit 1 s). Which plan passes?
- A service stores n = 10⁵ integer keys in a chained hash table with m = 1000 buckets and h(k) = k mod m. An attacker sends keys that are…
- An empty queue performs: enqueue 7, enqueue 2, enqueue 9, dequeue, enqueue 4, dequeue. Which element is now at the front?