Leetcode 775. Global and Local Inversions
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 < n
nums[i] > nums[j]
The number of local inversions is the number of indices i
where:
0 <= i < n - 1
nums[i] > nums[i + 1]
Return true
if the number of global inversions is equal to the number of local inversions.
n
be 0 or 1?
n = 0
, there are no elements, so global and local inversions are trivially equal.n = 1
, no inversions are possible because there’s only one element.0
to n-1
without any duplicates?
0
to n-1
.To solve the problem, consider the definitions of global and local inversions:
Using this, we can deduce that for the number of global inversions to be equal to the number of local inversions, there should be no “non-local” global inversions.
A “non-local” global inversion (i < j, j > i + 1
) would be detected if for any index i
, there exists a j
such that nums[i] > nums[j]
and (j - i) > 1
.
To determine this efficiently, we can keep track of the maximum value encountered up to the element just before the current one. If at any point this maximum value is greater than the current element, it indicates a “non-local” global inversion.
#include <vector>
#include <algorithm>
class Solution {
public:
bool isIdealPermutation(std::vector<int>& nums) {
int max_val = -1;
// Traverse the array
for (int i = 0; i < nums.size() - 2; ++i) {
max_val = std::max(max_val, nums[i]);
if (max_val > nums[i + 2]) {
return false;
}
}
return true;
}
};
n
is the length of the input array nums
.
max_val
update is a constant-time operation.This solution efficiently checks the condition required to determine whether all global inversions are local inversions, ensuring that the algorithm runs in linear time suitable for large inputs.
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?