Count Inversions in Array in DSA Typescript - Time & Space Complexity
Counting inversions means finding how many pairs in an array are out of order.
We want to know how the time to count these pairs grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
function countInversions(arr: number[]): number {
let count = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) count++;
}
}
return count;
}
This code counts how many pairs (i, j) have arr[i] > arr[j] with i < j.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing pairs of elements to check if one is greater than the other.
- How many times: The outer loop runs n times, and for each, the inner loop runs up to n times, so roughly n x n = n² times.
As the array size grows, the number of comparisons grows much faster.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 comparisons |
| 100 | About 4,950 comparisons |
| 1000 | About 499,500 comparisons |
Pattern observation: When input size doubles, operations roughly quadruple, showing a square growth.
Time Complexity: O(n²)
This means the time to count inversions grows roughly with the square of the array size.
[X] Wrong: "Counting inversions can be done in linear time by just one pass."
[OK] Correct: Because you must compare pairs, and many pairs exist, so one pass cannot see all pairs needed.
Understanding this helps you see why some problems need careful approaches to avoid slow solutions.
"What if we used a divide-and-conquer method like merge sort to count inversions? How would the time complexity change?"
Practice
inversion mean in the context of an array?Solution
Step 1: Understand the definition of inversion
An inversion is a pair of elements (i, j) such that i < j but array[i] > array[j].Step 2: Compare options with definition
A pair of elements where the first is greater than the second and appears before it correctly describes this condition. Other options describe unrelated concepts.Final Answer:
A pair of elements where the first is greater than the second and appears before it -> Option DQuick Check:
Inversion = pair where earlier element > later element [OK]
- Confusing inversion with sorted order
- Thinking inversion counts total elements
- Mixing up greater and smaller element order
Solution
Step 1: Analyze the function purpose and parameters
The function should take an array of numbers and return a number representing the count of inversions.Step 2: Match the correct signature
function countInversions(arr: number[]): number matches this: input is number array, output is number. Others mismatch input/output types.Final Answer:
function countInversions(arr: number[]): number -> Option CQuick Check:
Input array, output number count [OK]
- Using wrong input type like string instead of array
- Returning array instead of number
- Using void return type when output is needed
function countInversions(arr: number[]): number {
let count = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) count++;
}
}
return count;
}
console.log(countInversions([2, 4, 1, 3, 5]));Solution
Step 1: Identify all inversion pairs in the array
Array: [2, 4, 1, 3, 5]. Inversions are (2,1), (4,1), (4,3). Total 3 inversions.Step 2: Confirm the count returned by the nested loops
The nested loops count each inversion correctly, so output is 3.Final Answer:
3 -> Option AQuick Check:
Inversions = 3 [OK]
- Counting pairs incorrectly by missing some
- Confusing equal elements as inversions
- Off-by-one errors in loops
function countInversions(arr: number[]): number {
let count = 0;
for (let i = 0; i <= arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) count++;
}
}
return count;
}Solution
Step 1: Analyze the outer loop condition
The outer loop runs from i = 0 to i <= arr.length, which means i can be arr.length, causing arr[i] to be undefined (out-of-bounds).Step 2: Correct the loop condition
Changing to i < arr.length prevents out-of-bounds access and fixes the bug.Final Answer:
The outer loop condition should be < instead of <= to avoid out-of-bounds -> Option BQuick Check:
Loop bounds must prevent out-of-range access [OK]
- Using <= causes index out-of-bounds error
- Resetting count inside loop loses total count
- Changing comparison reverses inversion logic
[8, 4, 2, 1], which approach is the most efficient to count inversions and what is the inversion count?Solution
Step 1: Identify inversion count manually
Array: [8,4,2,1]. Inversions are (8,4), (8,2), (8,1), (4,2), (4,1), (2,1) totaling 6.Step 2: Choose the most efficient method
Modified merge sort counts inversions in O(n log n), better than nested loops O(n²). Hash map or sorting differences do not directly count inversions.Final Answer:
Use a modified merge sort to count inversions; count is 6 -> Option AQuick Check:
Merge sort method = 6 inversions [OK]
- Counting inversions incorrectly by missing pairs
- Using nested loops for large arrays causing slow performance
- Confusing sorting with inversion counting
Ready to prove it?
Pass the test and this pattern moves unknown
