986. Interval List Intersections

class Solution:
    def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
        i = 0
        j = 0
        res = []
        
        while i < len(firstList) and j < len(secondList):
            
            lo = max(firstList[i][0], secondList[j][0])
            hi = min(firstList[i][1], secondList[j][1])

            if lo <= hi:
                res.append([lo, hi])

            if firstList[i][1] < secondList[j][1]: # if ai is less than bj, means ai cannot intersect more intervals in b, therefore move the pointer
                i += 1 
            else: # vice versa
                j += 1
        return res

Last updated