Time: O(logN), Space: O(n)