Skip to content

Commit 0442d1d

Browse files
committed
Add 3 interval solutions
* Identify All Interval Overlaps * Largest Overlap of Intervals * Merge Overlapping Intervals
1 parent b2d4105 commit 0442d1d

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
data class Interval(var start: Int, var end: Int)
2+
3+
fun identifyAllIntervalOverlaps(intervals1: List<Interval>, intervals2: List<Interval>): List<Interval> {
4+
val overlaps = mutableListOf<Interval>()
5+
var i = 0
6+
var j = 0
7+
while (i < intervals1.size && j < intervals2.size) {
8+
// Set A to the interval that starts first and B to the other
9+
// interval.
10+
val (A, B) = if (intervals1[i].start <= intervals2[j].start) {
11+
intervals1[i] to intervals2[j]
12+
} else {
13+
intervals2[j] to intervals1[i]
14+
}
15+
// If there's an overlap, add the overlap.
16+
if (A.end >= B.start) {
17+
overlaps.add(Interval(B.start, minOf(A.end, B.end)))
18+
}
19+
// Advance the pointer associated with the interval that ends
20+
// first.
21+
if (intervals1[i].end < intervals2[j].end) {
22+
i++
23+
} else {
24+
j++
25+
}
26+
}
27+
return overlaps
28+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
data class Interval(var start: Int, var end: Int)
2+
3+
fun largestOverlapOfIntervals(intervals: List<Interval>): Int {
4+
val points = mutableListOf<Pair<Int, Char>>()
5+
for (interval in intervals) {
6+
points.add(interval.start to 'S')
7+
points.add(interval.end to 'E')
8+
}
9+
// Sort in chronological order. If multiple points occur at the same
10+
// time, ensure end points are prioritized before start points.
11+
points.sortWith(compareBy({ it.first }, { it.second }))
12+
var activeIntervals = 0
13+
var maxOverlaps = 0
14+
for ((time, pointType) in points) {
15+
if (pointType == 'S') {
16+
activeIntervals++
17+
} else {
18+
activeIntervals--
19+
}
20+
maxOverlaps = maxOf(maxOverlaps, activeIntervals)
21+
}
22+
return maxOverlaps
23+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
data class Interval(var start: Int, var end: Int)
2+
3+
fun mergeOverlappingIntervals(intervals: List<Interval>): List<Interval> {
4+
val sortedIntervals = intervals.sortedBy { it.start }
5+
val merged = mutableListOf(sortedIntervals[0])
6+
for (B in sortedIntervals.subList(1, sortedIntervals.size)) {
7+
val A = merged.last()
8+
// If A and B don't overlap, add B to the merged list.
9+
if (A.end < B.start) {
10+
merged.add(B)
11+
// If they do overlap, merge A with B.
12+
} else {
13+
merged[merged.size - 1] = Interval(A.start, maxOf(A.end, B.end))
14+
}
15+
}
16+
return merged
17+
}

0 commit comments

Comments
 (0)