Data Structures & AlgorithmsModerateTCS NQT · sorting
Problem: How many swaps does insertion sort perform on [3, 2, 1]? Count the shifts in the code.
Problem: How many swaps does insertion sort perform on [3, 2, 1]? Count the shifts in the code.
a = [3, 2, 1]
swaps = 0
for i in range(1, len(a)):
j = i
while j > 0 and a[j - 1] > a[j]:
a[j - 1], a[j] = a[j], a[j - 1]
swaps += 1
j -= 1
print(swaps)What is printed?- A. 3
- B. 2
- C. 1
- D. 6
Correct answer: A. 3
Insertion sort performs one swap per inversion, and [3,2,1] has 3 inversions.
More Coding Interview Problems questions
- Problem: What is the minimum number of intervals from [[1,4],[3,7],[6,10],[9,10]] needed to cover the segment [1, 10]? Run the greedy…
- Problem: How many pairs (i < j) of [1, 2, 3, 4, 5] have a[i] XOR a[j] = 1? Run the code. python a = [1, 2, 3, 4, 5] print(sum(1 for i in…
- Problem: How many subarrays of [3, 4, 7, 2, -3, 1, 4, 2] have sum exactly 7? Run the prefix-sum hash code. python from collections import…
- Problem: What is the length of the shortest substring of 'aabcbcdbca' that contains all distinct characters of the string? Run the…
- Problem: What is the Levenshtein distance between 'horse' and 'ros'? Run the DP. python a, b = 'horse', 'ros' dp = [[0] (len(b) + 1) for…
- Problem: What is the sum of |ai - aj| over all pairs i < j of the sorted array [1, 4, 6]? Run the code. python a = sorted([1, 4, 6])…