Problem
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 example, if colors
2
,4
, and6
are mixed, then the resulting mixed color is{2,4,6}
.
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
.
- For example, the painting created with
segments = [[1,4,5],[1,7,7]]
can be described bypainting = [[1,4,12],[4,7,7]]
because:[1,4)
is colored{5,7}
(with a sum of12
) from both the first and second segments.[4,7)
is colored{7}
from only the second segment.
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
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= segments.length <= 2 * 10^4
segments[i].length == 3
1 <= starti < endi <= 10^5
1 <= colori <= 10^9
- Each
colori
is distinct.
Solution
Method 1 - Sweep line algorithm
The key idea for solving this problem is to merge intervals based on the colors applied and create new non-overlapping intervals with their mixed color sums:
- Use sweep line and sort events to determine the intervals where color changes.
- Events represent a starting or ending of a segment. For each segment
[start, end, color]
, you add two events:- A start event for
start
withcolor
. - An end event for
end
to removecolor
.
- A start event for
- Traverse the sorted events and keep track of the active colors using a
TreeMap
or ordered map in Java and Python. - Whenever moving between events on the number line, output the interval
[left, right)
and sum of active color set values. - Finally, return the result.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
- Sorting the events:
O(n log n)
, wheren
is the number of segments. - Traversing events and managing active colors:
O(n)
. Overall complexity isO(n log n)
.
- Sorting the events:
- 🧺 Space complexity:
O(n)
for storing events and active colors.