Global and Local Inversions

viaLeetCode

Problem: Given an array nums of length n which is a permutation of [0, 1, ..., n-1], determine if the number of global inversions equals the number of local inversions. A global inversion is a pair (i, j) with i < j and nums[i] > nums[j]. A local inversion is a global inversion where j = i + 1.

Constraints: Every local inversion is also a global inversion, so the question reduces to: are there any global inversions that are NOT local (i.e. i and j differ by 2 or more)?

Example: Input: nums = [1,0,2] -> Output: true. Input: nums = [1,2,0] -> Output: false (nums[0]=1 > nums[2]=0 is a global inversion but not local).

Approach: O(n) scan checking that for every index i, nums[i] is at most 1 away from i in value (i.e. |nums[i] - i| <= 1); if any element is more than one position out of place, a non-local global inversion exists.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account