Count inversions in a permutation
Problem Description
Given an array a of length n that is a permutation of distinct integers (e.g., 1..n), an inversion is defined as a pair of indices (i, j) such that:
0 ≤ i < j < na[i] > a[j]
Task
Write a function that returns the total number of inversions in the array.
Input/Output
- Input: An integer array
awith all distinct values. - Output: A single integer representing the count of inversions.
Notes
Any time complexity is acceptable (e.g., an O(n^2) approach is fine), but candidates are encouraged to discuss and implement faster approaches if they are familiar with them.
AI interview prep
Core dilemma
Optimizing the time complexity for counting inversions, specifically moving beyond the naive quadratic approach to a more efficient one, often involving divide and conquer.
2 tradeoffs and 2 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Count inversions in a permutation
Problem Description
Given an array a of length n that is a permutation of distinct integers (e.g., 1..n), an inversion is defined as a pair of indices (i, j) such that:
0 ≤ i < j < na[i] > a[j]
Task
Write a function that returns the total number of inversions in the array.
Input/Output
- Input: An integer array
awith all distinct values. - Output: A single integer representing the count of inversions.
Notes
Any time complexity is acceptable (e.g., an O(n^2) approach is fine), but candidates are encouraged to discuss and implement faster approaches if they are familiar with them.