class Solution:
def isIdealPermutation(self, A):
# For local == global, no element can be more than 1 away from its sorted position
for i, num in enumerate(A):
if abs(num - i) > 1:
return False
return True
class Solution {
public:
bool isIdealPermutation(vector<int>& A) {
for (int i = 0; i < A.size(); ++i) {
if (abs(A[i] - i) > 1) return false;
}
return true;
}
};
class Solution {
public boolean isIdealPermutation(int[] A) {
for (int i = 0; i < A.length; i++) {
if (Math.abs(A[i] - i) > 1) return false;
}
return true;
}
}
var isIdealPermutation = function(A) {
for (let i = 0; i < A.length; ++i) {
if (Math.abs(A[i] - i) > 1) return false;
}
return true;
};
Given an array A
consisting of distinct integers from 0
to n-1
(a permutation), we define:
(i, j)
such that 0 <= i < j < n
and A[i] > A[j]
.(i, i+1)
such that A[i] > A[i+1]
.A
. In other words, the number of global inversions is equal to the number of local inversions.
Constraints:
1 <= A.length <= 10^5
A
are unique and in the range [0, A.length - 1]
Let's break down what the problem is asking:
j - i > 1
).A[i]
is more than 1 away from i
, it must have swapped with a non-adjacent element, creating a non-local inversion.
A
is a permutation of 0
to n-1
, the "correct" position for k
is k
itself.i
, check if A[i]
is at most 1 away from i
(i.e., abs(A[i] - i) <= 1
).abs(A[i] - i) > 1
, then there must be a global inversion that is not local.True
.This approach is efficient and only requires a single pass through the array.
Let's use the array A = [1, 0, 2]
:
i=0
: A[0]=1
, abs(1-0)=1
(OK)i=1
: A[1]=0
, abs(0-1)=1
(OK)i=2
: A[2]=2
, abs(2-2)=0
(OK)True
.
A = [1, 2, 0]
:
i=0
: A[0]=1
, abs(1-0)=1
(OK)i=1
: A[1]=2
, abs(2-1)=1
(OK)i=2
: A[2]=0
, abs(0-2)=2
(Not OK)0
is two positions away from where it should be, so there is a non-local inversion. The answer is False
.
(i, j)
, check if A[i] > A[j]
. This is O(n^2)
time, which is too slow for large arrays.
abs(A[i] - i) <= 1
for each i
. This is O(n)
time and O(1)
space.
The problem asks whether all global inversions are also local. By realizing that this is only possible when no element is more than one position from its sorted place, we can efficiently solve the problem in a single pass. This elegant solution leverages the properties of permutations and avoids unnecessary counting or nested loops.