def solve(input): input = sorted(input) result = [] while len(input) > 0: base = input.pop(0) while len(input) > 0 and input[0][0] <= base[1] + 1: base = [base[0], max(base[1], input[0][1])] input.pop(0) result.append(base) return result print(solve([[1, 3], [4, 6], [5, 8], [12, 17], [20, 23], [6, 9], [22, 25], [13, 15]]))