LeetCode Problem Workspace

Finding Pairs With a Certain Sum

Efficiently track and count pairs across two arrays using array scanning plus hash lookup to support dynamic updates.

category

3

Topics

code_blocks

8

Code langs

hub

3

Related

Practice Focus

Medium · Array scanning plus hash lookup

bolt

Answer-first summary

Efficiently track and count pairs across two arrays using array scanning plus hash lookup to support dynamic updates.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Array scanning plus hash lookup

Try AiBox Copilotarrow_forward

This problem requires implementing a data structure that efficiently counts the number of pairs between two arrays that sum to a target value. The key pattern is array scanning plus hash lookup, leveraging the fact that nums1 is smaller than nums2 for faster queries. Updates to nums2 must also be handled without recomputing all pairs, making hash maps essential for maintaining counts dynamically.

Problem Statement

You are given two integer arrays, nums1 and nums2. Implement a class FindSumPairs that supports adding values to nums2 and counting the number of pairs where an element from nums1 plus an element from nums2 equals a target sum.

The FindSumPairs class must implement a constructor to initialize the arrays, an add method to increment elements of nums2 by a value at a given index, and a count method to return the total number of valid pairs for a given sum. Optimize for multiple calls where nums1 is smaller than nums2.

Examples

Example 1

Input: See original problem statement.

Output: See original problem statement.

Input ["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"] [[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]] Output [null, 8, null, 2, 1, null, null, 11]

Explanation FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]); findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4 findSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4] findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5 findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1 findSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4] findSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4] findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4

Constraints

  • 1 <= nums1.length <= 1000
  • 1 <= nums2.length <= 105
  • 1 <= nums1[i] <= 109
  • 1 <= nums2[i] <= 105
  • 0 <= index < nums2.length
  • 1 <= val <= 105
  • 1 <= tot <= 109
  • At most 1000 calls are made to add and count each.

Solution Approach

Use Hash Map for nums2 Counts

Create a hash map to store the frequency of each number in nums2. This allows constant-time access to counts when computing sums with nums1 elements.

Scan nums1 Against Hash Map

For count queries, iterate through nums1 and for each element compute the complement to reach the target sum. Look up the complement in the nums2 hash map to get the number of valid pairs efficiently.

Update nums2 Efficiently

When adding a value to nums2 at an index, update the hash map by decrementing the old value count and incrementing the new value count. This keeps count queries fast without rescanning the entire array.

Complexity Analysis

Metric Value
Time O(n + m + q_1 + q_2 \cdot n)
Space O(n + m)

Initialization takes O(n + m) time and space. Each add operation is O(1) due to hash map updates. Count queries take O(n) time by scanning nums1 and performing hash lookups into nums2 counts.

What Interviewers Usually Probe

  • Are you leveraging the fact that nums1 is smaller than nums2 to optimize count queries?
  • Can you maintain counts in a hash map without recomputing all pairs after each add?
  • How would your approach change if nums2 was updated frequently and nums1 was very large?

Common Pitfalls or Variants

Common pitfalls

  • Recomputing all pairs on every count query instead of using the hash map for efficient lookup.
  • Failing to update the hash map correctly when adding values to nums2, leading to incorrect counts.
  • Ignoring integer overflow or assuming nums1 and nums2 have similar lengths, reducing efficiency.

Follow-up variants

  • Allow both nums1 and nums2 to be updated dynamically, requiring two hash maps.
  • Count pairs within a single array instead of between two arrays, changing the scanning logic.
  • Support finding pairs that satisfy a product or difference condition instead of sum, altering the complement calculation.

FAQ

What is the main pattern used in Finding Pairs With a Certain Sum?

The primary pattern is array scanning plus hash lookup, leveraging the small size of nums1 against nums2 for efficient counting.

How should I handle multiple add operations efficiently?

Update the hash map by decrementing the old value count and incrementing the new value count to maintain fast count queries.

Why not scan nums2 directly for every count query?

Scanning nums2 repeatedly is inefficient because it is large. Using a hash map reduces the query time to O(n) where n is nums1 length.

Does the order of nums1 or nums2 matter?

No, the order does not matter since pairs are counted based on value sums, not indices, and hash maps track frequencies.

Can this approach handle large integers in nums1 or nums2?

Yes, the approach uses hash maps to store counts, so it can handle large integer values as long as they are within constraints.

terminal

Solution

Solution 1: Hash Table

We note that the length of the array $\textit{nums1}$ does not exceed ${10}^3$, while the length of the array $\textit{nums2}$ reaches ${10}^5$. Therefore, if we directly enumerate all index pairs $(i, j)$ and check whether $\textit{nums1}[i] + \textit{nums2}[j]$ equals the specified value $\textit{tot}$, it will exceed the time limit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class FindSumPairs:

    def __init__(self, nums1: List[int], nums2: List[int]):
        self.cnt = Counter(nums2)
        self.nums1 = nums1
        self.nums2 = nums2

    def add(self, index: int, val: int) -> None:
        self.cnt[self.nums2[index]] -= 1
        self.nums2[index] += val
        self.cnt[self.nums2[index]] += 1

    def count(self, tot: int) -> int:
        return sum(self.cnt[tot - x] for x in self.nums1)


# Your FindSumPairs object will be instantiated and called as such:
# obj = FindSumPairs(nums1, nums2)
# obj.add(index,val)
# param_2 = obj.count(tot)
Finding Pairs With a Certain Sum Solution: Array scanning plus hash lookup | LeetCode #1865 Medium