Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: One pass of Lomuto partition (pivot = last element) as used in quicksort.
Problem: One pass of Lomuto partition (pivot = last element) as used in quicksort.
def lomuto(a):
p = a[-1]; i = -1
for j in range(len(a) - 1):
if a[j] <= p:
i += 1; a[i], a[j] = a[j], a[i]
a[i+1], a[-1] = a[-1], a[i+1]
return a, i + 1
print(*lomuto([7, 2, 9, 4, 1, 8, 5]))What is printed?- A. [2, 4, 1, 5, 7, 8, 9] 3
- B. [2, 4, 1, 5, 9, 8, 7] 3
- C. [1, 2, 4, 5, 7, 8, 9] 3
- D. [2, 4, 1, 5, 9, 8, 7] 4
Correct answer: B. [2, 4, 1, 5, 9, 8, 7] 3
Elements ≤ 5 (2, 4, 1) are swapped forward in order of appearance; the others are left where the swaps put them: after the loop a = [2, 4, 1, 7, 9, 8, 5], then the pivot swaps with index 3 (7): [2, 4, 1, 5, 9, 8, 7], pivot index 3. Partition does not sort either side.
More Coding Interview Problems questions
- Problem: Count the swaps made by bubble sort and by selection sort on the same array. python def bubble(a): a = a[:]; s = 0 for i in…
- Problem: Bottom-up heapify (max-heap) of an array; print the resulting array. python def heapify(a): n = len(a) def down(i): while True…
- Problem: Insert keys into a hash table of size 7 with open addressing and LINEAR probing, h(k) = k mod 7. python T = [None] 7 for k in…
- Problem: Double hashing with h1(k) = k mod 11 and h2(k) = 7 − (k mod 7); probe i is (h1 + i·h2) mod 11. Print the slots probed for key 58…
- Problem: Exponential (galloping) search: double the bound until a[hi] ≥ target, then binary search in (hi/2, hi]. Count the comparisons of…
- Problem: Count unique quadruplets (as value multisets) summing to target with sort + two nested loops + two pointers. python def four(a…