Why is using unordered set causing TLE while it works for Boolean Vector?

Revision en1, by ParthJha17, 2023-06-17 21:23:08

Hello Codeforces community,

I recently encountered a performance difference while solving a problem using an unordered_set and a vector, and I would like to seek some insights on this matter.

In my solution, I initially implemented the logic using an unordered_set to keep track of element occurrences. However, to my surprise, this implementation resulted in a Time Limit Exceeded (TLE) verdict. Curious about the issue, I refactored the code to use a vector instead, and the TLE issue was resolved.

Solution with Unorder_Set: https://cses.fi/problemset/result/6298544/ Solution with Vector: https://cses.fi/problemset/result/6298541/ Problem: https://cses.fi/problemset/task/1141/

Here are the relevant parts of the two code snippets:

First implementation with Unordered_Set:

while (head + 1 < n && occ.find(id[head + 1]) == occ.end())
{
    ++head;
    occ.insert(id[head]);
    ++count;
}

while (head + 1 < n && occ.find(id[head + 1]) == occ.end()) { ++head; occ.insert(id[head]); ++count; }

Second implementation with Vector:

vector<bool> occ(n, false);

while (head + 1 < n && !occ[id[head + 1]])
{
    ++head;
    occ[id[head]] = true;
    ++count;
}

I expected both implementations to have similar performance, as the time complexity of accessing elements in an unordered_set and a vector is generally O(1). However, it seems that the implementation with unordered_set resulted in a TLE, while the vector implementation passed the tests successfully.

I would greatly appreciate it if someone could shed some light on why this performance difference occurred. Are there any particular reasons or considerations that make unordered_set less performant in this scenario? Any insights or suggestions would be valuable to me.

Thank you for your time and expertise.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English ParthJha17 2023-06-17 21:28:03 8
en2 English ParthJha17 2023-06-17 21:27:14 663 Corrected spelling mistakes
en1 English ParthJha17 2023-06-17 21:23:08 1951 Initial revision (published)