Time: O(logn), Space: O(1)