Data Structures & AlgorithmsHardProduct Company SDE · ICPC regional
Consider the permutation p = [4, 1, 7, 3, 8, 2, 6, 5]. Count its inversions, i.e. pairs of positions i < j with p[i] > p[j]. Run the code.
Consider the permutation p = [4, 1, 7, 3, 8, 2, 6, 5]. Count its inversions, i.e. pairs of positions i < j with p[i] > p[j]. Run the code.
p=[4,1,7,3,8,2,6,5] print(sum(1 for i in range(len(p)) for j in range(i+1,len(p)) if p[i]>p[j]))What is printed?
- A. 6
- B. 16
- C. 4
- D. 12
Correct answer: D. 12
An inversion is a pair in the wrong order, so the count is over i < j with p[i] > p[j]. Counting only adjacent descents undercounts, and counting the non-inversion pairs gives the complement.
More Coding Interview Problems questions
- Problem: A connected undirected graph has 7 vertices. Its BFS tree from vertex 0 has depths: vertex 0 at depth 0, vertices 1 and 2 at…
- Problem: A graph's vertices 0–4 are connected by edges 0-1 (1), 1-2 (1), 2-3 (1), 3-4 (1), 0-4 (5), 1-3 (3). What is the largest…
- Problem: In a directed graph on vertices 0–3, the arcs are 0→1, 1→2, 2→0, 2→3. The vertex 3 has no outgoing arcs. How many vertices can…
- Problem: A rooted tree has root 1 and children 1: [2, 3, 4], 3: [5], 4: [6, 7]. The number of nodes on the longest root-to-leaf path…
- Problem: The string "abcdcba" is checked for palindromic substrings with an odd length of at least 5. How many such substrings are there?
- Problem: What is the number of distinct strings of length 4 over the alphabet {a, b} containing at least one 'a' and at least one 'b'?