Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Easy solution in Clear category for Merge Intervals by chur4hella
def merge_intervals(inter):
i = 0
while i < len(inter) - 1:
if inter[i][0] <= inter[i + 1][0] <= inter[i][1] + 1:
a, b = inter.pop(i), inter.pop(i)
inter.insert(0, (a[0], a[1] if a[1] >= b[1] else b[1]))
else:
i += 1
return inter
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 10, 2021
Comments: