Leetcode 775. Global and Local Inversions
You are given an integer array A
of length n
, containing all the integers from 0
to n-1
in some order. A global inversion is defined as a pair (i, j)
where 0 <= i < j < n
and A[i] > A[j]
.
A local inversion is defined as a pair (i, j)
where 0 <= i < j < n
, j = i + 1
, and A[i] > A[j]
.
Return true
if the number of global inversions is equal to the number of local inversions, and false
otherwise.
(i, j)
where j > i + 1
should not exist. This means that the array should almost be sorted except for the local inversions.i - 2
.A[i] < max(A[0]...A[i-2])
, this means there is a global inversion that is not a local inversion.max_value
to track the maximum value up to A[i-2]
.A[i]
that is less than max_value
.public class Solution {
public boolean isIdealPermutation(int[] A) {
int n = A.length;
int max_value = A[0];
// We start from the index 2 onwards
for (int i = 2; i < n; i++) {
if (A[i] < max_value) {
return false;
}
max_value = Math.max(max_value, A[i-1]);
}
return true;
}
}
This approach ensures that we efficiently check the required conditions, leveraging the insight that any global inversion that isn’t local invalidates our condition.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?