this is my first StackOverflow question so please let me know if I didn't follow community guidelines with this question and if I should delete it.
I got my first ever interview question and I got rejected because of my implementation.
The question is:
Design and implement a C++ class that stores a collection of integers. On construction, the collection should be empty. The same number may be stored more than once.
Implement the following methods:
Insert(int x). Insert an entry for the value “x”.
Erase(int x). Remove one entry with the value “x” (if one exists) from the collection.
Erase(int from, int to). Remove all the entries with a value in the range [from, to).
Count(int from, int to). Count how many entries have a value in the range [from, to).
I thought a good implementation would be to use linked lists since it uses non-contiguous memory and removing entries would not require shuffling a lot of data (like in vectors or arrays). However, I got feedback from the company saying my implementation was O(n^2) time complexity and was very inefficient so I was rejected. I don't want to repeat the same mistake if a similar question pops up in another interview so I'd like to know what is the best way to approach this question (a friend suggested using maps but he is also unsure).
My code is:
void IntegerCollector::insert(int x)
{
entries.push_back(x);
}
void IntegerCollector::erase(int x)
{
list<int>::iterator position = find(entries.begin(), entries.end(), x);
if (position != entries.end())
entries.erase(position);
}
void IntegerCollector::erase(int from, int to)
{
list<int>::iterator position = entries.begin();
while (position != entries.end())
{
if (*position >= from && *position <= to)
position = entries.erase(position);
else
position++;
}
}
int IntegerCollector::count(int from, int to)
{
list<int>::iterator position = entries.begin();
int count = 0;
while (position != entries.end())
{
if (*position >= from && *position <= to)
count++;
position++;
}
return count;
}
The feedback mentioned that they would only hire candidates that can implement solutions with O(nlogn) complexity.