Merge Intervals

This is one of the commonly asked questions in LC as there were about 22 companies who’ve used this question in their interviews.

class Solution {
    fun merge(intervals: Array<IntArray>): Array<IntArray> {
        if(intervals.size <= 1) return intervals
        intervals.sortBy { it.first() }
        var output = mutableListOf<IntArray>()
        for(index in 0 until intervals.size){
            if(output.isEmpty() || output.last().last() < intervals[index].first()){
                output.add(intervals[index])    
            }else{
                output.last()[1] = Math.max(output.last()[1], intervals[index].last())
            }            
        }
        
        return output.toTypedArray()
    }
}
Runtime: 272 ms, faster than 31.09% of Kotlin online submissions for Merge Intervals.
Memory Usage: 43.4 MB, less than 100.00% of Kotlin online submissions for Merge Intervals.