79541202

Date: 2025-03-28 10:46:19
Score: 0.5
Natty:
Report link

Why is using a dictionary slower than sorting a list to generate frequency array?

Apparently because one input is specially crafted to hack Python's dict implementation, so that building your dict doesn't take the expected linear time. It can take up to quadratic time, and likely they did that. See Python's TimeComplexity page (showing O(n) worst case time for each dict access) and Tutorial: How to hack hash table in Python 3 on CodeForces itself.

One way to defeat it is to simply add 1 to all the numbers, i.e., change

    for num in arr:

to this:

    for num in arr:
        num += 1

Then the solution doesn't get stopped and rejected at the 1 second time limit but gets accepted with around 0.18 seconds. Despite doing more work, and without really changing the data like randomizing or sorting would. The effect is simply that Python's collision resolution takes different paths then, which is enough to thwart the brittle attack.

Another way, also accepted in around 0.18 seconds, is to simply not convert to ints, instead counting the strings. I.e., change

    arr = map(int, input().split())

to this:

    arr = input().split()
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): Why is
  • Low reputation (1):
Posted by: Robert