KatInterview

Most Overlapped Aisle Along a Line of Lamps

Greedy & IntervalsAuto-graded · 23 test cases
MediumAuto-gradedGreedy & Intervalssweep-lineintervalsdifference-array

Last updated

Find the integer position covered by the most symmetric intervals, returning the smallest on ties, using an event sweep over interval endpoints instead of visiting every position.

A long corridor is described by integer positions on a number line. You are given a list lamps, where each entry lamps[i] = [pos_i, radius_i] is a lamp placed at position pos_i. That lamp lights every integer position from pos_i - radius_i up to pos_i + radius_i, with both endpoints included.

The brightness of an integer position is the number of lamps that light it. Return the integer position with the greatest brightness. If more than one position reaches that greatest brightness, return the smallest of them.

Rules

  • Only integer positions are considered.
  • A lamp with radius_i = 0 lights only its own position pos_i.
  • Several lamps may be placed at the same position; each one is counted separately.
  • lamps is never empty, so the maximum brightness is always at least 1 and an answer always exists.
  • Positions that no lamp lights have brightness 0 and are never the answer.

Constraints

  • 1 <= len(lamps) <= 10^5
  • -10^8 <= pos_i <= 10^8
  • 0 <= radius_i <= 10^8
  • Every lit position fits in a 32-bit signed integer.

Examples

Example 1

Input: brightest_position([[1, 3], [8, 2], [4, 2]])

Output: 2

Example 2

Input: brightest_position([[2, 0], [-2, 0]])

Output: -2

Example 3

Input: brightest_position([[14, 6], [2, 4], [11, 1]])

Output: 10

Hints

Hint 1

The range of positions is far too large to count brightness one position at a time, so think about which positions can actually change the brightness.

Hint 2

Brightness only changes where a lamp's lit range begins (it goes up by one) or just after it ends (it goes down by one). Turn each lamp into two such events.

Hint 3

Sort the events and sweep left to right keeping a running total. Apply all events at the same position before comparing, and only update your best answer on a strictly larger total so the smallest position wins ties.