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?
  1. A. [2, 4, 1, 5, 7, 8, 9] 3
  2. B. [2, 4, 1, 5, 9, 8, 7] 3
  3. C. [1, 2, 4, 5, 7, 8, 9] 3
  4. 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

Exams that ask this topic