I think the problem is a limitation of the website - rather than the code itself.
(EDIT: You are trying with an input of 100000 (hundred thousand) - it will run OK
with an input of 10 000 (ten thousand) - which is why I think it is
due to a limitation of the website - in that it can only handle so much output - rather than the source code)