use TCO to reduce space complexity