Data Structures & AlgorithmsHardProduct Company SDE · counting
Problem: How many inversions (pairs i < j with a[i] > a[j]) does a = [2, 0, 2, 1, 1, 0] have? Run the code.
Problem: How many inversions (pairs i < j with a[i] > a[j]) does a = [2, 0, 2, 1, 1, 0] have? Run the code.
a = [2, 0, 2, 1, 1, 0] 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. 9
- B. 8
- C. 10
- D. 6
Correct answer: A. 9
Equal values are not inversions. Counting only pairs with the first element at index 0 gives 4, which is not the total.
More Coding Interview Problems questions
- Problem: How many integers x in [1, 50] are perfect sixth powers (x = y^6 for an integer y)? Run the code. python print(sum(1 for x in…
- Problem: Merging ropes of lengths 2, 3, 4 costs the sum of the two lengths merged each time, always merging the two shortest. What is the…
- Problem: How many subsets (including the empty one) of {1, 2, 3, 4, 5} have a sum divisible by 4? Run the code. python print(sum(1 for m…
- Problem: What does the following print? It takes the maximum of every window of size 2 in [4, 2, 12, 11, -5]. python a = [4, 2, 12, 11…
- Problem: What is the sum of the number of 1-bits in the binary representations of 1, 2, ..., 20? Run the code. python…
- Problem: Which statement about shortest paths in a weighted directed acyclic graph (DAG) is correct?