Skip to content

Commit 3edd707

Browse files
author
Partho Biswas
committed
986. Interval List Intersections
1 parent e1fd5ef commit 3edd707

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/986_Interval_List_Intersections.swift

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// brute force
1+
// Brute force
22
// Time O((m+n)log(m+n)) | Space O(m+n)
33
class Solution {
44
func intervalIntersection(_ A: [[Int]], _ B: [[Int]]) -> [[Int]] {
@@ -7,7 +7,6 @@ class Solution {
77
return mergedIntervals
88
}
99
mergedIntervals.sort(by: { $0[0] < $1[0] })
10-
print(mergedIntervals)
1110
var intersections = [[Int]]()
1211
for i in 0..<(mergedIntervals.count - 1) {
1312
let currentInterval = mergedIntervals[i]
@@ -23,5 +22,27 @@ class Solution {
2322
}
2423

2524

26-
27-
25+
// Improved linear
26+
// Time O(m+n) | Space O(1)
27+
class Solution {
28+
func intervalIntersection(_ A: [[Int]], _ B: [[Int]]) -> [[Int]] {
29+
var intersactions = [[Int]]()
30+
var (aIdx, bIdx) = (0, 0)
31+
while aIdx < A.count && bIdx < B.count {
32+
let (aInterval, bInterval) = (A[aIdx], B[bIdx])
33+
if (aInterval[1] >= bInterval[0]) && (aInterval[0] <= bInterval[1]) {
34+
let intersection = [max(aInterval[0], bInterval[0]), min(aInterval[1], bInterval[1])]
35+
intersactions.append(intersection)
36+
}
37+
if aInterval[1] < bInterval[1] {
38+
aIdx += 1
39+
} else if aInterval[1] > bInterval[1] {
40+
bIdx += 1
41+
} else {
42+
aIdx += 1
43+
bIdx += 1
44+
}
45+
}
46+
return intersactions
47+
}
48+
}

0 commit comments

Comments
 (0)