simple recursive JavaScript solution


  • 0
    1
    /**
     * Definition for an interval.
     * function Interval(start, end) {
     *     this.start = start;
     *     this.end = end;
     * }
     */
    /**
     * @param {Interval[]} intervals
     * @return {number}
     */
    var minMeetingRooms = function(intervals) {
        intervals = intervals.sort(function (a, b) { return a.start - b.start; });
        return minMeetingRoomsRecur(intervals, 0, []);
    };
    
    var minMeetingRoomsRecur = function (intervals, intervalIndex, rooms) {
        if (intervalIndex >= intervals.length) {
            return rooms.length; // base case
        }
        
        var newInterval = intervals[intervalIndex];
        for (var i = 0; i < rooms.length; ++i) {
            var room = rooms[i];
            var fitsInRoom = newInterval.start >= room[room.length - 1].end;
            if (fitsInRoom === true) {
                rooms[i].push(newInterval);
                return minMeetingRoomsRecur(intervals, intervalIndex + 1, rooms);
            }
        }
        
        // add a new room
        rooms.push([newInterval]);
        return minMeetingRoomsRecur(intervals, intervalIndex + 1, rooms);
    };
    

Log in to reply
 

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