time :O(n) space O((logn)*(logn))