Interview Bootcamp
Ask Author
Back to course home

0% completed

Vote For New Content
Aydar Nabiev
I think this is the one that is easier to understand

Aydar Nabiev

Jan 18, 2026

The reason for it - it is easier to determine if intervals don't touch each other. In that case it is also easy to understand which one needs to 'catch up' to the other.

This task is 'inspired by' Leetcode 986 - I write this so you can go there and see example 1, the visual representation will help you reach this solution yourself, like I (thanks to this course, too) did. In my opinion, those 'ifs' which exclude all non-overlapping scenarios, seems to be better for the eye than the visually complex 'if' for overlapping.

public List<Interval> merge(Interval[] arr1, Interval[] arr2) { if (arr1.length == 0 || arr2.length == 0) { new ArrayList<>(); } // we probably must create new intervals on the fly, but understanding their bounds is the hardest challenge here // two pointers, huh? int firstPointer = 0; int secondPointer = 0; List<Interval> list = new ArrayList<>(); while (firstPointer < arr1.length && secondPointer < arr2.length) { Interval firstInterval = arr1[firstPointer]; Interval secondInterval = arr2[secondPointer]; // conditions: // first interval is fully before second interval - increase first // first interval is fully after second interval - increase second // intervals overlap - several cases, too? if (firstInterval.end < secondInterval.start) { firstPointer++; } else if (firstInterval.start > secondInterval.end) { secondPointer++; } else { // overlap! determine intersection and then move appropriate pointer appropriately // now, how to determine which one will need to go up after intersection? // also what if intersection still going from previous iterations? list.add(new Interval(Math.max(firstInterval.start, secondInterval.start), Math.min(firstInterval.end, secondInterval.end))); if (firstInterval.end < secondInterval.end) { firstPointer++; } else { secondPointer++; } } } return list; }

0

0

Comments
Comments