Jaewoo Song
Jaewoo Song


  • Tech

I have usually used map.insert() to put a value in the map and known that this would update automatically if there is already the existing key value.

But I realized that this does not overwrite the overlapping value.


This was a tough problem but I managed to come up with an idea and submitted the solution.

But it kept saying that it is wrong.

After several hours of debugging, I found that the problem was that in the map, values which should be deleted have not been eliminated and new values were added again and again.

idAndValue.insert(pair<int, int> (cow, after));

Originally the algorithm should change the value corresponding to “cow id” into after continuously, but instead, the size of map kept growing.

So I searched about it, and the reason is that map.insert() itself put a value at the beginning but does not update it into new value.

Eventually, I found that map[key] = value adds a new value if there is no key and updates existing value into value if there is key.

It’s so simple…

idAndValue[cow] = after;

I got the correct answer with a shorter and clean code.