Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Roman Kishchenko
Easy to follow Java solution

Roman Kishchenko

Jan 16, 2025

class Solution { public List<Interval> merge(Interval[] left, Interval[] right) { List<Interval> result = new ArrayList<Interval>(); int l = 0; int r = 0; while (l < left.length && r < right.length) { // Skipping an interval from the left if it ends before an // interval from the right starts if (left[l].end < right[r].start) { l++; // Similarly, skipping an interval from the right if it ends before // an interval from the left starts } else if (right[r].end < left[l].start) { r++; } else { // If the first two conditions are not satisfied, there is an intersection. Interval intersection = new Interval( Math.max(left[l].start, right[r].start), Math.min(left[l].end, right[r].end) ); result.add(intersection); // Skipping the interval that ends first because the longer interval can // still intersect with another interval if (left[l].end > right[r].end) { r++; } else { l++; } } } return result; } }

0

0

Comments
Comments

On this page