Hossain_Ahmed's blog

By Hossain_Ahmed, history, 5 hours ago, In English

I've been facing some confusion about when to use map and unordered_map. In some problems, using unordered_map leads to TLE , while map works fine. This has made me curious about the correct usage of these two containers.

Could you give me any suggestion please

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
5 hours ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

Check this

In brief: Unordered set and unordered map use hash table (imagine it as a large array) and for each item it uses some algorithm to find the index it should be stored in (which usually works in $$$O(1)$$$), if something is already stored at that index, for simplicity let's say it puts it next to it, if something is next to it, it finds the next empty index and inserts it there, this is known as collision, now if the algorithm determines that most items should be stored in the same index what will happen? it will keep searching for the next empty one which will lead the complexity to increase from $$$O(1)$$$ to $$$O(n)$$$, this rarely happen unless a test case is specifically written to cause this (which someone will mostly do to hack your solution if the author didn't), so for codeforces contests just avoid using them unless you are sure no collisions can happen.

  • »
    »
    4 hours ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thank you.

»
5 hours ago, # |
  Vote: I like it +3 Vote: I do not like it

The reason you get TLE when using an unordered_map is that, although the average complexity of insert() and find() is O(1), their worse case complexity is O(n). This makes it possible to hack a solution that uses unordered_map in some cases.

The complexity of insert() and find() on a map is O(logn), which is efficient enough most of the time. I'm pretty sure I never got TLE because of using a map instead of an unordered_map (Maybe I was just lucky, though. Did that ever happpen to you?), so I don't think there's a reason not to prefer it.

  • »
    »
    4 hours ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thank you.

    As a beginner, I haven't faced TLE with map yet, but I got a TLE and even got hacked while using unordered_map. It's heartbreaking when you solve two problems in a Div 2 contest and hacked by someone afterward.

    • »
      »
      »
      4 hours ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      Yeah, I know how you feel. Don't worry, though, the better you get, and the more you learn, the easier it will be to avoid getting hacked. Plus, if you get hacked because of a small mistake, you'll most likely regain your previous rating on the next contest.