Skip to content

Commit c3bbe0f

Browse files
authored
Add files via upload
1 parent 6337e3e commit c3bbe0f

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Two_Heaps/find_right_interval.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import heapq
2+
3+
def find_right_interval(intervals):
4+
5+
# Initialize result array
6+
result = [-1] * len(intervals)
7+
8+
# Initialize min_heaps for start and end points
9+
start_heap = []
10+
end_heap = []
11+
12+
# Populate heaps with intervals
13+
for i, interval in enumerate(intervals):
14+
heapq.heappush(start_heap, (interval[0], i))
15+
heapq.heappush(end_heap, (interval[1], i))
16+
17+
# Process each interval based on its end point
18+
while end_heap:
19+
20+
# Get the interval with the smallest end point
21+
value, index = heapq.heappop(end_heap)
22+
23+
# Remove all start points from that are smaller than current end point
24+
while start_heap and start_heap[0][0] < value:
25+
heapq.heappop(start_heap)
26+
27+
# If start heap is not empty, top element is smallest valid interval
28+
if start_heap:
29+
result[index] = start_heap[0][1]
30+
31+
# Return result list
32+
return result
33+
34+
35+
36+
# Time Complexity = O(nlogn)
37+
# Space Complexity = O(n)
38+
39+
40+
41+
###############################################################
42+
43+
44+
45+
def main():
46+
test_cases = [
47+
[[1, 2]],
48+
[[3, 4], [2, 3], [1, 2]],
49+
[[1, 4], [2, 3], [3, 4]],
50+
[[5, 6], [1, 2], [3, 4]],
51+
[[1, 3], [2, 4], [3, 5], [4, 6]],
52+
]
53+
54+
for i, test_case in enumerate(test_cases):
55+
print(i + 1, "\tintervals:", test_case)
56+
result = find_right_interval(test_case)
57+
print("\n\tOutput:", result)
58+
print("-" * 100)
59+
60+
if __name__ == "__main__":
61+
main()

0 commit comments

Comments
 (0)