DSA Factory
Free lessonsIntervals · Stage 0 · Overlap and merge · Step 1

Do they overlap?

Two ranges share a point unless one ends before the other begins. About 7 minutes.

Ask when they miss

Two ranges miss each other in only two ways: the first one ends before the second one starts, or the second one ends before the first one starts. Like two meetings, one is finished before the other begins.

If neither happens, they overlap. Turning both "miss" conditions around gives the test directly.

Each starts no later: than the other one ends.
Order doesn't matter: the test works whichever interval comes first.
In code
return a[0] <= b[1] and b[0] <= a[1]
a = [1, 4], b = [3, 6]
123456ab

Does a end before b starts? a ends at 4, b starts at 3. No.

Move 1 of 3

The easy mistakes

Checking only whether the first start lies inside the second range misses the case where the second sits entirely inside the first, such as [1, 10] and [3, 4]. Picture a short meeting wholly inside a long one.

Using "less than" where "at most" is needed wrongly says that touching ranges like [1, 4] and [4, 6] don't overlap.

One inside the other: [1, 10] and [3, 4] overlap even though 1 is not inside [3, 4].
Ends are included: so equal values count as overlapping.
Quick check

Do [5, 9] and [2, 5] overlap?

  1. AYes, they share 5
  2. BNo, [2, 5] ends where [5, 9] begins
Show the answer

Yes, they share 5. 5 <= 5 and 2 <= 9: both ranges include 5.

Your problem

Do they overlap?

Two classes are booked in the same room. Each booking is an interval [start, end] that includes both ends. Given bookings a and b, return true if they share at least one time, otherwise false.

Example
a = [1, 4], b = [3, 6] → true

a.length == b.length == 2 · 0 ≤ start ≤ end ≤ 1,000,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding