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