All problems
0699EasyArrayHash TableCounting

Counting Label Pairs at a Fixed Gap

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2006Count Number of Pairs With Absolute Difference K

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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