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.
- Check every far pairO(n²)
- Running max two places backO(n)
- Each value near its indexO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Check every far pair | O(n²) | Too slow at the limit | |
| Running max two places back | O(n) | Passes; works on any array | |
| Each value near its index | O(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
- 1Clarify. Is nums always a permutation of 0..n−1? How large can n get?
- 2Reframe. Local inversions are a subset of global ones, so look only for inversions two or more apart.
- 3Give the O(n²) check. Every pair j ≥ i + 2; too slow at 100,000.
- 4Reduce to O(n). Keep the max up to i − 2, or use the permutation: every value within one of its index.
- 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?