Problem · Hash Table
Count Cross-Array Target-Sum Pairs
Learn this problemProblem statement
You are given two integer arrays, first and second, and a signed 64-bit integer target.
Return the number of index pairs (i, j) such that first[i] + second[j] = target. Equal values at different indices are distinct occurrences and contribute separately. Compute each sum and the final count in signed 64-bit arithmetic.
Function
countCrossArrayTargetSumPairs(first: int[], second: int[], target: long) → longExamples
Example 1
first = [1,1,2]second = [2,2,3]target = 4return = 4The two occurrences of 1 each pair with 3, and the single 2 pairs with both occurrences of 2.
Example 2
first = []second = [1,2,3]target = 4return = 0No cross-array pair exists when either array is empty.
Example 3
first = [-2,0,2]second = [2,0,-2,2]target = 0return = 4The value -2 pairs with both 2 occurrences, while 0 pairs with 0 and 2 pairs with -2.
Constraints
0 <= first.length, second.length <= 200000.- Every array value is a signed 32-bit integer.
targetis a signed 64-bit integer.- The answer fits a signed 64-bit integer.