DEV Community

truongductri01
truongductri01

Posted on

252. Meeting Rooms

Problem Source: 252. Meeting Rooms

1. Understand the problem
We need to determine whether the user could attend all meetings without any conflict or not.
2 meeting a and b will conflict with each other if there is any overlap between a and b.

Here are 2 valid situation that a and b do not conflict each other:

  • a.start >= b.end
  • b.start >= a.end (this means that one meeting start after the other ends)

Other situations will resolved in an overlap situation.

2. Solution
When dealing with interval problems, we need to sort the meeting times in ascending order of start time followed by the ascending order of end time.

With this, when consider 2 interval I1 and I2, if I2.start is less than I1.end, they overlap.

Here is the code:

class Solution {
    public boolean canAttendMeetings(int[][] intervals) {
        /**
        If the meetings time overlapped, return no.
        */
        if (intervals.length <= 1) {
            return true;
        }

        Arrays.sort(intervals, (a, b) -> a[0] == b[0]? a[1] - b[1]: a[0] - b[0]);

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

        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)