Thursday, December 25, 2014

Two Sum III - Data structure design (LeetCode HashMap)

Question:  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,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false

Idea: Since duplicate insertion is allowed, e.g. "add(4) add(4) find(8) = true, but add(4) find(8) =false", we need to count the times of insertion of each inserted value. I used a Hashmap <value, inserted times> to store the inserted numbers. If a desired pair is found, check if the HashMap has enough number of insertions, otherwise "continue".

Time: O(1) for add. O(n) for find. Space: O(n)

Discussion: To use less space, I design the algorithm as Time O(1) for add and Time O(n) for find. If we need Time O(1) for find, we can add another HashSet to store the possible sums whenever a new number is inserted. Therefore it will be Time O(n) for add, Time O(1) for find, and Space is O(n^2).

Code:
 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 needed=value-i;  
          if(elements.containsKey(needed))  
          {  
            if(i==needed&&elements.get(needed)<2)  
            {  
              continue;  
            }  
            return true;  
          }  
        }  
        return false;  
      }  
 }  



No comments:

Post a Comment