Finding Pairs With a Certain Sum — LeetCode 1865 Python Solution
- Problem
- #1865
- Pattern
- Hash Map
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Add a positive integer to an element of a given index in the array nums2.
Example
- Input
- ["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"]
- 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]);
Python solution
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)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times q) |
| Space | O(m) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1865. Finding Pairs With a Certain Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1865. Finding Pairs With a Certain Sum?
- LeetCode 1865. Finding Pairs With a Certain Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1865. Finding Pairs With a Certain Sum?
- The Python solution on this page runs in O(n \times q).
- What is the space complexity of LeetCode 1865. Finding Pairs With a Certain Sum?
- The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 1865. Finding Pairs With a Certain Sum cover?
- LeetCode 1865. Finding Pairs With a Certain Sum is tagged Design, Array and Hash Table on LeetCode.