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)- A. [2, 4, 3, 5, 7, 9, 8] 3
- B. [2, 3, 4, 5, 9, 8, 7] 3
- C. [4, 2, 3, 5, 9, 8, 7] 3
- 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²).
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
- Merge two sorted halves and count comparisons. What is printed? python L, R = [1, 4, 6, 9], [2, 3, 10] i = j = comps = 0; out = [] while i…
- What is printed? (Python list aliasing) python a = [1, 2, 3] b = a c = a[:] b.append(4) c.append(5) print(a, len(b), len(c))
- What is printed? (frequency of the most common character, ties to the earliest) python s = "programming" best = max(s, key=s.count)…
- Sliding window: what is printed? (maximum sum of any 3 consecutive elements) c int a[] = {4, -1, 6, -2, 3, 5, -4, 2}; int n = 8, k = 3, s…
- What is printed? (two-pointer: remove all occurrences of a value in place) cpp vector<int> a = {3, 2, 2, 3, 4, 3, 5}; int w = 0; for (int…
- What is printed? (stack: check if a sequence of pops is possible after pushing 1..n in order) python def valid(pushed, popped): st, j =…