Finding Pairs With a Certain Sum

MediumArrays & Hashinghashing

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Implement FindSumPairs(nums1, nums2), which holds two integer arrays and supports two operations: - add(index, val) increases nums2[index] by val. - count(tot) returns the number of index pairs (i, j) with nums1[i] + nums2[j] == tot. Pairs are counted by index, so equal values at different positions count separately. nums1 is short and never changes, while nums2 can be long and is updated in place.

Examples

Input: ["FindSumPairs","count","add","count","count","add","count","count"] [[[1,1,2],[1,2,3,3]],[4],[0,2],[4],[5],[1,2],[5],[4]]
Output: [null,5,null,7,3,null,5,6]
Initially 4 = 1+3 (2 ones x 2 threes = 4 pairs) or 2+2 (1 pair), so 5. After nums2[0] becomes 3, nums2 = [3,2,3,3]: 4 is formed 6 + 1 = 7 ways and 5 = 2+3 three ways. After nums2[1] becomes 4, nums2 = [3,4,3,3]: 5 = 1+4 (2) or 2+3 (3) = 5, and 4 = 1+3 six ways.
Input: ["FindSumPairs","count","add","count","count","count"] [[[5],[0,0]],[5],[1,1],[5],[6],[7]]
Output: [null,2,null,1,1,0]
Both zeros pair with 5. After nums2[1] becomes 1, sum 5 has one pair and sum 6 has one pair.

Constraints

  • 1 <= nums1.length <= 1000
  • 1 <= nums2.length <= 10^5
  • 1 <= nums1[i] <= 10^9, 1 <= nums2[i] <= 10^5
  • 0 <= index < nums2.length, 1 <= val <= 10^5
  • 1 <= tot <= 10^9
  • At most 1000 calls each to `add` and `count`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More hashing problems