MediumNo. 2021LeetCode Premium

Brightest Position on Street — LeetCode 2021 Python Solution

Pattern
Prefix Sum
Topics
Array, Ordered Set, Prefix Sum, Sorting
Reading time
3 min

The problem

A perfectly straight street is represented by a number line. The street has street lamp(s) on it and is represented by a 2D integer array lights.

Example

Input
lights = [[-3,2],[1,2],[3,3]]
Output
-1
Explanation
The first street lamp lights up the area from [(-3) - 2, (-3) + 2] = [-5, -1].

Python solution

PythonSolution
class Solution:
    def brightestPosition(self, lights: List[List[int]]) -> int:
        d = defaultdict(int)
        for i, j in lights:
            l, r = i - j, i + j
            d[l] += 1
            d[r + 1] -= 1
        ans = s = mx = 0
        for k in sorted(d):
            s += d[k]
            if mx < s:
                mx = s
                ans = k
        return ans

Complexity

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

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2021. Brightest Position on Street is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

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
2731Movement of RobotsMedium
2017Grid GameMedium
0238Product of Array Except SelfMedium
0303Range Sum Query - ImmutableEasy
0304Range Sum Query 2D - ImmutableMedium
0724Find Pivot IndexEasy

Frequently asked questions

How hard is LeetCode 2021. Brightest Position on Street?

LeetCode 2021. Brightest Position on Street is rated Medium on LeetCode.

What is the time complexity of LeetCode 2021. Brightest Position on Street?

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

What is the space complexity of LeetCode 2021. Brightest Position on Street?

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

What topics does LeetCode 2021. Brightest Position on Street cover?

LeetCode 2021. Brightest Position on Street is tagged Array, Ordered Set, Prefix Sum and Sorting on LeetCode.

Is LeetCode 2021. Brightest Position on Street a premium problem?

Yes. LeetCode 2021. Brightest Position on Street is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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.