DSA interview question
A music-recommendation service compares a user's ranking of songs with the global chart. A good measure of disagreement is the number of inversions: pairs of songs the user ranks in the opposite order to the chart, i.e. pairs i < j with a[i] > a[j]. Counting all pairs is O(n²), far too slow for long playlists. Merge sort can count them in O(n log n): whenever merging takes an element from the right half, it is smaller than every element still waiting in the left half, and each of those pairs is one inversion.
Example: [2, 4, 1, 3, 5] → 3 (the pairs (2, 1), (4, 1), (4, 3)).
long long countInversions(vector<int> a); // number of pairs i < j with a[i] > a[j]
Input a | Output | Explanation |
|---|---|---|
[2, 4, 1, 3, 5] | 3 | (2,1), (4,1), (4,3) |
[2, 3, 4, 5, 6] | 0 | Sorted |
[5, 4, 3, 2, 1] | 10 | Reverse sorted: n(n − 1)/2 |
[10, 10, 10] | 0 | Equal elements are not inversions |
[8, 4, 2, 1] | 6 | |
[1] | 0 |
(Confirm: only strictly greater pairs count; the answer can be as large as n(n − 1)/2, so use 64-bit.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in