LeetCode Entry
228. Summary Ranges
Fold continues ranges in a sorted array 1 2 3 5 -> 1->3, 5
228. Summary Ranges easy
blog post
substack
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/243
Problem TLDR
Fold continues ranges in a sorted array 1 2 3 5 -> 1->3, 5
Intuition
Scan from start to end, modify the last interval or add a new one.
Approach
Let’s write a Kotlin one-liner
Complexity
- Time complexity: \(O(n)\)
- Space complexity: \(O(n)\)
Code
fun summaryRanges(nums: IntArray): List<String> = nums
.fold(mutableListOf<IntArray>()) { r, t ->
if (r.isEmpty() || r.last()[1] + 1 < t) r += intArrayOf(t, t)
else r.last()[1] = t
r
}
.map { (f, t) -> if (f == t) "$f" else "$f->$t"}