Coding Challenge Practice – Question 52



This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan

The task is to implement findMeetingSlots(schedules) that finds available meeting slots for all members to have a meeting, given their busy schedules.

The boilerplate code

function findMeetingSlots(schedules) {
  // your code here
}

Flatten all members’ schedules into one array

let allBusy = schedules.flat();

Sort the schedules by start time.

allBusy.sort((a, b) => a[0] - b[0]);

Merge overlapping time intervals

 let merged = [];
  for (let interval of allBusy) {
    if (!merged.length || merged[merged.length - 1][1] < interval[0]) {
      merged.push(interval);
    } else {
      merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
    }
  }

Find the gaps between the merged busy intervals – these are the available meeting slots

let available = [];
  let start = 0;
  for (let [s, e] of merged) {
    if (start < s) available.push([start, s]);
    start = e;
  }

Add the final available slot until 24

if (start < 24) available.push([start, 24]);

The final code:

function findMeetingSlots(schedules) {
  // your code here
  let allBusy = schedules.flat();

  allBusy.sort((a,b) => a[0] - b[0]);

  let merged = [];
  for(let interval of allBusy) {
    if(!merged.length || merged[merged.length - 1][1] < interval[0]) {
      merged.push(interval)
    } else {
      merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1])
    }
  }

  let available = [];
  let start = 0;
  for(let[s,e] of merged) {
    if(start < s) available.push([start,s]);
    start = e;
  }
  if (start < 24) available.push([start, 24]);

  return available;
}

That’s all folks!


This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan