Global and Local Inversions - Problem
You are given an integer array nums of length n which represents a permutation of all integers in the range [0, n-1].
Understanding inversions:
- Global inversion: A pair of indices
(i, j)where0 ≤ i < j < nandnums[i] > nums[j] - Local inversion: An index
iwhere0 ≤ i < n-1andnums[i] > nums[i+1]
Your task is to determine if the number of global inversions equals the number of local inversions.
Key insight: Every local inversion is also a global inversion! The question becomes: are there any global inversions that are NOT local inversions?
Return true if global inversions equal local inversions, false otherwise.
Input & Output
example_1.py — Basic Case
$
Input:
[1, 0, 2]
›
Output:
true
💡 Note:
Global inversions: (0,1) since 1 > 0. Local inversions: (0,1) since nums[0] > nums[1]. Count: 1 = 1, so return true. Also note: |1-0|=1, |0-1|=1, |2-2|=0, all ≤ 1.
example_2.py — False Case
$
Input:
[1, 2, 0]
›
Output:
false
💡 Note:
Global inversions: (0,2) and (1,2) since 1>0 and 2>0, total=2. Local inversions: (1,2) since 2>0, total=1. Since 2 ≠ 1, return false. Also note: |0-2|=2 > 1.
example_3.py — Already Sorted
$
Input:
[0, 1, 2, 3]
›
Output:
true
💡 Note:
Already sorted array has 0 global inversions and 0 local inversions. 0 = 0, so return true. All elements are exactly in their ideal positions.
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Problem
We need to check if global inversions (any two elements out of order) equal local inversions (adjacent elements out of order)
2
Key Mathematical Insight
Every local inversion is automatically a global inversion. So they're equal only if there are no 'far apart' global inversions
3
Position-Based Check
Check if each element nums[i] is within 1 position of its ideal location i. If |nums[i] - i| ≤ 1 for all i, then global equals local
4
Efficient Solution
Single pass through array checking position differences gives O(n) solution instead of O(n²) counting
Key Takeaway
🎯 Key Insight: Since every local inversion is automatically a global inversion, they're equal only when there are no "far apart" global inversions - which happens precisely when each element is at most 1 position away from its ideal sorted location.
Time & Space Complexity
Time Complexity
O(n²)
We check all pairs (i,j) where i < j, which gives us n(n-1)/2 comparisons
⚠ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for counters
✓ Linear Space
Constraints
- n == nums.length
- 1 ≤ n ≤ 105
- 0 ≤ nums[i] < n
- nums is a permutation of [0, 1, 2, ..., n - 1]
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code