Funcia
Lv.1countinghashsorting

Pairs with Difference K

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Given an integer array nums and an integer k, return the number of index pairs i < j with ∣|nums[i] −- nums[j]∣=k| = k. Equal values at different positions are different elements. The answer may exceed the 32-bit range.

Examples

numskresult
[1, 5, 3, 4, 2]23
[1, 1, 1, 2]13
[3, 3, 3]03

Example 3 — with k = 0 the pairs are equal values: 3 ways to choose two of the three elements.

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(nums: int[], k: int) → long

Constraints

  • 1≤1 \le nums.length ≤200,000\le 200{,}000
  • 0≤0 \le nums[i] ≤109\le 10^9
  • 0≤0 \le k ≤109\le 10^9

Expected complexity

Time
O(N log N)
Space
O(N)

Examples

numskExpected
[1,5,3,4,2]23
[1,1,1,2]13
[3,3,3]03

Hint

Hint

Count each value in a hash map; values x (count c) and x + k (count d) form c × d pairs, and summing over distinct x counts each pair once. Handle k = 0 separately with c(c−1)2\frac{c(c-1)}{2} per value. Sorting plus two pointers also works. Checking every pair is O(N2)O(N^2) and exceeds the time limit; use a 64-bit result.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251182 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4011verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.