Improved memory usage by looping through sequences only once