# Given time intervals determine if a person could attend all meetings

Posted on

Problem

The task is taken from LeetCode

Given an array of meeting time intervals consisting of start and end times `[[s1,e1],[s2,e2],...]` `(si < ei)`, determine if a person could
attend all meetings.

Example 1:

``````Input: [[0,30],[5,10],[15,20]]
Output: false
``````

Example 2:

``````Input: [[7,10],[2,4]]
Output: true
``````

My imperative solution:

``````/**
* @param {number[][]} intervals
* @return {boolean}
*/
var canAttendMeetings = function(intervals) {
intervals.sort((a,b) => a - b);
for (let i = 1; i < intervals.length; i++) {
if (intervals[i] < intervals[i - 1]) { return false; }
}
return true;
};
``````

My functional solution:

``````/**
* @param {number[][]} intervals
* @return {boolean}
*/
var canAttendMeetings = function(intervals) {
return intervals
.sort((a,b) => a - b)
.flat()
.every((x,i, src) => i % 2 === 0 || src[i + 1] === void 0 || src[i] < src[i + 1]);
};
``````

Solution

These two functions look quite sufficient to solve the task. I will say that the functional solution will likely be slower, not only because it is functional but also because of the call to `.flat()` and iterating over twice as many elements.

Correct me if this is incorrect, but the call to `.flat()` could be removed if the call to `.every()` was changed to a condition similar to the condition in the imperative solution:

``````.every((x,i, src) => i === 0 || !(src[i] < src[i - 1]));
``````