|
| 1 | +package interview.google; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Comparator; |
| 5 | +import java.util.Iterator; |
| 6 | + |
| 7 | +import org.junit.Test; |
| 8 | + |
| 9 | +import junit.framework.TestCase; |
| 10 | + |
| 11 | +/** |
| 12 | + * Link: https://www.interviewbit.com/problems/merge-overlapping-intervals/ |
| 13 | + * |
| 14 | + * @author shivam.maharshi |
| 15 | + */ |
| 16 | +public class MergeOverlappingIntervals extends TestCase { |
| 17 | + |
| 18 | + @Test |
| 19 | + public static void test() { |
| 20 | + ArrayList<Interval> l = new ArrayList<>(); |
| 21 | + l.add(new Interval(4, 4)); |
| 22 | + l.add(new Interval(5, 27)); |
| 23 | + l.add(new Interval(5, 31)); |
| 24 | + l.add(new Interval(6, 20)); |
| 25 | + assertEquals(3, merge(l).size()); |
| 26 | + } |
| 27 | + |
| 28 | + public static ArrayList<Interval> merge(ArrayList<Interval> intervals) { |
| 29 | + if (intervals == null || intervals.isEmpty()) |
| 30 | + return intervals; |
| 31 | + intervals.sort(new IComp()); |
| 32 | + Iterator<Interval> it = intervals.iterator(); |
| 33 | + while (it.hasNext()) { |
| 34 | + Interval in = it.next(); |
| 35 | + while (it.hasNext()) { |
| 36 | + Interval next = it.next(); |
| 37 | + if (overlaps(in, next)) { |
| 38 | + in.end = Math.max(in.end, next.end); |
| 39 | + it.remove(); |
| 40 | + } else |
| 41 | + in = next; // Must increment the cur pointer. |
| 42 | + } |
| 43 | + } |
| 44 | + return intervals; |
| 45 | + } |
| 46 | + |
| 47 | + static class IComp implements Comparator<Interval> { |
| 48 | + |
| 49 | + @Override |
| 50 | + public int compare(Interval o1, Interval o2) { |
| 51 | + if (o1.start == o2.start) |
| 52 | + return o1.end < o2.end ? -1 : 1; |
| 53 | + return o1.start < o2.start ? -1 : 1; |
| 54 | + } |
| 55 | + |
| 56 | + } |
| 57 | + |
| 58 | + public static boolean overlaps(Interval i, Interval j) { |
| 59 | + return !(Math.min(i.end, j.end) < Math.max(i.start, j.start)); |
| 60 | + } |
| 61 | + |
| 62 | + static class Interval { |
| 63 | + int start; |
| 64 | + int end; |
| 65 | + |
| 66 | + Interval() { |
| 67 | + start = 0; |
| 68 | + end = 0; |
| 69 | + } |
| 70 | + |
| 71 | + Interval(int s, int e) { |
| 72 | + start = s; |
| 73 | + end = e; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments