Lv.2arrayhashtwo-pointers
Count Triplets with Sum T
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums and an integer target, return how many index triples i < j < k satisfy
nums[i] + nums[j] + nums[k] == target. Equal values at different indices count as different triples.
Examples
| nums | target | result |
|---|---|---|
[1, 2, 3, 4, 5] | 9 | 2 |
[0, 0, 0, 0] | 0 | 4 |
[-1, 0, 1, 2, -1, -4] | 0 | 3 |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(nums: int[], target: int) → long
Constraints
-
nums.length -
nums[i],target - Return the count as a 64-bit integer.
Expected complexity
- Time
- O(N^2)
- Space
- O(N)
Examples
| nums | target | Expected |
|---|---|---|
[1,2,3,4,5] | 9 | 2 |
[0,0,0,0] | 0 | 4 |
[-1,0,1,2,-1,-4] | 0 | 3 |
Hint
Hint
Fix the middle index j and keep counts of the values to its left. For every k > j, add left[target - nums[j] - nums[k]],
then add nums[j] to left. That is ; trying all triples is and exceeds the time limit.
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 | 1000 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 | 9 | verdict only |
| performance | 60 | 4 | verdict only |