What is difference between .sort(key=lambda x: x[0]) and .sort(key=lambda x: (x[0], -x[1])). I thought they both would sort the list basically.
I tried with an example:
lst = [[2,1], [0,4], [6,7], [3, 5]]
lst.sort(key=lambda x: x[0])
print(last)
>>> [[0, 4], [2, 1], [3, 5], [6, 7]]
lst = [[2,1], [0,4], [6,7], [3, 5]]
lst.sort(key=lambda x: (x[0], -x[1]))
print(last)
>>> [[0, 4], [2, 1], [3, 5], [6, 7]]
They work ideally the same in this case.
In this LeetCode problem, however, when I use the first approach (key=lambda x: x[0]), I get the wrong answer
When I use the second approach (key=lambda x: (x[0], -x[1])), the solution is accepted.
My final code then looks like the following:
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
# intervals.sort(key=lambda x: x[0])
intervals.sort(key=lambda x: (x[0], -x[1]))
last = -1
removed = 0
for i in intervals:
if i[1] <= last:
removed += 1
else:
last = i[1]
return len(intervals) - removed
Also, I guess that the problem is with the intervals which start with the same left-end (as in the wrong answer). When I tried that test case separately I got this:
lst = [[1,2], [1,4], [3,4]]
lst.sort(key=lambda x: x[0])
print(last)
>>> [[1, 2], [1, 4], [3, 4]]
lst = [[1,2], [1,4], [3,4]]
lst.sort(key=lambda x: (x[0], -x[1]))
print(last)
>>> [[1, 4], [1, 2], [3, 4]]
It seems to have a little difference with the order of right-ends, though.


-second element of sublist. Then it is sorting according to that