← Questions
Safe ranges between planets' gravity zones
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Nov 2025. It tests intervals and sorting.
A route runs along the x-axis. Each planet is given as (center, radius) and makes the closed range [center - radius, center + radius] unsafe. Return every maximal safe range on the whole real line, in order. Ranges may overlap, nest or touch, and the planets come in any order.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
safe_ranges(planets: list[tuple[int, int]]) -> list[tuple[int | None, int | None]]— each result(start, end)means the open rangestart < x < end.Nonestands for minus infinity on the left or plus infinity on the right.
Example
safe_ranges([(3, 1), (10, 2)]) -> [(None, 2), (4, 8), (12, None)] # unsafe: [2, 4] and [8, 12]
safe_ranges([(2, 1), (5, 2)]) -> [(None, 1), (7, None)] # [1, 3] and [3, 7] touch, so no gap
safe_ranges([(5, 4), (4, 1)]) -> [(None, 1), (9, None)] # [3, 5] sits inside [1, 9]
safe_ranges([(0, 0)]) -> [(None, 0), (0, None)] # a single unsafe point
safe_ranges([]) -> [(None, None)]
Constraints
-
0 <= len(planets) <= 2 · 10^5. -
-10^9 <= center <= 10^9,0 <= radius <= 10^9.
Clarifying questions
- Is the boundary point
center ± radiusunsafe? (Yes: the unsafe range is closed.) - Do touching ranges leave a safe gap of zero width? (No.)
- How should unbounded ends be represented?
- Is the input sorted?
What a strong answer covers
- Turn each planet into
[c - r, c + r], sort by start, and merge any range whose start is<=the current end. - The gaps before the first merged range, between consecutive ones and after the last are the answer.
- O(n log n) time, O(n) space; the special case of no planets.
- Using 64-bit values when
c ± rcan leave the 32-bit range. - Tests: nested, touching, identical and single-point ranges.
Follow-ups
- Return only the safe ranges inside a trip from
atob, or whether the trip fromatobis safe at all. - Planets are added one at a time while queries arrive.
- The route is in 2D and zones are circles. What changes?
Where it's asked
- Google · First round: coding · Last asked Nov 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
