orangy
list.sortedBy { it.first }. fold(mutableListOf(list.size)) { result, range ->
when {
result.isEmpty() -> result.add(range) // first
result.last().end < range.start -1 -> result.add(range) // no merge
else -> result.last().let { result[result.lastIndex] = it.start .. range.end }
}
result
}
(written in Slack, it sure has off-by-one errors and other bugs)