LeetCode 1865: Finding Pairs With a Certain Sum Solution

Master LeetCode problem 1865 (Finding Pairs With a Certain Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1865. Finding Pairs With a Certain Sum

Problem Explanation

Explanation

To solve this problem efficiently, we can use a hashmap to store the frequency of sums that can be obtained by adding elements from nums1 and nums2. When we call the count function, we can iterate over nums1, calculate the desired sum (tot - nums1[i]), and check the frequency of this sum in the hashmap. This way, we can count the pairs that satisfy the given sum.

When we add a value to an element in nums2, we need to update the hashmap accordingly.

Solution Code

import java.util.HashMap;
import java.util.Map;

class FindSumPairs {
    Map<Integer, Integer> map;
    int[] nums1;
    int[] nums2;

    public FindSumPairs(int[] nums1, int[] nums2) {
        this.map = new HashMap<>();
        this.nums1 = nums1;
        this.nums2 = nums2;
        
        for (int num : nums1) {
            for (int num2 : nums2) {
                int sum = num + num2;
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
        }
    }

    public void add(int index, int val) {
        int num = nums2[index];
        for (int num1 : nums1) {
            int prevSum = num1 + num;
            int newSum = num1 + num + val;
            map.put(prevSum, map.get(prevSum) - 1);
            map.put(newSum, map.getOrDefault(newSum, 0) + 1);
        }
        nums2[index] += val;
    }

    public int count(int tot) {
        return map.getOrDefault(tot, 0);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1865 (Finding Pairs With a Certain Sum)?

This page provides optimized solutions for LeetCode problem 1865 (Finding Pairs With a Certain Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1865 (Finding Pairs With a Certain Sum)?

The time complexity for LeetCode 1865 (Finding Pairs With a Certain Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1865 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1865 in Java, C++, or Python.

Back to LeetCode Solutions