# Two Sum III – Data structure design (Java)

Design and implement a TwoSum class. It should support the following operations: add and find.

find - Find if there exists any pair of numbers which sum is equal to the value.

For example,

```add(1);
find(4) -> true
find(7) -> false
```

Java Solution

Since the desired class need add and get operations, HashMap is a good option for this purpose.

```public class TwoSum { private HashMap<Integer, Integer> elements = new HashMap<Integer, Integer>();   public void add(int number) { if (elements.containsKey(number)) { elements.put(number, elements.get(number) + 1); } else { elements.put(number, 1); } }   public boolean find(int value) { for (Integer i : elements.keySet()) { int target = value - i; if (elements.containsKey(target)) { if (i == target && elements.get(target) < 2) { continue; } return true; } } return false; } }```
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• Michael Brooks

Python3

class TwoSum:
def __init__(self):
self.values = set()

def find_me(self, num):
myNum = num
seen = set()
for val in self.values:
temp = num – val
if temp in self.values:
return True
return False

• Cat Racket

A JavaScript Solution with Youtube Video Explains:

• Ahmed Hamdy

He used hashtable as a frequency table, add will work in O(1) and find will work in O(n)
add: will check if the number already in the table, if so, increment the count by 1, else, add the number to the table.
find: will loop over the table and for each element, he will compute the (element – value), like if the value is 9 and the current element in the loop is 5, then the target should be 9 – 5 = 4, if 4 found in the table, then return true, else, check the next element and so on. If none found, return false.

• Tao Cheng

can anyone explain the solution please

• Soran Ebrahim

Unfortunately TLE, actually I tried this before and out of my luck. So I’m here to see if there’s a better solution, but still unable to find one:(

• kingdaa

Elegant solution.