max_negative = 0 prev_end = None combined = [] for start, size in offsets: if start < 0: max_negative = min(start, max_negative) else: end = start + size - 1 if prev_end is None: combined.append([start, end]) elif start <= prev_end + 1 + fudge_factor: combined[-1][1] = end else: combined.append([start, end]) prev_end = end return combined, -max_negative