O(n^3) algorithm for rectangles