Finalized Algorithm to run in O(N^3)