v3 time O(n^2log(n)) space O(log(n)) Accepted