You can do this with one pass, you don't have to iterate twice.