Problem 3 - more efficient algorithm