Data Structures & AlgorithmsHardProduct Company SDE pattern

Quick sort with Lomuto partition (last element as pivot). What is the array after the FIRST partition, and the pivot's final index?

Quick sort with Lomuto partition (last element as pivot). What is the array after the FIRST partition, and the pivot's final index?
a = [7, 2, 9, 4, 3, 8, 5]
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]
print(a, i + 1)
  1. A. [2, 4, 3, 5, 7, 9, 8] 3
  2. B. [2, 3, 4, 5, 9, 8, 7] 3
  3. C. [4, 2, 3, 5, 9, 8, 7] 3
  4. D. [2, 4, 3, 5, 9, 8, 7] 3

Correct answer: D. [2, 4, 3, 5, 9, 8, 7] 3

Elements ≤ 5 (2, 4, 3) are swapped to the front in order of appearance; then the pivot swaps with the first larger element (7) at index 3. The right side [9, 8, 7] is not sorted yet. On already-sorted input Lomuto degrades to O(n²).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic