Count Inversions in Array in DSA Go - Time & Space Complexity
We want to understand how the time needed to count inversions in an array changes as the array grows.
How does the number of steps increase when the array gets bigger?
Analyze the time complexity of the following code snippet.
func countInversions(arr []int) int {
count := 0
for i := 0; i < len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
count++
}
}
}
return count
}
This code counts how many pairs of elements are out of order in the array by checking every pair.
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 outer loop, 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 because every element is compared with many others.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 comparisons |
| 100 | About 4,950 comparisons |
| 1000 | About 499,500 comparisons |
Pattern observation: When the input size doubles, the number of operations roughly quadruples.
Time Complexity: O(n²)
This means the time needed grows very quickly as the array gets bigger, because every element is checked against many others.
[X] Wrong: "Counting inversions can be done in linear time by just scanning the array once."
[OK] Correct: Because to find all pairs out of order, you must compare many pairs, not just look at each element once.
Understanding this helps you explain why some problems need more time and how to think about improving solutions, which is a valuable skill in interviews.
"What if we use 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: Identify the correct description
A pair of elements where the first is greater than the second and appears before it correctly describes this condition as the first element being greater and appearing before the second.Final Answer:
A -> Option BQuick Check:
Inversion = pair where first > second and first appears earlier [OK]
- Confusing inversion with sorted order
- Thinking inversion counts equal or smaller pairs
- Mixing up element positions
Solution
Step 1: Check function signature syntax in Go
In Go, a function with an integer slice parameter and integer return type is declared asfunc name(arr []int) int.Step 2: Validate return statement type
func countInversions(arr []int) int { return 0 } returns an integer 0, matching the return type. Other options have syntax errors or wrong return types.Final Answer:
C -> Option AQuick Check:
Correct Go function syntax returns int [OK]
- Using wrong slice syntax like int[]
- Returning wrong type like string instead of int
- Using void instead of int for return type
func main() {
arr := []int{2, 4, 1, 3, 5}
fmt.Println(countInversions(arr))
}
func countInversions(arr []int) int {
count := 0
for i := 0; i < len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
count++
}
}
}
return count
}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.Step 2: Confirm count from nested loops
Loops check all pairs iFinal Answer:
3 -> Option DQuick Check:
Inversions counted = 3 [OK]
- Counting pairs where first is smaller
- Missing some inversion pairs
- Confusing index order
func countInversions(arr []int) int {
count := 0
for i := 0; i <= len(arr); i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
count++
}
}
}
return count
}Solution
Step 1: Analyze loop boundaries
The outer loop runs with i <= len(arr), which means i can equal len(arr), causing arr[i] to be out of range.Step 2: Identify correct loop condition
The loop should use i < len(arr) to avoid accessing invalid index.Final Answer:
The outer loop uses <= causing index out of range error -> Option AQuick Check:
Loop index must be less than length [OK]
- Using <= instead of < in loops
- Starting inner loop at wrong index
- Wrong comparison operator
[8, 4, 2, 1], which approach is the most efficient to count inversions and what is the inversion count?Solution
Step 1: Understand efficient inversion counting
Merge sort based method counts inversions in O(n log n) time, more efficient than brute force O(n²).Step 2: Calculate inversion count for [8,4,2,1]
Inversions: (8,4), (8,2), (8,1), (4,2), (4,1), (2,1) = 6 total.Final Answer:
Use merge sort based method; inversion count is 6 -> Option CQuick Check:
Merge sort counts 6 inversions efficiently [OK]
- Using slow brute force for large arrays
- Miscounting inversion pairs
- Confusing inversion count with swap count
Ready to prove it?
Pass the test and this pattern moves unknown
