Infosys · Question 1 · Arrays
Reverse Pairs - related to count inversions
Problem
Count the number of inversions in the array, i.e., pairs (i, j) such that i < j and arr[i] > arr[j].
Approach
Use modified merge sort: during merge, when a right element is smaller, count inversions equal to remaining left elements.
Time O(nlogn)Space O(n)
How it works
- 1Sort halves recursively, counting inside each.
- 2Merging: a smaller right element beats all remaining left ones.
Sample input / output
Input: arr = [2, 4, 1, 3, 5] Output: 3
Constraints
1 <= n <= 10^5; 64-bit count.
Solution — read it, then walk it
Time O(nlogn)Space O(n)Loops 3Branches 2Returns 4source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/29
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits