1+ '''
2+ Find All Intervals
3+
4+ You are given an array of intervals.
5+ Each interval is defined as: (start, end). e.g. (2, 5)
6+ It represents all the integer numbers in the interval, including start and end. (in the example 2, 3, 4 and 5).
7+ Given the array of intervals find the smallest set of unique intervals that contain the same integer numbers, without overlapping.
8+
9+
10+ Input: [(1, 5), (2, 6)]
11+ Output: [(1, 6)]
12+
13+ Input: [(2, 4), (5, 5), (6, 8)]
14+ Output: [(2, 8)]
15+
16+ Input: [(1, 4), (6, 9), (8, 10)]
17+ Output: [(1, 4), (6, 10)]
18+
19+ =========================================
20+ Sort the intervals (using the start), accessing order. After that just iterate the intervals
21+ and check if the current interval belongs to the last created interval.
22+ Time Complexity: O(N LogN)
23+ Space Complexity: O(1)
24+ '''
25+
26+
27+ ############
28+ # Solution #
29+ ############
30+
31+ def find_all_intervals (intervals ):
32+ n = len (intervals )
33+ if n == 0 :
34+ return []
35+
36+ # sort the intervals
37+ intervals .sort (key = lambda interval : interval [0 ])
38+ result = []
39+ start , end = intervals [0 ]
40+
41+ for i in range (1 , n ):
42+ # check if this interval belongs to the last created interval
43+ if intervals [i ][0 ] <= end + 1 :
44+ # only the end can be changed (start is min, because array is sorted)
45+ end = max (end , intervals [i ][1 ])
46+ else :
47+ # save this interval
48+ result .append ((start , end ))
49+ # create a new interval
50+ start , end = intervals [i ]
51+
52+ # add the last interval
53+ result .append ((start , end ))
54+
55+ return result
56+
57+
58+ ###########
59+ # Testing #
60+ ###########
61+
62+ # Test 1
63+ # Correct result => [(1, 6)]
64+ print (find_all_intervals ([(1 , 5 ), (2 , 6 )]))
65+
66+ # Test 2
67+ # Correct result => [(2, 8)]
68+ print (find_all_intervals ([(2 , 4 ), (5 , 5 ), (6 , 8 )]))
69+
70+ # Test 3
71+ # Correct result => [(1, 4), (6, 10)]
72+ print (find_all_intervals ([(1 , 4 ), (6 , 9 ), (8 , 10 )]))
0 commit comments