Linear time solution for 409 (runs in 1s).