MediumNo. 1943

Describe the Painting — LeetCode 1943 Python Solution

Pattern
Prefix Sum
Topics
Array, Hash Table, Prefix Sum, Sorting
Reading time
2 min

The 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.

Example

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:

Python solution

PythonSolution
class Solution:
    def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
        d = defaultdict(int)
        for l, r, c in segments:
            d[l] += c
            d[r] -= c
        s = sorted([[k, v] for k, v in d.items()])
        n = len(s)
        for i in range(1, n):
            s[i][1] += s[i - 1][1]
        return [[s[i][0], s[i + 1][0], s[i][1]] for i in range(n - 1) if s[i][1]]

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1943. Describe the Painting is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2251Number of Flowers in Full BloomHard
0049Group AnagramsMedium
0169Majority ElementEasy
0217Contains DuplicateEasy
0229Majority Element IIMedium
0268Missing NumberEasy

Frequently asked questions

How hard is LeetCode 1943. Describe the Painting?

LeetCode 1943. Describe the Painting is rated Medium on LeetCode.

What is the time complexity of LeetCode 1943. Describe the Painting?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1943. Describe the Painting?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1943. Describe the Painting cover?

LeetCode 1943. Describe the Painting is tagged Array, Hash Table, Prefix Sum and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.