My Python Solution


  • 11
    Y
    def canAttendMeetings(self, intervals):
        intervals.sort(key=lambda x: x.start)
        
        for i in range(1, len(intervals)):
            if intervals[i].start < intervals[i-1].end:
                return False
            
        return True

  • 12

    Same, but using all(...):

    def canAttendMeetings(self, intervals):
        intervals.sort(key=lambda i: i.start)
        return all(intervals[i-1].end <= intervals[i].start
                   for i in range(1, len(intervals)))
    

    I like that it's shorter and that I can positively say what I want (intervals[i-1].end <= intervals[i].start), not its negation.

    Another alternative:

    def canAttendMeetings(self, intervals):
        intervals.sort(key=lambda i: i.start)
        return all(i.end <= j.start for i, j in zip(intervals, intervals[1:]))

  • 0

    The second one using zip is really cool!!!


  • 0
    O

    love the zip one too!!


  • 0

    Alternative:

    def canAttendMeetings(self, v):
        v.sort(key=lambda v:v.start)
        return not any(v[i].start < v[i-1].end for i in range(1, len(v)))

  • 0
    A

    @StefanPochmann @agave While I love the simplicity of the solution I think it suffers from a worst average case runtime compared to the solution posted by OP.


Log in to reply
 

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