Solution 3.4: O(N^3)