I tried but cannot find any way to improve its time complexity. Help is appreciated.

I faced the same issue. However, on trying a simple bruteforce solution for subtask 1 (l<=10) helped me to solve it! Try it out

But there is no different code for subtask 1 (l < = 10).

It is due to heavy inputs in substask 1 so u Just need to change Ur dictionary to arrays u will get ac

Try Running in PyPy got AC using Pypy while Python 3 was giving TLE

Actually one guy had a solution same as mine but I can’t find why his is faster than mine.
AC guy:
Spent hours finding the reason and didn’t got any.