LeetCode in Kotlin

1943. Describe the Painting

Medium

There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color.

The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors.

For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set.

You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj.

Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order.

A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.

Example 1:

Input: segments = [[1,4,5],[4,7,7],[1,7,9]]

Output: [[1,4,14],[4,7,16]]

Explanation: The painting can be described as follows:

Example 2:

Input: segments = [[1,7,9],[6,8,15],[8,10,7]]

Output: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]]

Explanation: The painting can be described as follows:

Example 3:

Input: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]

Output: [[1,4,12],[4,7,12]]

Explanation: The painting can be described as follows:

Note that returning a single segment [1,7) is incorrect because the mixed color sets are different.

Constraints:

Solution

class Solution {
    fun splitPainting(segments: Array<IntArray>): List<List<Long>> {
        val result: MutableList<List<Long>> = ArrayList()
        var n = 1
        for (s in segments) {
            n = Math.max(n, s[1])
        }
        n += 1
        val line = LongArray(n)
        val endpoint = BooleanArray(n)
        for (s in segments) {
            val start = s[0]
            val end = s[1]
            val color = s[2]
            line[start] += color.toLong()
            line[end] -= color.toLong()
            endpoint[end] = true
            endpoint[start] = endpoint[end]
        }
        var mixedColor: Long = 0
        var start = 1
        for (end in 1 until n) {
            if (endpoint[end]) {
                if (mixedColor > 0) {
                    result.add(listOf(start.toLong(), end.toLong(), mixedColor))
                }
                start = end
            }
            mixedColor += line[end]
        }
        return result
    }
}