0

So I'm doing a practice problem where I'm trying to merge elements from a 2d array and return non-overlapping intervals.

I came up with the solution:

def merge(self, intervals: List[List[int]]) -> List[List[int]]:
    sorted(intervals, key=lambda x: x[0])
    merged_intervals = []
    print(intervals)
    for interval in intervals:
        if not merged_intervals:
            merged_intervals.append(interval)
        else:
            if merged_intervals[-1][1] >= interval[0]:
                merged_intervals[-1][1] = interval[1]
            else:
                merged_intervals.append(interval)
    return merged_intervals

But I'm having an issue where if the test case is [[1,4],[0,4]] sorted() is returning the list in the same order. Am I misunderstanding how the lambda is used in the sorting algorithm here?

Park
  • 2,446
  • 1
  • 16
  • 25
Komrix
  • 1
  • 1
  • 2
    `sorted` does not do in-place sorting. You would want to use `intervals.sort(key=lambda x: x[0])`. – Ervin Szilagyi Jan 29 '22 at 18:39
  • or `intervals = sorted(intervals, key=lambda x: x[0])` – JonSG Jan 29 '22 at 18:40
  • Does this answer your question? [Python sorted() function not working the way it should](https://stackoverflow.com/questions/8767779/python-sorted-function-not-working-the-way-it-should) – JonSG Jan 29 '22 at 18:41
  • Does this answer your question? [What is the difference between \`sorted(list)\` vs \`list.sort()\`?](https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort) – Ervin Szilagyi Jan 29 '22 at 18:41

0 Answers0