Meeting Rooms II

Problem

Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2

Example 2:

Input: intervals = [[7,10],[2,4]]
Output: 1

Constraints:

  • 1 <= intervals.length <= 104
  • 0 <= starti < endi <= 106

Solution

Sort

class Solution {
    public int minMeetingRooms(int[][] intervals) {
        var start = Arrays.copyOf(intervals, intervals.length);
        var end = Arrays.copyOf(intervals, intervals.length);

        Arrays.sort(start, (l, r) -> {
            return Integer.compare(l[0], r[0]);
        });

        Arrays.sort(end, (l, r) -> {
            return Integer.compare(l[1], r[1]);
        });

        var startP = 0;
        var endP = 0;
        var rooms = 0;

        while (startP < start.length) {
            if (start[startP][0] >= end[endP][1]) {
                rooms -= 1;
                endP += 1;
            }

            rooms += 1;
            startP += 1;
        }

        return rooms;
    }
}

Sort + Heap

class Solution {
    public int minMeetingRooms(int[][] intervals) {
        // sort input by start
        Arrays.sort(intervals, (l, r) -> {
            return Integer.compare(l[0], r[0]);
        });
        // pq by end
        var pq = new PriorityQueue<int[]>((l, r) -> {
            return Integer.compare(l[1], r[1]);
        });
        var rooms = 0;
        for (var i = 0; i < intervals.length; i++) {
            // remove meetings that have ended
            while (!pq.isEmpty() && pq.peek()[1] <= intervals[i][0]) {
                pq.poll();
            }

            pq.offer(intervals[i]);
            rooms = Math.max(rooms, pq.size());
        }
        return rooms;
    }
}

Recent posts from blogs that I like

Paintings of Saint-Tropez: Colour, boats and bathers 2

Paintings by Paul Signac, Maximilien Luce, and Pierre Bonnard showing fishing boats, trees and bathers near this smalll fishing village on the Mediterranean coast.

via The Eclectic Light Company

Run LLMs on macOS using llm-mlx and Apple's MLX framework

via Simon Willison

How to add a directory to your PATH

I was talking to a friend about how to add a directory to your PATH today. It’s something that feels “obvious” to me since I’ve been using the terminal for a long time, but when I searched for instructions for how to do it, I actually couldn’t find something that explained all of the steps – a lot o...

via Julia Evans