Python coding

Pairs with mismatched gaps

Given a list of integers nums, count the index pairs i < j whose values move by a different amount than their positions do: nums[j] - nums[i] != j - i. For [3, 7, 5, 6] the answer is 3: the three pairs that use index 1 (the 7) are out of step, and every other pair matches.

nums may be empty and may hold negatives. Checking every pair is O(n²): aim for one pass.

Besides the tests, one large input (4,500 numbers) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • mismatched_pairs([3,7,5,6]) → 3
  • mismatched_pairs([1,2,3,4,5]) → 0
  • mismatched_pairs([5,5,5]) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Counting the pairs that do match is easier, and every pair is one or the other: there are j pairs that end at index j.

Hint 2

Rewrite nums[j] - nums[i] == j - i as nums[i] - i == nums[j] - j: two indexes match exactly when they share the key nums[k] - k.

Hint 3

Walk once with a map from each key to how many earlier indexes had it. At index j, the earlier indexes that don't share its key are the mismatched pairs ending at j.

Solution and why it works
pythonO(n) · O(n)
def mismatched_pairs(nums: list[int]) -> int:
    seen = {}                       # nums[i] - i -> how many earlier indexes share it
    total = 0
    for j, x in enumerate(nums):
        key = x - j                 # nums[j] - nums[i] == j - i  <=>  same key
        total += j - seen.get(key, 0)   # earlier indexes, minus the ones that match
        seen[key] = seen.get(key, 0) + 1
    return total

The condition mixes both indexes, so no map can answer it as written. Moving each index to its own side, nums[i] - i == nums[j] - j, turns matching into sharing a key, and a map of key counts tells how many earlier indexes match j. The other j - seen[key] earlier indexes are mismatched. Rearranging a pair condition until each side depends on one index is the move to remember; checking all pairs is the O(n²) trap.

Related lab: Loops in motion