Data Structures & AlgorithmsModerateTCS NQT · sorting
Problem: What is the minimum number of operations to sort the array [4, 3, 2, 1] using only swaps of adjacent elements? Run the code.
Problem: What is the minimum number of operations to sort the array [4, 3, 2, 1] using only swaps of adjacent elements? Run the code.
a = [4, 3, 2, 1]
ops = 0
for i in range(len(a)):
for j in range(len(a) - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
ops += 1
print(ops)What is printed?- A. 4
- B. 3
- C. 10
- D. 6
Correct answer: D. 6
Adjacent swaps remove exactly one inversion each, and [4,3,2,1] has 6 inversions. Bubble sort performs one swap per inversion, so the count equals the inversion number.
More Coding Interview Problems questions
- Problem: Consider a graph where you must find the minimum 'maximum edge' on a path from s to t (a bottleneck path). Which algorithm…
- Problem: For a segment tree with n leaves supporting range-sum queries and point updates, what is the total space needed in terms of n?
- Problem: Find the number of inversions in [5, 4, 3, 2, 1] that a merge-sort based counter would report. Run the code. python def count(a)…
- Problem: Which claim about the Knuth-Morris-Pratt algorithm is correct?
- Problem: A player picks a number from 1 to 10 and the other player must guess it by yes/no questions. The minimum worst-case number of…
- Problem: What is the complexity of computing all prefix XOR values of an array of n = 10^6 integers and then answering q = 10^6 range-XOR…