LeetCode 170: Two Sum III - Data structure design Solution

Master LeetCode problem 170 (Two Sum III - Data structure design), a easy 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.

170. Two Sum III - Data structure design

Problem Explanation

Explanation:

To design a data structure that supports two operations:

  • add(num): Add the number num to the data structure.
  • find(target): Find if there exist two numbers such that their sum is equal to target.

We can use a hashmap to store the numbers and their frequencies. When adding a number, we store it in the hashmap along with its frequency. When finding a pair that sums up to the target, we iterate through the hashmap and check if target - num exists in the hashmap.

Solution Code

import java.util.HashMap;

class TwoSum {
    private HashMap<Integer, Integer> map;

    public TwoSum() {
        map = new HashMap<>();
    }

    public void add(int num) {
        map.put(num, map.getOrDefault(num, 0) + 1);
    }

    public boolean find(int target) {
        for (int num : map.keySet()) {
            int complement = target - num;
            if ((num == complement && map.get(num) > 1) || (num != complement && map.containsKey(complement))) {
                return true;
            }
        }
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 170 (Two Sum III - Data structure design)?

This page provides optimized solutions for LeetCode problem 170 (Two Sum III - Data structure design) 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 170 (Two Sum III - Data structure design)?

The time complexity for LeetCode 170 (Two Sum III - Data structure design) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 170 on DevExCode?

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

Back to LeetCode Solutions