Problem · Hash Table

Count Cross-Array Target-Sum Pairs

Learn this problem
EasyVisa logoVisaNEW GRADOA

Problem 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) → long

Examples

Example 1

first = [1,1,2]second = [2,2,3]target = 4return = 4

The 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 = 0

No cross-array pair exists when either array is empty.

Example 3

first = [-2,0,2]second = [2,0,-2,2]target = 0return = 4

The 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.
  • target is a signed 64-bit integer.
  • The answer fits a signed 64-bit integer.

More Visa problems

drafts saved locally
public long countCrossArrayTargetSumPairs(int[] first, int[] second, long target) {
  // write your code here
}
first[1,1,2]
second[2,2,3]
target4
expected4
checking account