Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count pairs with difference k

Count how many index-pairs in an array have an absolute difference equal to k.

Python practice15 minArrays – Fundamentals & PatternsIntermediateLast updated March 25, 2026

Problem statement

Given an array of integers nums and an integer k (k >= 0), return the number of index pairs (i, j) with i < j such that abs(nums[i] - nums[j]) == k. The function should handle duplicates correctly and run efficiently for large arrays.

Task

Implement an efficient function to count index pairs (i < j) where |nums[i] - nums[j]| == k.

Examples

Basic example

Input

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

Output

3

Pairs with difference 2: (1,3), (3,5), (2,4).

Input format

Function signature: count_pairs_with_diff_k(nums: list[int], k: int) -> int

Output format

Return an integer: the count of index pairs (i < j) with absolute difference == k.

Constraints

0 <= len(nums) <= 10^5, -10^9 <= nums[i] <= 10^9, k >= 0. Expected O(n) or O(n log n) time, O(n) extra space.

Samples

Sample 1

Input

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

Output

4

Three 1s -> 3 pairs, two 2s -> 1 pair, total 4.