Two Sum III – Data structure design (Java)

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

add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.

For example,

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) {
				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:
String foo = "bar";

  1. kingdaa on 2015-5-31

    Elegant solution.

  2. Soran Ebrahim on 2015-9-30

    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:(

  3. Tao Cheng on 2017-3-5

    can anyone explain the solution please

Leave a comment