Check if a person can attend all meetings?

Companies:
  • Microsoft Interview Questions

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.

Example 1:

Input: [[0,20],[5,10],[20,30]]

Output: false

Example 2:

Input: [[4,6],[7,10]

Output: true

Solution:

We will sort by end time of all the meetings and then check if there is a case where one meeting starts before the previous meeting stops. If such a case exists, then it is not possible to attend all the meetings. Otherwise, it is possible to attend all the meetings

Implementation:

bool canAttendMeetings(vector<Interval>& intervals) {
        sort(intervals.begin(), intervals.end(), [](const Interval& i1, const Interval& i2) -> bool {
            return i1.start < i2.start;
        });
        
        for (size_t i = 1; i < intervals.size(); i++) {
            if (intervals[i - 1].end > intervals[i].start) {
                return false;
            }
        }
        
        return true;
    }

 

class Solution {

  public boolean canAttendMeetings(int[][] intervals) {
    Arrays.sort(intervals, new Comparator<int[]>() {
      public int compare(int[] i1, int[] i2) {
        return i1[0] - i2[0];
      }
    });

    for (int i = 0; i < intervals.length - 1; i++) {
      if (intervals[i][1] > intervals[i + 1][0])
        return false;
    }
    return true;
  }
}

 

def canAttendMeetings(intervals):
        
    intervals.sort(key=lambda a: a.start)
    for i in range(len(intervals)-1):
        if intervals[i].end > intervals[i+1].start:
            return False
    return True

 

Complexity Analysis:

  • Time Complexity: O(nlogn).
  • Space Complexity: O(1).
Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]