One, two, skip a few…twenty one! This one was marked as Easy in the email, and out of the ones I have solved recently was the most fun because it made me think about heaps which, while foundational, I don’t find myself really every using. My daily choice is often driven by my opinon on data structures in general.
//Good morning! Here's your coding interview problem for today. //This problem was asked by Snapchat. //Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required. //For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
functionmeetingRooms(intervals) { if (intervals.length === 0) { return0; }
// sort intervals by duration intervals.sort((a, b) => a[0] - b[0]);
// init a *cough*heap const endTimes = [];
// heap push function functionpushHeap(heap, item) { heap.push(item); let i = heap.length - 1; while (i > 0) { let parent = Math.floor((i - 1) / 2); if (heap[parent] <= heap[i]) break; [heap[parent], heap[i]] = [heap[i], heap[parent]]; i = parent; } }
// heap pop function functionpopHeap(heap) { if (heap.length === 1) return heap.pop(); const top = heap[0]; heap[0] = heap.pop(); let i = 0; while (true) { let left = 2 * i + 1; let right = 2 * i + 2; let smallest = i; if (left < heap.length && heap[left] < heap[smallest]) smallest = left; if (right < heap.length && heap[right] < heap[smallest]) smallest = right; if (smallest === i) break; [heap[i], heap[smallest]] = [heap[smallest], heap[i]]; i = smallest; } return top; }
// add first meeting pushHeap(endTimes, intervals[0][1]);
for (let i = 1; i < intervals.length; i++) { // reuse the earliest room if it is free if (intervals[i][0] >= endTimes[0]) { popHeap(endTimes); }
// add the current meeting's end time pushHeap(endTimes, intervals[i][1]); }
// heap size is the # of rooms required // not to be confused with the room of requirement return endTimes.length; }