Global and Local Inversions - Problem

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.

Input & Output

Example 1 — Equal Inversions
$ Input: nums = [1,0,2]
Output: true
💡 Note: Global inversions: (0,1) where 1 > 0. Local inversions: (0,1) where 1 > 0. Both counts are 1, so return true.
Example 2 — Different Inversions
$ Input: nums = [1,2,0]
Output: false
💡 Note: Global inversions: (0,2) where 1 > 0 and (1,2) where 2 > 0 = 2 total. Local inversions: (1,2) where 2 > 0 = 1 total. 2 ≠ 1, so return false.
Example 3 — Already Sorted
$ Input: nums = [0,1,2,3]
Output: true
💡 Note: No inversions of either type exist. 0 == 0, so return true.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] < nums.length
  • nums is a permutation of [0, 1, 2, ..., nums.length - 1]

Visualization

Tap to expand
Global and Local Inversions INPUT Array nums (permutation) 1 i=0 0 i=1 2 i=2 Global Inversion: i < j and nums[i] > nums[j] Local Inversion: nums[i] > nums[i+1] (adjacent) In [1,0,2]: Global: (0,1) -- 1 > 0 Local: (0,1) -- 1 > 0 Count: Both = 1 n = 3 ALGORITHM STEPS 1 Key Observation Every local inversion is also a global inversion 2 Position Constraint For equality: each element must be at most 1 away from its sorted position 3 Check Condition For each i: check if |nums[i] - i| <= 1 4 Verify [1,0,2] i=0: |1-0|=1 <= 1 OK i=1: |0-1|=1 <= 1 OK i=2: |2-2|=0 <= 1 OK All positions valid! O(n) time, O(1) space FINAL RESULT true Global inversions = Local inversions Global Local (0,1): 1>0 (0,1): 1>0 Count: 1 Count: 1 1 == 1 Counts are equal! Output: true Key Insight: If any element is more than 1 position away from its sorted position, it creates a non-local global inversion. The condition |nums[i] - i| <= 1 ensures that all global inversions are also local inversions. This transforms an O(n^2) counting problem into an O(n) position check problem. TutorialsPoint - Global and Local Inversions | Optimized - Check Position Constraint
Asked in
Google 15 Facebook 12
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen