Lv.1countinghashmath
Pairs with Sum Divisible by K
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given non-negative integers nums and a positive k, count pairs i < j with nums[i] + nums[j] divisible by k.
Examples
| nums | k | result |
|---|---|---|
[2, 4, 1, 5, 3] | 3 | 4 |
[6, 6, 6] | 4 | 3 |
[1, 2] | 5 | 0 |
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 - The answer can exceed 32 bits.
Expected complexity
- Time
- O(N)
- Space
- O(N)
Examples
| nums | k | Expected |
|---|---|---|
[2,4,1,5,3] | 3 | 4 |
[6,6,6] | 4 | 3 |
[1,2] | 5 | 0 |
Hint
Hint
Only remainders matter: a value with remainder r pairs with remainder (k - r) % k. Sweep once with a hash map of remainder
counts (k is too large for an array). Checking all pairs is .
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 | 1172 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 | 8 | verdict only |
| performance | 60 | 4 | verdict only |