Funcia
Lv.2arrayhashtwo-pointers

Count Triplets with Sum T

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
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

numstargetresult
[1, 2, 3, 4, 5]92
[0, 0, 0, 0]04
[-1, 0, 1, 2, -1, -4]03

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

  • 3≤3 \le nums.length ≤3,000\le 3{,}000
  • −100,000≤-100{,}000 \le nums[i] ≤100,000\le 100{,}000, −300,000≤-300{,}000 \le target ≤300,000\le 300{,}000
  • Return the count as a 64-bit integer.

Expected complexity

Time
O(N^2)
Space
O(N)

Examples

numstargetExpected
[1,2,3,4,5]92
[0,0,0,0]04
[-1,0,1,2,-1,-4]03

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 O(N2)O(N^2); trying all triples is O(N3)O(N^3) and exceeds the time limit.

Time limits per language

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

Test groups

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

No result yet. Run or submit your code.