Tuesday, January 4, 2011

In an array find two numbers that add up to a given value X

As part of researching into regular math questions asked in interview, I stumbled upon this simple data structure question of "from an array of integers, given an input x, how do you find two numbers that add up to X.

The basic algorithm to find two numbers that add up to X:
declare hash
for each element in the array
diff = current_element - X
if(!hash.contains(current_element))
hash.put(current_element, diff);
end if
if(hash.contains(diff))
the two numbers are current_element, diff
end if
end for

Here is the tested java code for the same:

public class IntegerArrayTest {
public static final int[] int_array =
{1,2,3,4,5,6,7,8,9,10};
public static java.util.Hashtable intHash =
new java.util.Hashtable();
public static String getResult(int x_number) {
for (int i=0;i int current_element = int_array[i];
int diff = 0;
if( x_number > current_element)
diff = x_number - current_element;
else
diff = current_element - x_number;
if(!intHash.containsKey(current_element)) {
//just add it in
intHash.put(current_element, diff);
}
if(intHash.containsKey(diff)){
//out quest stops here
return new StringBuffer("The numbers are ").
append(current_element).append(" and ").
append(diff).toString();
}
}
return "Did not find mathing number";
}
public static void main(String args[]) {
String x_number = args[0];
String result =
IntegerArrayTest.getResult(
Integer.parseInt(x_number));
System.out.println(result);
}
}

There you go, thats my take on that algorithm. Let me know how it can be enhanced.

No comments:

Post a Comment