time : O(logn) space: O(logn);