2
\$\begingroup\$

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[0] - b[0]);
  for (let i = 1; i < intervals.length; i++) {
    if (intervals[i][0] < intervals[i - 1][1]) { return false; }
  }
  return true;
};

My functional solution:

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

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][0] < src[i - 1][1]));
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.