← Infosys bank

Infosys · Question 1 · Arrays

Reverse Pairs - related to count inversions

ArraysC++code⏱ O(nlogn)💾 O(n)
Service-based

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

  1. 1Sort halves recursively, counting inside each.
  2. 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.
yesno↻ repeatSTARTinclude <iostream>include <vector>using namespace stdDEFINE longmerge_count(vector<int>&arr, int l, int m, int r)vector<int>left(arr.begin() + l,arr.begin() + m + 1)vector<int>right(arr.begin() + m + 1,arr.begin() + r + 1)size_t i = 0, j = 0DEFINE k = lDEFINE long inv = 0while (i < left.size()&& j < right.size())if (left[i] <=right[j])arr[k++] = left[i++]} elsewhile (i <left.size()) arr[k++]= left[i++]while (j <right.size()) arr[k++]= right[j++]RETURN invDEFINE longmergeSortCount(vector<int>&arr, int l, int r)if (l >= r) return 0DEFINE m = l + (r - l) / 2DEFINE long inv =mergeSortCount(arr, l, m) +mergeSortCount(arr, m + 1…inv += merge_count(arr, l,m, r)RETURN invDEFINE longcountInversions(vector<int>&arr)RETURN mergeSortCount(arr,0, (int)arr.size() - 1)DEFINE main()vector<int> arr = {2, 4, 1,3, 5}cout <<countInversions(arr) <<endlRETURN 0END
  • 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