#775

Global and Local Inversions

Medium
ArrayMathArraySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the properties of the permutation to determine if the number of global inversions equals local inversions without explicitly counting all pairs. If an element is more than two positions ahead of its original position, it creates a global inversion without being a local inversion.

⚙️

Algorithm

2 steps
  1. 1Step 1: Loop through the array and check if any element nums[i] is greater than i + 1. If yes, return false.
  2. 2Step 2: If all elements satisfy the condition, return true.
solution.py5 lines
1def isIdealPermutation(nums):
2    for i in range(len(nums)):
3        if nums[i] > i + 1:
4            return False
5    return True

Complexity note: The time complexity is O(n) because we only make a single pass through the array. The space complexity is O(1) since we use no additional data structures.

  • 1Global inversions include local inversions, but not all global inversions are local inversions.
  • 2If any element is more than one position away from its original index, it creates a global inversion without being a local inversion.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.