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";
  • alexwest11

    put all numbers in hash.

    for each number in hash, find in hash [value- number], if yes. such pair exist!

    no need any freq table. !! it is misleading. we need put counter if in array [1 2 4 3 4 ] we are looking for 8
    , so need to know exist 2 of them.

    so instead of incr, if exist already, put any number not 1. thus we know it is more than 1 of 4!

  • alexwest11

    elements.put(number, elements.get(number) + 1);

    this line is confusing. no need one! just put 2 or anything not 1 . that’s all

    it is done to find in [1 2 4 3 4 ] value 8.

  • Michael Brooks


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

    def add_me(self, num):

    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.