Skip to content
Problem 775 · LeetCode 775(opens in a new tab)

Global and Local Inversions

MediumArrays

nums holds each number from 0 to n − 1 exactly once. A global inversion is any pair of indices i < j with nums[i] > nums[j]. A local inversion is the special case where j = i + 1: a neighbour pair in the wrong order.

Return true if the array has the same number of global and local inversions, and false otherwise.

Example 1

Input:  nums = [1, 0, 3, 2]
Output: true
Why:    2 global inversions, both between neighbours
2 more examples and the constraints

Example 2

Input:  nums = [2, 0, 1]
Output: false
Why:    2 global (2>0, 2>1) but only 1 local

Example 3

Input:  nums = [0]
Output: true
Why:    no inversions of either kind

Constraints

  • 1 ≤ n ≤ 100,000
  • 0 ≤ nums[i] < n
  • nums is a permutation of 0 to n − 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every far pairO(n²)
  2. Running max two places backO(n)
  3. Each value near its indexO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Check every far pairO(n²)
Too slow at the limit
Running max two places backO(n)
Passes; works on any array
Each value near its indexO(n)
Best; uses the permutation

n = length of nums.

Edge cases to test

  • One or two numbers. Always true: no pair can be two apart.
  • Already sorted. Zero of each kind, so true.
  • Disjoint neighbour swaps. [1, 0, 3, 2, 4] is true.
  • Chained swaps. [1, 2, 0] is false: 0 is two places from home.
  • Fully reversed, n ≥ 3. [2, 1, 0] is false.

Common mistakes

  • Counting global inversions with a double loop at n = 100,000, which times out.
  • Checking only neighbours, which never sees a far inversion like (2, 1) in [2, 0, 1].
  • Using |nums[i] − i| ≤ 1 on an array that is not a permutation, where it does not hold.

How to talk through it

  1. 1Clarify. Is nums always a permutation of 0..n−1? How large can n get?
  2. 2Reframe. Local inversions are a subset of global ones, so look only for inversions two or more apart.
  3. 3Give the O(n²) check. Every pair j ≥ i + 2; too slow at 100,000.
  4. 4Reduce to O(n). Keep the max up to i − 2, or use the permutation: every value within one of its index.
  5. 5Test out loud. Run [1, 0, 3, 2] (true) and [1, 2, 0] (false).
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?