Sobes.tech
Middle

/* Two sorted lists with user online presence intervals during the day are given. The start of the interval is strictly less than the end. Calculate the intervals when both users were online. Intervals are given in hours, from 0 to 24. */ intersection( [[8, 12], [17, 22]], [[5, 11], [14, 18], [20, 23]] )// [[8, 11], [17, 18], [20, 22]] intersection( [[9, 15], [18, 21]], [[10, 14], [21, 22]] )// [[10, 14]] function intersection(user1, user2) { // your code here }

sobes.tech AI

Answer from AI

To find the intersection of two interval lists, you can use an algorithm with two pointers, traversing both lists simultaneously and calculating the intersections of the current intervals.

Example solution in JavaScript:

function intersection(user1, user2) {
  let i = 0, j = 0;
  const result = [];

  while (i < user1.length && j < user2.length) {
    const start = Math.max(user1[i][0], user2[j][0]);
    const end = Math.min(user1[i][1], user2[j][1]);

    if (start < end) { // there is an intersection
      result.push([start, end]);
    }

    // move the pointer of the interval that ends first
    if (user1[i][1] < user2[j][1]) {
      i++;
    } else {
      j++;
    }
  }

  return result;
}

// Example usage:
console.log(intersection(
  [[8, 12], [17, 22]],
  [[5, 11], [14, 18], [20, 23]]
));
// Output: [[8, 11], [17, 18], [20, 22]]

This algorithm runs in O(n + m) time, where n and m are the lengths of the interval lists.