I was asked an interview question to find the number of distinct absolute values among the elements of the array. I came up with the following solution (in C++) but the interviewer was not happy with the code’s run time efficiency.
- I will appreciate pointers as to how I can improve the run time efficiency of this code?
- Also how do I calculate the efficiency of the code below? The
forloop executesA.size()times. However I am not sure about the efficiency of STLstd::find(In the worse case it could beO(n)so that makes this codeO(n²)?
Code is:
int countAbsoluteDistinct ( const std::vector<int> &A ) {
using namespace std;
list<int> x;
vector<int>::const_iterator it;
for(it = A.begin();it < A.end();it++)
if(find(x.begin(),x.end(),abs(*it)) == x.end())
x.push_back(abs(*it));
return x.size();
}
std::find()is linear (O(n)). I’d use a sorted associative container to handle this, specifically std::set.There is still some runtime penalty with this approach. Using a separate container incurs the cost of dynamic allocations as the container size increases. You could do this in place and not occur this penalty, however with code at this level its sometimes better to be clear and explicit and let the optimizer (in the compiler) do its work.