KatInterview

Count Index Pairs With a Fixed Value Gap

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashinghash-mapcountingfrequency

Last updated

Count index pairs i < j whose values differ by exactly k, using a frequency map and handling the k = 0 case separately to avoid double counting.

Pairs With an Exact Gap

You are given a list of non-negative integers values and a non-negative integer gap.

Count the index pairs (i, j) with i < j for which the two entries differ by exactly gap, that is, abs(values[i] - values[j]) == gap.

Pairs are distinguished by their positions, not by their values. If the same pair of values appears at several different position combinations, each combination counts separately.

Return the total number of such index pairs as an integer.

Special case

When gap = 0, a pair qualifies only if both entries hold the same value, and the two indices must be different. An element is never paired with itself.

Constraints

  • 1 <= len(values) <= 10^5
  • 0 <= values[i] <= 10^9
  • 0 <= gap <= 10^9

Examples

Example 1

Input: count_pairs_with_gap([1, 2, 2, 1], 1)

Output: 4

Example 2

Input: count_pairs_with_gap([1, 5, 3, 4, 2], 2)

Output: 3

Hints

Hint 1

Only the values matter, not their positions. Think about how many times each distinct value occurs, and how to store that.

Hint 2

For gap > 0, every valid pair has a smaller value v and a larger value v + gap. Multiply the number of occurrences of v by the number of occurrences of v + gap, and look only in the upward direction so nothing is counted twice.

Hint 3

gap = 0 needs its own formula. A value occurring f times forms f * (f - 1) / 2 pairs, not f * f.