Global and Local Inversions - Problem
You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].
The number of global inversions is the number of the different pairs (i, j) where:
0 <= i < j < nnums[i] > nums[j]
The number of local inversions is the number of indices i where:
0 <= i < n - 1nums[i] > nums[i + 1]
Return true if the number of global inversions is equal to the number of local inversions.
Input & Output
Example 1 — Equal Inversions
$
Input:
nums = [1,0,2]
›
Output:
true
💡 Note:
Global inversions: (0,1) where 1 > 0. Local inversions: (0,1) where 1 > 0. Both counts are 1, so return true.
Example 2 — Different Inversions
$
Input:
nums = [1,2,0]
›
Output:
false
💡 Note:
Global inversions: (0,2) where 1 > 0 and (1,2) where 2 > 0 = 2 total. Local inversions: (1,2) where 2 > 0 = 1 total. 2 ≠ 1, so return false.
Example 3 — Already Sorted
$
Input:
nums = [0,1,2,3]
›
Output:
true
💡 Note:
No inversions of either type exist. 0 == 0, so return true.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] < nums.length
- nums is a permutation of [0, 1, 2, ..., nums.length - 1]
Visualization
Tap to expand
Understanding the Visualization
1
Input
Permutation array [1,0,2]
2
Process
Count global vs local inversions
3
Output
Return true if counts are equal
Key Takeaway
🎯 Key Insight: Local inversions are always global inversions, so we only need to check if there are additional global inversions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code