This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
82. find available meeting slots
Here's one possible solution:
function findMeetingSlots(schedules) { let busySlots = schedules.flatMap(memberSchedules => memberSchedules); busySlots.sort((a, b) => a[0] - b[0]); let freeSlots = []; let lastEnd = 0; for (let [start, end] of busySlots) { if (start > lastEnd) { freeSlots.push([lastEnd, start]); } lastEnd = Math.max(lastEnd, end); } if (lastEnd < 24) { freeSlots.push([lastEnd, 24]); } return freeSlots;}let schedules = [ [[13,15], [11,12], [10,13]], //schedule for member 1 [[8, 9]], // schedule for member 2 [[13, 18]] // schedule for member 3];console.log(findMeetingSlots(schedules)); // [[0,8],[9,10],[18,24]]
Explanation:
- First, we combine all the member schedules into a single array called
busySlots
. We useflatMap
instead ofconcat
because some members might have multiple intervals in their schedule. - We sort
busySlots
by the starting time of each interval. - Next, we loop through the sorted
busySlots
array and keep track of the latest ending time of any interval we've seen so far. If there is a gap between the end of the previous interval and the start of the current one, we add a free slot to thefreeSlots
array. Finally, if the last interval does not end at 24 (i.e. the end of the day), we add one last free slot to cover the remaining time. - We return the
freeSlots
array as the answer.
Note that this solution assumes that schedules
is a 2-dimensional array where each member's schedule is given as an array of intervals. If schedules
is given as a single array of intervals, the first step can be skipped (since there is only one member).