revised answer 2 to be less memory intensive