Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Speedy category for Merge Intervals by ruslan92mv
def merge_intervals(intervals):
i=0
while i < len(intervals)-1:
if intervals[i+1][0] > intervals[i][1]+1:
i=i+1
elif intervals[i + 1][0] <= intervals[i][1] + 1 and intervals[i + 1][1] >= intervals[i][1]:
intervals[i] = (intervals[i][0], intervals[i + 1][1])
intervals.pop(i+1)
elif intervals[i][1] >= intervals[i + 1][1]:
intervals.pop(i+1)
print(intervals)
return intervals
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert merge_intervals([(1, 4), (2, 6), (8, 10), (12, 19)]) == [(1, 6), (8, 10), (12, 19)], "First"
assert merge_intervals([(1, 12), (2, 3), (4, 7)]) == [(1, 12)], "Second"
assert merge_intervals([(1, 5), (6, 10), (10, 15), (17, 20)]) == [(1, 15), (17, 20)], "Third"
print('Done! Go ahead and Check IT')
April 21, 2020
Comments: