Data Structures & AlgorithmsHardProduct Company SDE · counting
Problem: How many inversions does the array [5, 1, 4, 2, 3] have? Run the code.
Problem: How many inversions does the array [5, 1, 4, 2, 3] have? Run the code.
a = [5, 1, 4, 2, 3] print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if a[i] > a[j]))What is printed?
- A. 2
- B. 10
- C. 4
- D. 6
Correct answer: D. 6
5 beats all four later values and 4 beats 2 and 3, giving 6 inversions. Adjacent descents give 2, 10 is all pairs, and the 4 increasing pairs are the complement.
More Coding Interview Problems questions
- Problem: What is the greatest common divisor of 12, 18, 30 and 42? Run the code. python from math import gcd from functools import reduce…
- Problem: What is the worst-case time complexity of binary search for the first occurrence of a value in a sorted array that contains…
- Problem: Which algorithm constructs an Euler circuit of a connected graph whose vertices all have even degree in linear time?
- Problem: What is the time complexity of computing the Z-array of a string of length n?
- Problem: Which deterministic algorithm finds the global minimum cut of an undirected weighted graph with V vertices in O(V^3) time?
- Count the non-empty subarrays of a = [3, -1, 4, -1, 5, -9, 2, 6] whose sum is divisible by 5, using prefix sums taken modulo 5. python…