Refactors solution with fewer loop calls