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