Clean Java Solution with Detailed Explanation

  • 1

    This question is a basic for interval overlapping problems. To find if the person can attend all meetings is just to decide if there are overlapping intervals in the array.

    As we know the two intervals could have 6 position status as follows:
    0_1503695757855_Screen Shot 2017-08-25 at 5.14.35 PM.png

    After sorting by start, we only have three conditions. Then we can also find the overlap happens only if the start of the current interval smaller than the end of the prev one.

    So what we will do is to go through the array and compare the current start with prev end, if an overlap exists return false else update the prev one to current interval.

     * Definition for an interval.
     * public class Interval {
     *     int start;
     *     int end;
     *     Interval() { start = 0; end = 0; }
     *     Interval(int s, int e) { start = s; end = e; }
     * }
    class Solution {
        public boolean canAttendMeetings(Interval[] intervals) {
            if(intervals == null || intervals.length == 0) return true;
            Arrays.sort(intervals, new Comparator<Interval>(){
               public int compare(Interval e1, Interval e2) {
                   return e1.start-e2.start;
            Interval prev = intervals[0];
            for(int i=1; i<intervals.length; i++) {
                Interval current = intervals[i];
                if(prev.end > current.start) return false;
                prev = current;
            return true;

Log in to reply

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