</>

1865. Finding Pairs With a Certain Sum

Medium
Arrays & Hashing Space O(N1+N2)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Arrays & Hashing
Time
—
Space
O(N1+N2)

Standard Solution (C++)

SummaryDesign a data structure that holds two integer arrays and supports two operations: incrementing an element in the second array by a given value, and counting how many index pairs (i, j) across both arrays sum to a given target total.

Approach
  • Store nums2 as a mutable array and maintain a frequency map for it; build a separate frequency map for nums1 (which never changes).
  • add(index, val): decrement the old value's count, apply the increment to nums2[index], then increment the new value's count — O(1) per update.
  • count(tot): iterate over every unique value x in nums1's frequency map and accumulate freq1[x] * freq2[tot - x]; this avoids scanning nums2 on every query.
  • Because nums1 is read-only, its frequency map is built once at construction and never touched again, keeping the hot-path cheap.
#include <vector>
#include <unordered_map>
using namespace std;

class FindSumPairs {
public:
    FindSumPairs(vector<int>& nums1, vector<int>& nums2)
        : nums2_(nums2)
    {
        // nums1 never changes — build its freq map once
        for (int x : nums1) ++freq1_[x];
        // nums2 can be updated — keep freq map in sync
        for (int x : nums2) ++freq2_[x];
    }

    // Increment nums2[index] by val; keep freq2_ consistent
    void add(int index, int val) {
        --freq2_[nums2_[index]];   // remove old value
        nums2_[index] += val;
        ++freq2_[nums2_[index]];   // record new value
    }

    // Count pairs (i,j) where nums1[i] + nums2[j] == tot
    int count(int tot) {
        int res = 0;
        for (auto& [x, fx] : freq1_) {
            int need = tot - x;
            auto it = freq2_.find(need);
            if (it != freq2_.end())
                res += fx * it->second;
        }
        return res;
    }

private:
    vector<int> nums2_;                 // mutable copy of nums2
    unordered_map<int,int> freq1_;      // frequency of nums1 values (static)
    unordered_map<int,int> freq2_;      // frequency of nums2 values (dynamic)
};

/**
 * Your FindSumPairs object will be instantiated and called as such:
 * FindSumPairs* obj = new FindSumPairs(nums1, nums2);
 * obj->add(index, val);
 * int param_2 = obj->count(tot);
 */
Time Constructor: O(N1 + N2) average; add: O(1) average; count: O(U1) average where U1 is the number of distinct values in nums1 Space O(N1 + N2) for the frequency maps and the stored copy of nums2

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class FindSumPairs {
public:
    vector<int> v1, v2;
    unordered_map<int, int> umap1, umap2;

    FindSumPairs(vector<int>& nums1, vector<int>& nums2): v1(nums1), v2(nums2) {
        for(const int n: v1){
            ++umap1[n];
        }
        for(const int n: v2){
            ++umap2[n];
        }
    }
    
    void add(int index, int val) {
        --umap2[v2[index]];
        v2[index]+=val;
        ++umap2[v2[index]];
    }
    
    int count(int tot) {
        int res=0;
        for(auto const& [num, freq]: umap1){
            res+=freq*(umap2[tot-num]);
        }
        return res;
    }
};

// 
// Time Complexity
// FindSumPairs: O(N1 + N2) on average
// add: O(1) on average
// count: O(U1) on average, where U1 is the number of unique elements in nums1
// 
// Space Complexity: O(N1+N2)

/**
 * Your FindSumPairs object will be instantiated and called as such:
 * FindSumPairs* obj = new FindSumPairs(nums1, nums2);
 * obj->add(index,val);
 * int param_2 = obj->count(tot);
 */
Space O(N1+N2)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern