Smarter solution for problem #3. Runs in less than a second.