Find safe travel intervals between planet influences
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates interval arithmetic and line-sweep reasoning for computing complements on the real line, testing competencies in sorting, interval merging, and handling unbounded ranges within the Coding & Algorithms domain and focusing on practical application rather than purely conceptual theory.
Constraints
- 0 <= len(planets) <= 200000
- -10^9 <= c <= 10^9
- 0 <= r <= 10^9
Examples
Input: []
Expected Output: [(None, None)]
Explanation: With no planets, no point is unsafe, so the entire real line is safe.
Input: [(3, 1), (10, 2)]
Expected Output: [(None, 2), (4, 8), (12, None)]
Explanation: The unsafe intervals are [2, 4] and [8, 12]. Their complement is (-infinity, 2), (4, 8), and (12, +infinity).
Input: [(-4, 3), (1, 2), (0, 5)]
Expected Output: [(None, -7), (5, None)]
Explanation: The unsafe intervals are [-7, -1], [-1, 3], and [-5, 5], which merge into one interval [-7, 5].
Input: [(0, 1), (3, 2), (7, 0)]
Expected Output: [(None, -1), (5, 7), (7, None)]
Explanation: The first two unsafe intervals are [-1, 1] and [1, 5], which touch and must be merged into [-1, 5]. The point interval [7, 7] removes only x = 7, leaving a gap (5, 7) and then (7, +infinity).
Input: [(-2, 0), (2, 0)]
Expected Output: [(None, -2), (-2, 2), (2, None)]
Explanation: Each planet blocks only a single point: x = -2 and x = 2. The safe regions are everything else.
Solution
def solution(planets):
if not planets:
return [(None, None)]
intervals = [(c - r, c + r) for c, r in planets]
intervals.sort()
merged = []
for left, right in intervals:
if not merged or left > merged[-1][1]:
merged.append([left, right])
else:
if right > merged[-1][1]:
merged[-1][1] = right
safe = []
safe.append((None, merged[0][0]))
for i in range(1, len(merged)):
prev_right = merged[i - 1][1]
curr_left = merged[i][0]
if prev_right < curr_left:
safe.append((prev_right, curr_left))
safe.append((merged[-1][1], None))
return safeTime complexity: O(n log n). Space complexity: O(n).
Hints
- First convert every planet (c, r) into the unsafe interval [c - r, c + r].
- Sort the unsafe intervals and merge all overlapping or touching ones. The safe intervals are the gaps before, between, and after the merged intervals.