Describe the Painting - 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, and 6 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.

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.

Input & Output

Example 1 — Basic Overlapping
$ Input: segments = [[1,4,5],[4,7,7],[1,7,9]]
Output: [[1,4,14],[4,7,16]]
💡 Note: Segment [1,4) has colors {5,9} with sum 14. Segment [4,7) has colors {7,9} with sum 16.
Example 2 — No Overlap
$ Input: segments = [[1,7,9],[6,10,15],[8,12,5]]
Output: [[1,6,9],[6,7,24],[7,8,15],[8,10,20],[10,12,5]]
💡 Note: Multiple distinct segments with different color combinations at each interval.
Example 3 — Single Segment
$ Input: segments = [[1,4,5]]
Output: [[1,4,5]]
💡 Note: Only one segment, so output is identical to input with no mixing.

Constraints

  • 1 ≤ segments.length ≤ 2 × 104
  • segments[i].length == 3
  • 1 ≤ starti < endi ≤ 105
  • 1 ≤ colori ≤ 109
  • starti < endi

Visualization

Tap to expand
Describe the Painting: Segment Overlap Analysis147Segment [1,4): Color 5Segment [4,7): Color 7Segment [1,7): Color 9Overlapping regions create mixed colors[1,4): 5+9=14[4,7): 7+9=16Output: [[1,4,14],[4,7,16]]
Understanding the Visualization
1
Input
Multiple colored segments on number line
2
Process
Find overlapping regions and sum colors
3
Output
Non-overlapping segments with mixed color sums
Key Takeaway
🎯 Key Insight: Use sweep line events to efficiently track when colors start and end, avoiding coordinate range limitations
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
487 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen