So, I’ve spent a lot of time to solve this problem… basically, to solve the TLE, not the problem itself. So, after you solve it, consider two things for your final solution:
- Do not use ArrayList, LinkedList or Sets (HashMap or HashSet)… use only arrays like int[]
- Do not store strings in the queue, use only ints and build your string at the end.