Problem Description
Given an array nums which is a permutation of [0, n - 1], count the number of global inversions (pairs (i, j) such that i < j and nums[i] > nums[j]) and local inversions (indices i such that nums[i] > nums[i+1]). Return true if they are equal; otherwise, false.
Key Insights
- Every local inversion is a global inversion.
- For the counts to be equal, all global inversions must be local inversions.
- A global inversion that is not local exists if an element is placed more than one position away from its index.
- It is sufficient to check if the element's value differs from its index by more than 1.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1)
Solution
The idea is to iterate through the array and for each index check if the absolute difference between the element value and its index is more than one. If any element is displaced by more than one position, there exists a non-local global inversion and we return false. If no such element is found, return true. This approach leverages a simple linear scan and a constant extra space check, ensuring both optimal time and space complexity.