#1865

Finding Pairs With a Certain Sum

Medium
ArrayHash TableDesignHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(m)
💡

Intuition

Time O(n + m)Space O(m)

Instead of checking every pair, we can use a HashMap to count occurrences of numbers in nums2. This allows us to quickly find how many numbers in nums2 can pair with each number in nums1 to reach the target sum.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a HashMap to store the frequency of each number in nums2.
  2. 2Step 2: For the count method, iterate through nums1 and for each element, calculate the required complement (tot - num1).
  3. 3Step 3: Use the HashMap to get the frequency of the complement in nums2.
  4. 4Step 4: Sum these frequencies to get the total count of pairs.
  5. 5Step 5: For the add method, update the HashMap with the new value.
solution.py18 lines
1from collections import Counter
2
3class FindSumPairs:
4    def __init__(self, nums1, nums2):
5        self.nums1 = nums1
6        self.nums2 = nums2
7        self.counter = Counter(nums2)
8
9    def add(self, index, val):
10        self.counter[self.nums2[index]] -= 1
11        self.nums2[index] += val
12        self.counter[self.nums2[index]] += 1
13
14    def count(self, tot):
15        count = 0
16        for num1 in self.nums1:
17            count += self.counter[tot - num1]
18        return count

Complexity note: The time complexity is O(n + m) because we build the frequency map in O(m) and then count pairs in O(n). The space complexity is O(m) for storing the frequency of elements in nums2.

  • 1Using a HashMap allows for quick lookups, significantly reducing the time complexity.
  • 2The problem can be viewed as a counting problem where we need to efficiently count complements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.