Computer >> Computer tutorials >  >> Programming >> Javascript

Meeting Rooms 2 problem in JavaScript


We will be given an array of arrays, each subarray consists of exactly two elements indicating the start and end time of a meeting.

The task of our function is to find the maximum number of meetings one person can take avoiding the conflict of time. The function should finally return this number.

For example −

If the input array describing meeting times is −

const arr = [[5, 40], [10, 20], [25, 35]];

Then the output should be −

const output = 2;

because it's not possible to take all three meetings due to overlapping times but [10, 20] and [25, 35] can be attended.

Example

The code for this will be −

const arr = [[5, 40], [10, 20], [25, 35]];
const canAttendAll = (arr = []) => {
   const times = new Set();
   const { length } = arr;
   for (let i = 0; i < length; i += 1) {
      for (let j = arr[i][0]; j < arr[i][1]; j += 1) {
         if (times.has(j)) {
            return false;
         } else {
            times.add(j);
         };
      };
   };
   return true;
};
console.log(canAttendAll(arr));

Output

And the output in the console will be −

false