Anything wrong with my Python code?

  • 0

    I had this simple Python code that fails after submission at the case of [[1,2],[2,3]], I think my code gives 0, but it said 1.

    if len(intervals)<=1:
    return 0
    res, end = 0, float('-inf')
    for x in intervals:
    if x.start<end:
    return res

  • 0

    Two issues.

    1. Interval is a python custom class, if you want to sort it like this you need to implement __cmp__ function, otherwise you have to use the key argument in sort function to tell python what do you want to sort. Otherwise this is a undefined behaviour (I guess by default python sort custom class by id(), but I am not sure).

    2. If you are sorting the start interval, you must process the array from backward.
      if you don't want to process in reverse order, you should sort the end interval by ASC, this is the tricky part for this question. Here is an example:

    if you sort by start interval and process in ASC, you get:
    [[1, 1000000000000000000000000], [2,3], [4,5]]

    Since the end of the first element is really big, you will always need to remove the rest, however if you sort by the end, you will get:

    now, it looks better.

    Hope this helps

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.