Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Count Number Of Pairs With Absolute Difference K

Count the number of index pairs whose values differ by exactly k.

Acceptance 0%
Problem Statement

Problem

Given an integer array nums and an integer k, count how many index pairs (i, j) satisfy:

  • i < j
  • |nums[i] - nums[j]| = k

Your task is to return the total number of such pairs.

A pair is counted by index, so two equal values at different positions can contribute multiple pairs.

Input Format

  • An integer array nums
  • An integer k

The exact platform input format may vary, but the core task is to count pairs of indices with absolute difference k.

Output Format

Return an integer: the number of index pairs (i, j) such that i < j and |nums[i] - nums[j]| = k.

Constraints

  • 0 <= k
  • Count pairs by index, not by distinct values.
  • If k = 0, only equal-value pairs contribute.
  • Use integer arithmetic for counting; the answer may exceed the range of a 32-bit signed integer in some variants.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 2, 2, 1], k = 1

Output

4

Explanation

Valid pairs are (1st 1, first 2), (1st 1, second 2), (second 1, first 2), and (second 1, second 2).

Example 2

Input

nums = [1, 3, 5, 8], k = 2

Output

2

Explanation

The valid pairs are (1, 3) and (3, 5).

Show 1 more example

Example 3

Input

nums = [1, 1, 1, 1], k = 0

Output

6

Explanation

Every pair of equal values counts, so the answer is C(4, 2) = 6.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.