Skip to content

775. Global and Local Inversions 👍

Approach 1: Local inversions $\subseteq$ global inversions

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  bool isIdealPermutation(vector<int>& nums) {
    int mx = -1;  // the number that is most likely > nums[i + 2]

    for (int i = 0; i + 2 < nums.size(); ++i) {
      mx = max(mx, nums[i]);
      if (mx > nums[i + 2])
        return false;
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public boolean isIdealPermutation(int[] nums) {
    int mx = -1; // the number that is most likely > nums[i + 2]

    for (int i = 0; i + 2 < nums.length; ++i) {
      mx = Math.max(mx, nums[i]);
      if (mx > nums[i + 2])
        return false;
    }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def isIdealPermutation(self, nums: list[int]) -> bool:
    mx = -1  # the number that is most likely > nums[i + 2]

    for i in range(len(nums) - 2):
      mx = max(mx, nums[i])
      if mx > nums[i + 2]:
        return False

    return True

Approach 2: Ideal permutation

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  bool isIdealPermutation(vector<int>& nums) {
    for (int i = 0; i < nums.size(); ++i)
      if (abs(nums[i] - i) > 1)
        return false;
    return true;
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public boolean isIdealPermutation(int[] nums) {
    for (int i = 0; i < nums.length; ++i)
      if (Math.abs(nums[i] - i) > 1)
        return false;
    return true;
  }
}
1
2
3
4
5
6
class Solution:
  def isIdealPermutation(self, nums: list[int]) -> bool:
    for i, num in enumerate(nums):
      if abs(num - i) > 1:
        return False
    return True