Show problems as
Classic problem #2006EasyArrayHash TableCounting

Count Number of Pairs With Absolute Difference K

Real-world version: Counting Label Pairs at a Fixed Gap
Tracked in this browser only
Read Count Number of Pairs With Absolute Difference K on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A shelf of parts is described by labels, where labels[i] is the number printed on the part in slot i. Two different slots i and j form a matched pair when the two printed numbers differ by exactly gap, that is when abs(labels[i] - labels[j]) == gap.

Return how many matched pairs of slots the shelf holds. A pair of slots counts once, regardless of which slot you name first, and two slots printed with the same number are still two different slots.

Examples

Example 1

Input
labels = [3, 3, 3, 6, 6], gap = 3
Output
6

Each of the three slots printed `3` pairs with each of the two slots printed `6`, since those numbers differ by `3`. Two slots printed with the same number differ by `0`, so they never pair here.

Example 2

Input
labels = [4, 9, 4, 9, 4], gap = 5
Output
6

Three slots carry `4` and two carry `9`, and `9 - 4` is `5`, so every one of those slot combinations is a matched pair.

Example 3

Input
labels = [10, 20, 30, 40], gap = 10
Output
3

The matched pairs are the slots printed `10` and `20`, `20` and `30`, and `30` and `40`. Slots printed `10` and `30` differ by `20`, so they do not count.

Constraints

  • 1 <= labels.length <= 200
  • 1 <= labels[i] <= 100
  • 1 <= gap <= 99

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def count_gap_pairs(labels: list[int], gap: int) -> int:
Java
public int countGapPairs(int[] labels, int gap)