I have a question about the time complexity of the solution for the "two number sum" problem. You get an array of integer numbers and should return true if any two distinct numbers in the array sum up to a defined target sum or not.
The problem can be found here: https://leetcode.com/problems/two-sum/
Here is one possible solution:
vector<int> twoSum(vector<int> &numbers, int target)
{
//Key is the number and value is its index in the vector.
unordered_map<int, int> hash;
vector<int> result;
for (int i = 0; i < numbers.size(); i++) {
int numberToFind = target - numbers[i];
//if numberToFind is found in map, return them
if (hash.find(numberToFind) != hash.end()) {
//+1 because indices are NOT zero based
result.push_back(hash[numberToFind] + 1);
result.push_back(i + 1);
return result;
}
//number was not found. Put it in the map.
hash[numbers[i]] = i;
}
return result;
}
The "for loop" time complexity is O(n) because it goes through n array elements. The find() function's average time complexity is O(1). You look into that here: http://www.cplusplus.com/reference/unordered_map/unordered_map/find/ Since 1 * n is still n, the average case time complexity is still just O(n).
I thought when we talk about time complexity we always mean the worst-case time complexity. Operations on a hash map are then O(n) or at least O(log n).
In a coding interview would you say the algorithm above runs in O(n^2) or O(n)?