Checking for overlapping times JavaScript

Time interval overlap detection is a common programming challenge. We need to determine if any two time intervals in an array share common time periods.

Problem Definition

Given an array of time intervals with start and end times, we need to check if any two intervals overlap. Two intervals overlap when they have some time in common.

const arr = [
   { start: '01:00', end: '04:00' },
   { start: '05:00', end: '08:00' },
   { start: '07:00', end: '11:00' },
   { start: '09:30', end: '18:00' },
];

Understanding Overlap Logic

Two intervals A and B overlap if:

  • A's end time is after B's start time, AND
  • B's end time is after A's start time
Time Interval Overlap 0 24 05:00-08:00 07:00-11:00 Overlap

Complete Solution

const arr = [
   { start: '01:00', end: '04:00' },
   { start: '05:00', end: '08:00' },
   { start: '07:00', end: '11:00' },
   { start: '09:30', end: '18:00' },
];

const overlapping = (a, b) => {
   const getMinutes = s => {
      const p = s.split(':').map(Number);
      return p[0] * 60 + p[1];
   };
   return getMinutes(a.end) > getMinutes(b.start) && getMinutes(b.end) > getMinutes(a.start);
};

const isOverlapping = (arr) => {
   let i, j;
   for (i = 0; i 

Overlap found: 05:00-08:00 and 07:00-11:00
true

How It Works

The solution uses a helper function getMinutes() to convert time strings to minutes for easy comparison. The main algorithm compares each interval with every other interval using nested loops.

Testing with Non-Overlapping Intervals

const nonOverlapping = [
   { start: '01:00', end: '03:00' },
   { start: '04:00', end: '06:00' },
   { start: '07:00', end: '09:00' },
];

console.log("Non-overlapping result:", isOverlapping(nonOverlapping));
Non-overlapping result: false

Conclusion

This algorithm efficiently detects time interval overlaps by converting time strings to minutes and using the mathematical overlap condition. It returns true immediately when the first overlap is found, making it optimal for early detection scenarios.

Updated on: 2026-03-15T23:19:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements