Rewrite of Problem 8 to make it run in O(N) time