Data Structures & AlgorithmsModerateProduct Company SDE · CP practice
Problem: How many inversions does the array [2, 3, 8, 6, 1] have? Run the code.
Problem: How many inversions does the array [2, 3, 8, 6, 1] have? Run the code.
a = [2, 3, 8, 6, 1] 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. 6
- B. 4
- C. 7
- D. 5
Correct answer: D. 5
Each element is compared with the smaller values after it; the count of inversions is 5.
More Coding Interview Problems questions
- Problem: What is the number of distinct subarray sums of [1, 2, 3] (non-empty subarrays)? Run the code. python a = [1, 2, 3]…
- Problem: What is the sum of all two-digit numbers that are divisible by the sum of their digits? Run the code. python print(sum(x for x in…
- Problem: How many integers in [1, 1000] are both perfect squares and perfect cubes? Run the code. python print(sum(1 for x in range(1…
- Problem: How many integers in [1, 100] are divisible by neither 2 nor 3? Run the code. python print(sum(1 for x in range(1, 101) if x % 2…
- Problem: How many ordered pairs (a, b) with 1 <= a, b <= 9 make a b a perfect square? Run the code. python print(sum(1 for a in range(1…
- Problem: What is the time complexity of Johnson's all-pairs shortest path algorithm on a sparse graph with V vertices and E edges?