DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

2 1

Interval List Intersections - LeetCode

Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.

This problem can be divided into two steps, finding intervals from two lists and looping through lists

Let's see what kind of overlaps can occur

types-of-overlaps

From the image the condition for overlap is

overlap-condition

In order to get start and end of the overlapping range

start and end of overlap

Now we need to figure out how to loop through the lists A and B

You can use two pointers technique. See below image to understand better

Two pointers technique

Here's the code

/**
 * @param {number[][]} A
 * @param {number[][]} B
 * @return {number[][]}
 */
var intervalIntersection = function(A, B) {
    let res = new Array()
    let i = 0, j = 0
    while(i < A.length && j < B.length) {
        let lo = Math.max(A[i][0], B[j][0])
        let hi = Math.min(A[i][1], B[j][1])
        if(lo <= hi) {
            res.push([lo, hi])
        }

        if(A[i][1] < B[j][1]) {
            i++ // A length is over go to next one
        } else {
            j++
        }
    }
    return res
};

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay