I was given a problem to solve in O(n)
time complexity :
"Given a list of numbers and number x. Find if there any 2 numbers in the list that add up to x?"
And this is my solution :
public class SumMatchResult {
public static void main(String[] args){
int[] numberList = {6,1,8,7,4,6};
int requiredSum = 8;
boolean isSumPresent = checkSumPresentHash(numberList,requiredSum);
if(isSumPresent) {
System.out.println("Numbers exist");
}else {
System.out.println("Numbers donot exist");
}
}
private static boolean checkSumPresentHash(int[] numberList, int requiredSum) {
Map<Integer, Integer> m = new HashMap<Integer,Integer>();
int count = 0;
for(int i=0;i<numberList.length;i++){
m.put(i, numberList[i]);
}
for(int i=0;i<numberList.length;i++){
if(m.containsValue(requiredSum - numberList[i])){
count++;
}
}
if(count>1){
return true;
}
return false;
}
}
I am using HashMap.containsValue()
instead of using a HashSet.contains()
which surely has a complexity of O(1)
because, I have to account for the scenario where my input might contain identical values. For example, in the above case, I can have a set of input values {3,6,4,4,7}
to be matched for the sum 8
, which should return true
.
My above solution's time complexity depends on the complexity of HashMap.containsValue()
method. Please shed some light on the time complexity of containsValue()
method and suggest me if there is any better solution for the above problem in terms of time complexity. Thank you.