Skip to content

Commit 98fa149

Browse files
committed
Interval List Intersections
1 parent 27ad12a commit 98fa149

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

986-interval-list-intersections.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/interval-list-intersections/
3+
4+
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
5+
Return the intersection of these two interval lists.
6+
(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x
7+
with a <= x <= b. The intersection of two closed intervals is a set of real numbers
8+
that is either empty, or can be represented as a closed interval.
9+
For example, the intersection of [1, 3] and [2, 4] is [2, 3].)
10+
11+
Example 1:
12+
Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
13+
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
14+
Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.
15+
16+
Note:
17+
0 <= A.length < 1000
18+
0 <= B.length < 1000
19+
0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9
20+
"""
21+
class Solution:
22+
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
23+
indexA = indexB = 0
24+
res = []
25+
while indexA < len(A) and indexB < len(B):
26+
# startpoint of the intersection
27+
start = max(A[indexA][0], B[indexB][0])
28+
# endpoint of the intersection
29+
end = min(A[indexA][1], B[indexB][1])
30+
# if A and B intersect
31+
if start <= end:
32+
res.append([start,end])
33+
34+
# Remove the interval with the smallest endpoint
35+
if A[indexA][1] < B[indexB][1]:
36+
indexA += 1
37+
else:
38+
indexB += 1
39+
return res

0 commit comments

Comments
 (0)