Problem
Given a list of meeting intervals where each interval consists of a start and an end time, check if a person can attend all the given meetings such that only one meeting can be attended at a time.
Example
{
"intervals": [[1, 5], [5, 8], [10, 15]]
}
and
{
"intervals": [[1, 5], [4, 8]]
}
Output:
1 and 0
Solution
const canAttendMeetings = (intervals) => {
//Solution 1
const times = new Set();
for (let i = 0; i < intervals.length; i += 1) {
for (let j = intervals[i][0]; j < intervals[i][1]; j += 1) {
if (times.has(j)) {
return 0;
} else {
times.add(j);
}
}
}
return 1;
//Solution 2
for (let i = 0; i < intervals.length; i++) {
for (let j = i + 1; j < intervals.length; j++) {
// If overlap found, return 0
if (!(
intervals[i][1] <= intervals[j][0] ||
intervals[j][1] <= intervals[i][0]
)) {
return 0;
}
}
}
return 1;
};
//Input: intervals = [[1, 5], [4, 8]]; //Output: 0
//Input: [[1, 5], [5, 8], [10, 15]]; Output: 1
const result = canAttendMeetings([[1, 5], [5, 8], [10, 15]]);
console.log(result);