Possible improvement

There's no need for extra quadratic memory - a single stack will do, as described.