Brightest Position on Street

Medium Intervals Line Sweep

Brightest Position on Street is a medium intervals problem solved with the line sweep pattern. The best approach, optimal (sorted starts and ends, two pointers), runs in O(n log n) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every left end) up.

Problem

A long straight street is modelled as a number line. Some street lights stand on it. Each light is given as lights[i] = [position, range]: it stands at position and lights every integer point from position - range to position + range, both ends included.

The brightness of a point is the number of lights that reach it.

Return the point with the greatest brightness. If several points share that greatest brightness, return the smallest of them.

Examples

Example 1

Input
lights = [[-3, 2], [1, 2], [3, 3]]
Output
-1
Why
The lights cover [-5, -1], [-1, 3] and [0, 6]. Position -1 is lit by the first two lights, and every position from 0 to 3 is lit by the last two, so the best brightness is 2. The smallest position that reaches it is -1.

Example 2

Input
lights = [[2, 1], [5, 0], [4, 2]]
Output
2
Why
The lights cover [1, 3], [5, 5] and [2, 6]. Positions 2, 3 and 5 each have brightness 2, and no position has 3. The smallest of them is 2.

Example 3

Input
lights = [[7, 0]]
Output
7
Why
A single light with range 0 only lights its own position.

Constraints

  • 1 <= lights.length <= 10^5
  • lights[i].length == 2
  • -10^8 <= lights[i][0] <= 10^8
  • 0 <= lights[i][1] <= 10^8

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 17 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (try every left end)O(n²)O(1)
Line sweep with a sorted mapO(n log n)O(n)
Optimal (sorted starts and ends, two pointers)O(n log n)O(n)

1Brute force (try every left end)

TimeO(n²)n candidates, and each one checks all n lights.
SpaceO(1)Only a few counters.

Moving right, the brightness can only rise at a position where some light starts. So the smallest brightest position is always the left end of some light. Try each left end as a candidate and count, by looking at every light, how many lights cover it. Keep the candidate with the largest count, breaking ties by the smaller position.

  1. Set best = 0 and answer = the first light's left end.
  2. For each light i, let x = position - range.
  3. Count the lights j with left end <= x <= right end.
  4. If the count beats best, or ties it with a smaller x, update best and answer.
  5. Return answer.
class Solution {
    public int brightestPosition(int[][] lights) {
        int best = 0;
        int answer = lights[0][0] - lights[0][1];
        for (int[] light : lights) {
            int x = light[0] - light[1];
            int count = 0;
            for (int[] other : lights) {
                if (other[0] - other[1] <= x && x <= other[0] + other[1]) count++;
            }
            if (count > best || (count == best && x < answer)) {
                best = count;
                answer = x;
            }
        }
        return answer;
    }
}

2Line sweep with a sorted map

TimeO(n log n)2n insertions into a balanced tree map, then one pass over at most 2n keys.
SpaceO(n)The map holds up to 2n keys.

Record a change in brightness instead of the brightness itself. A light covering [a, b] adds 1 at a and takes it away again at b + 1, the first position it no longer reaches. Put these changes in a map sorted by position, adding up changes that land on the same spot. Walking the map from left to right with a running total gives the exact brightness at each key, and it stays the same until the next key. The first key where the total sets a new record is the answer.

  1. For each light, add +1 at position - range and -1 at position + range + 1 in a sorted map.
  2. Walk the keys in increasing order, adding each change to cur.
  3. If cur > best, set best = cur and answer = this key. A strict > keeps the smallest position on ties.
  4. Return answer.
class Solution {
    public int brightestPosition(int[][] lights) {
        TreeMap<Integer, Integer> change = new TreeMap<>();
        for (int[] light : lights) {
            change.merge(light[0] - light[1], 1, Integer::sum);
            change.merge(light[0] + light[1] + 1, -1, Integer::sum);
        }
        int cur = 0, best = 0, answer = 0;
        for (Map.Entry<Integer, Integer> e : change.entrySet()) {
            cur += e.getValue();
            if (cur > best) {
                best = cur;
                answer = e.getKey();
            }
        }
        return answer;
    }
}

3Optimal (sorted starts and ends, two pointers)

TimeO(n log n)Sorting the two arrays dominates; the sweep itself moves i and j forward n times each.
SpaceO(n)Two arrays of n numbers.

The brightness at x is the number of lights that have started by x, minus the number that have already stopped (end + 1 <= x). Sort all starts in one array and all stop points (end + 1) in another. Visit the distinct starts from left to right: first count every light starting there, then drop every light whose stop point is at or before it. The total is now the exact brightness at that start, and only starts can be new records. This is the same sweep as the map, but on two plain sorted arrays, which is lighter in practice.

  1. Build starts[i] = position - range and stops[i] = position + range + 1. Sort both.
  2. Set i = j = cur = best = 0.
  3. While i < n: let x = starts[i]. Add one to cur for every start equal to x, moving i forward.
  4. Then subtract one for every stop <= x, moving j forward.
  5. If cur > best, set best = cur and answer = x.
  6. Return answer.
class Solution {
    public int brightestPosition(int[][] lights) {
        int n = lights.length;
        int[] starts = new int[n], stops = new int[n];
        for (int k = 0; k < n; k++) {
            starts[k] = lights[k][0] - lights[k][1];
            stops[k] = lights[k][0] + lights[k][1] + 1;
        }
        Arrays.sort(starts);
        Arrays.sort(stops);
        int i = 0, j = 0, cur = 0, best = 0, answer = 0;
        while (i < n) {
            int x = starts[i];
            while (i < n && starts[i] == x) {
                cur++;
                i++;
            }
            while (j < n && stops[j] <= x) {
                cur--;
                j++;
            }
            if (cur > best) {
                best = cur;
                answer = x;
            }
        }
        return answer;
    }
}

Edge cases to test

  • A single light: the answer is its left end, position - range
  • Range 0: the light covers exactly one position
  • Two lights that only touch at one point, like [0, 2] and [2, 4]: the ends are inclusive, so position 2 has brightness 2
  • Two lights with a gap of one between them, like [0, 2] and [3, 5]: they never overlap, so the answer is the smaller left end
  • Several positions tie for the maximum: return the smallest one
  • Many lights with the same left end: all of them must be added before comparing
  • Coordinates down to -2 * 10^8: negative answers are common, so do not start the answer at 0 or the best brightness at a value a real position could miss

Hints

Hint 1

Each light lights a closed interval [position - range, position + range]. The brightness at x is the number of intervals that contain x.

Hint 2

The brightness only goes up where some interval starts. So the brightest positions always include a left end, and the smallest brightest position is a left end.

Hint 3

Turn each interval into two events: +1 at its start and -1 just after its end, at end + 1. Sweep the events from left to right and keep a running total.

FAQ

What is the best time complexity for Brightest Position on Street?

Optimal (sorted starts and ends, two pointers) runs in O(n log n) time and O(n) extra space. Sorting the two arrays dominates; the sweep itself moves i and j forward n times each.

Which pattern does Brightest Position on Street use?

It is a intervals problem that uses the line sweep pattern. Other problems with the same pattern: Meeting Rooms II, Car Pooling, Employee Free Time.

Is there a brute force solution for Brightest Position on Street?

Yes. Brute force (try every left end) takes O(n²) time and O(1) space. Moving right, the brightness can only rise at a position where some light starts.

Which edge cases should I test for Brightest Position on Street?

A single light: the answer is its left end, position - range; Range 0: the light covers exactly one position; Two lights that only touch at one point, like [0, 2] and [2, 4]: the ends are inclusive, so position 2 has brightness 2; Two lights with a gap of one between them, like [0, 2] and [3, 5]: they never overlap, so the answer is the smaller left end; Several positions tie for the maximum: return the smallest one; Many lights with the same left end: all of them must be added before comparing; Coordinates down to -2 10^8: negative answers are common, so do not start the answer at 0 or the best brightness at a value a real position could miss.