Data Structures & AlgorithmsVery hardProduct company OA
Inversions counted during merge sort (pairs i < j with a[i] > a[j]). What is printed?
Inversions counted during merge sort (pairs i < j with a[i] > a[j]). What is printed?
def inv(a):
if len(a) <= 1: return a, 0
m = len(a) // 2
L, x = inv(a[:m]); R, y = inv(a[m:])
out, i, j, c = [], 0, 0, x + y
while i < len(L) and j < len(R):
if L[i] <= R[j]: out.append(L[i]); i += 1
else: out.append(R[j]); j += 1; c += len(L) - i
return out + L[i:] + R[j:], c
print(inv([5, 3, 8, 3, 1, 9, 2])[1], inv([4, 4, 4])[1], inv(list(range(10, 0, -1)))[1])- A. 12 3 45
- B. 12 0 45
- C. 11 0 45
- D. 12 0 55
Correct answer: B. 12 0 45
When R[j] is taken before L[i], it is smaller than every remaining element of L, so it adds len(L) − i inversions at once – O(n log n) instead of O(n²). [5,3,8,3,1,9,2]: brute force confirms 12. Equal values are not inversions, and the merge takes from L on ties (≤), so [4,4,4] gives 0; using < there would count equal pairs and give 3. A reversed array of 10 has C(10, 2) = 45.
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
- One Hoare partition with the FIRST element (6) as pivot. What is printed (array after the partition, returned index)? python def hoare(a)…
- Counting palindromic substrings (by position) with centre expansion over 2n − 1 centres. What is printed? python def pal(s): c = 0 for…
- Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is…
- Merging files costs the size of the result each time. Compare the greedy 'always merge the two smallest' (heap) with merging left to right…
- You must count pairs i < j with a[i] + a[j] ≤ T for n ≤ 2·10⁵ values up to 10⁹ in absolute value (time limit 1 s). Which plan passes?
- A service stores n = 10⁵ integer keys in a chained hash table with m = 1000 buckets and h(k) = k mod m. An attacker sends keys that are…