Correct solution without recursion