Skip to content

Commit 452ef7e

Browse files
committed
add: IdentifyAllIntervalOverlaps
1 parent bda4964 commit 452ef7e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
import DS.Interval;
5+
6+
/*
7+
// Definition of Interval:
8+
class Interval {
9+
public int start;
10+
public int end;
11+
public Interval(int start, int end) {
12+
this.start = start;
13+
this.end = end;
14+
}
15+
}
16+
*/
17+
18+
public class IdentifyAllIntervalOverlaps {
19+
public List<Interval> identifyAllIntervalOverlaps(List<Interval> intervals1, List<Interval> intervals2) {
20+
List<Interval> overlaps = new ArrayList<>();
21+
int i, j;
22+
i = j = 0;
23+
while (i < intervals1.size() && j < intervals2.size()) {
24+
// Set A to the interval that starts first and B to the other
25+
// interval.
26+
Interval A, B;
27+
if (intervals1.get(i).start <= intervals2.get(j).start) {
28+
A = intervals1.get(i);
29+
B = intervals2.get(j);
30+
} else {
31+
A = intervals2.get(j);
32+
B = intervals1.get(i);
33+
}
34+
// If there's an overlap, add the overlap.
35+
if (A.end >= B.start) {
36+
overlaps.add(new Interval(B.start, Math.min(A.end, B.end)));
37+
}
38+
// Advance the pointer associated with the interval that ends
39+
// first.
40+
if (intervals1.get(i).end < intervals2.get(j).end) {
41+
i++;
42+
} else {
43+
j++;
44+
}
45+
}
46+
return overlaps;
47+
}
48+
}

0 commit comments

Comments
 (0)