Java solution for LeetCode Two Sum design problem:
package com.kpatil.leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* Design and implement TwoSum class, to support following methods: add and find
*
* add(input) - add the number input two the internal data structure find(value)
* - find if there exists any pair of numbers which sum is equal to the value
*
* e.g. add(1), add(3), add(5); find(4) -> true, find(7) -> false
*
*/
// Store each input into a hash table with the input as a key
// and it's count (no of times it is added) as value.
// To find if a pair sum exists, just iterate through the hash table in O(n) runtime.
// Make sure to handle duplicates
public class TwoSum {
// O(n) space
private Map lookupTable = new HashMap<>();
// O(1) runtime
public void add(int input) {
int count = lookupTable.containsKey(input) ? lookupTable.get(input) : 0;
lookupTable.put(input, count + 1);
}
// O(n) runtime
public boolean find(int val) {
for (Map.Entry entry : lookupTable.entrySet()) {
int num = entry.getKey();
int diff = val - num;
if (diff == num) {
// for duplicates, make sure there are at least two individual numbers
if (entry.getValue() >= 2)
return true;
} else if (lookupTable.containsKey(diff)) {
return true;
}
}
return false;
}
public void print() {
System.out.println("---------------------------------------------");
for (Map.Entry entry : lookupTable.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
System.out.println("---------------------------------------------");
}
}
JUnit Test:
package com.kpatil.leetcode.test;
import static org.junit.Assert.*;
import org.junit.Test;
import com.kpatil.leetcode.TwoSum;
public class TwoSumTest {
@Test
public void testTwoSum() {
TwoSum twoSum3 = new TwoSum();
twoSum3.add(1);
twoSum3.print();
twoSum3.add(3);
twoSum3.print();
twoSum3.add(5);
twoSum3.print();
twoSum3.add(5);
twoSum3.print();
twoSum3.add(1);
twoSum3.print();
twoSum3.add(10);
twoSum3.print();
boolean found = twoSum3.find(4);
assertEquals(found,true);
boolean notFound = twoSum3.find(7);
assertEquals(notFound,false);
boolean found2 = twoSum3.find(10);
assertEquals(found2,true);
boolean found3 = twoSum3.find(11);
assertEquals(found3,true);
boolean nfound2 = twoSum3.find(12);
assertEquals(nfound2,false);
}
}
No comments:
Post a Comment