#1943
Describe the Painting
MediumArrayHash TableSortingPrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a sweep line algorithm to efficiently track overlapping segments and their colors. By sorting the segments and using a map to keep track of color sums, we can achieve a more efficient solution.
⚙️
Algorithm
4 steps- 1Step 1: Create an array of events for each segment's start and end points.
- 2Step 2: Sort the events by position, processing starts before ends at the same position.
- 3Step 3: Use a hashmap to track the sum of colors currently active as we sweep through the events.
- 4Step 4: When moving to a new position, if there are active colors, create a new segment with their sum.
solution.py27 lines
1# Full working Python code
2from collections import defaultdict
3
4def describe_painting(segments):
5 events = []
6 for start, end, color in segments:
7 events.append((start, color, 'start'))
8 events.append((end, color, 'end'))
9 events.sort()
10
11 color_sum = defaultdict(int)
12 painting = []
13 last_position = None
14
15 for position, color, typ in events:
16 if last_position is not None and last_position != position:
17 if color_sum:
18 painting.append([last_position, position, sum(color_sum.keys())])
19 if typ == 'start':
20 color_sum[color] += 1
21 else:
22 del color_sum[color]
23 last_position = position
24
25 return painting
26
27print(describe_painting([[1, 4, 5], [1, 7, 7]]))ℹ
Complexity note: The sorting of events takes O(n log n), and maintaining the hashmap for active colors takes linear space.
- 1Using a sweep line algorithm can significantly reduce the complexity of overlapping interval problems.
- 2Tracking active colors dynamically allows for efficient summation without unnecessary recalculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.