You are given an integer array nums
of length n
, where nums
is a permutation of the numbers 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]
Given an array nums
, return true
if the number of global inversions is equal to the number of local inversions.
nums
?
nums
will always be a permutation of numbers [0, n-1]
?
[0]
or [1, 0]
.def isIdealPermutation(nums):
n = len(nums)
# Checking the main condition for ideal permutation
for i in range(n):
# If a number is found whose position difference is more than 1
# it means there is a global inversion which is not local
# since local inversions must be between adjacent numbers
if abs(nums[i] - i) > 1:
return False
return True
# Example Usage
print(isIdealPermutation([1, 0, 2])) # Output should be True
print(isIdealPermutation([1, 2, 0])) # Output should be False
The key insight here is to recognize that for the number of global inversions to be equal to the number of local inversions, there cannot be any global inversions that are not local. In other words, every inversion must be between adjacent elements.
For each element nums[i]
in the array nums
, the ideal position it should be in is i
because it’s a permutation of [0, n-1]
. If nums[i]
is off by more than 1 position from i
, then there is a global inversion that is not a local inversion.
The time complexity of this solution is O(n) where n is the number of elements in nums
. This is because we are iterating through the array once performing a constant time check for each element. The space complexity is O(1) as we are using a constant amount of additional space.
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?