Lv.1countinghashsorting
Pairs with Difference K
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums and an integer k, return the number of index pairs i < j with
nums[i] nums[j]. Equal values at different positions are different elements. The answer may exceed the
32-bit range.
Examples
| nums | k | result |
|---|---|---|
[1, 5, 3, 4, 2] | 2 | 3 |
[1, 1, 1, 2] | 1 | 3 |
[3, 3, 3] | 0 | 3 |
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
-
nums.length -
nums[i] -
k
Expected complexity
- Time
- O(N log N)
- Space
- O(N)
Examples
| nums | k | Expected |
|---|---|---|
[1,5,3,4,2] | 2 | 3 |
[1,1,1,2] | 1 | 3 |
[3,3,3] | 0 | 3 |
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 per value. Sorting plus two pointers also works.
Checking every pair is and exceeds the time limit; use a 64-bit result.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1182 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 11 | verdict only |
| performance | 60 | 4 | verdict only |