Here is how we will implement this feature:
We will use two indices, i and j, to traverse both of the meeting schedules, meetingsA and meetingsB, respectively.
The indices i and j will both be zero at the beginning.
Next, we will check if meetingsA[i] and meetingsB[j] overlap by comparing the start and end times.
If the times overlap, the overlapping time interval will be added to the resultant list.
Otherwise, we will keep incrementing the indices depending upon the end time of the next meeting. This means that if the next meeting in meetingsA ends before the next meeting in meetingsB we will only increment i. This is because the current meeting in meetingsB has the possibility to overlap with the next meeting. Similarly, vice versa is also true in case of incrementation in j.
Scala
xxxxxxxxxx
import scala.collection.mutable.ArrayBuffer
object Main {
def meetingsIntersection(meetingsA: Array[Array[Int]], meetingsB: Array[Array[Int]]): Array[Array[Int]] = {
val intersection = new ArrayBuffer[Array[Int]]
var i = 0
var j = 0
while ( {
i < meetingsA.length && j < meetingsB.length
}) {
val start = Math.max(meetingsA(i)(0), meetingsB(j)(0))
val end = Math.min(meetingsA(i)(1), meetingsB(j)(1))
if (start < end)
intersection += Array[Int](start, end)
if (meetingsA(i)(1) < meetingsB(j)(1)) i += 1
else j += 1
}
intersection.toArray
}
def main(args: Array[String]): Unit = {
val meetingsA = Array(Array(1, 3), Array(5, 6), Array(7, 9))
val meetingsB = Array(Array(2, 3), Array(5, 7))
meetingsIntersection(meetingsA, meetingsB).foreach(list=>
{
print("["+list(0)+", " + list(1)+"],")
})
print("]\n")
}
}