First implementation, time O(N), space O(1)