Simulate Message Spreading in an Orbital Network
Data Structure DesignModel answerLast updated
Simulate timed, discrete-event message propagation across a satellite graph and fire report callbacks in exact time and ID order.
Design an online simulation class SatelliteNetwork that models message propagation and reporting over an undirected network of satellites.
Implement the following public operations:
satellite_connected(satellite_id): Adds a new satellite node. Ifsatellite_idwas already registered, trigger the callbackErrDuplicateSatelliteId(satellite_id)and do not modify the network.relationship_established(satellite_id1, satellite_id2): Establishes a bidirectional link between two registered satellites. If either ID is not registered, invokeErrInvalidSatelliteId(offending_id)for the first invalid ID encountered and ignore the operation.message_received(satellite_ids): Simulates an independent broadcast starting simultaneously at time $t = 0$ at all listed satellites. If any ID insatellite_idsis invalid, invokeErrInvalidSatelliteId(offending_id)for each invalid reference.
Propagation Mechanics
- Transmission Speed: When a satellite receives a message at time $t$, it attempts to forward it to all directly connected neighbors in increasing
SatelliteIdorder. Each individual forwarding attempt takes exactly 10 seconds of sender time. The first attempt reaches its target at $t + 10$, the second at $t + 20$, and so forth. - Parent Exemption: A satellite never forwards the message back to the sender that first notified it.
- First Arrival Wins: A satellite processes only its first message reception. Receptions occurring later are ignored.
- In-Flight Delays: If neighbor $V$ receives the message from another route while sender $U$ is transmitting to $V$, sender $U$'s 10-second transmission attempt is not cancelled; $U$ remains busy for those 10 seconds before moving to its next candidate neighbor.
- Neighbor Skipping: At the instant a satellite is free to start its next transmission, it skips any neighbor that has already received the message (or is its parent) at zero cost in time.
Reporting Back to Earth
- A satellite becomes ready to report back to Earth as soon as all of its direct neighbors have received the message (from any source).
- Upon satisfying this condition at time $T_{\text{all_notified}}$, the satellite spends 30 seconds preparing its report and sends it back at $T_{\text{report}} = T_{\text{all_notified}} + 30$.
- Note that $T_{\text{all_notified}}$ is equivalent to $\max(\text{recv}[u], \max_{v \in \text{neighbors}(u)} \text{recv}[v])$. For an isolated satellite with no neighbors, $T_{\text{all_notified}} = \text{recv}[u]$.
- Whenever a report arrives, trigger the callback
OnSatelliteReportedBack(satellite_id). - Callbacks for a message run must be triggered in strictly non-decreasing order of delivery time. If multiple reports complete at the exact same second, invoke them in ascending order of
satellite_id.
Hints
Hint 1
Model the network propagation as a discrete-event simulation using a min-heap ordered by timestamp.
Hint 2
When multiple events occur at the exact same timestamp t, process message deliveries (DELIVER) before satellite state updates (ADVANCE) to ensure senders see up-to-date recipient statuses at time t.
Hint 3
After computing the first arrival time recv[u] for every reachable satellite, the report time for any satellite u simplifies to max(recv[u], max_{v in neighbors(u)} recv[v]) + 30.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem requires simulating time-based message forwarding on an undirected graph. Unlike standard Breadth-First Search (BFS) where propagation across edges is uniform and simultaneous, each node acts as a single-threaded queue: it transmits to neighbors sequentially, spending 10 seconds per attempt. Furthermore, nodes skip neighbors that are already notified at the moment the send would begin.
We solve this using a discrete-event simulation with a priority queue (min-heap):
- Event Priority: Events are ordered primarily by time
t. To resolve simultaneous events cleanly, we prioritizeDELIVERevents beforeADVANCEevents at the same timestamp $t$. This ensures that if a node receives a message at time $t$, all other nodes making decisions at time $t$ will correctly recognize that node as already notified. - State Tracking:
recv[u]: Earliest time satellite $u$ received the message.parent[u]: Satellite that successfully delivered the message to $u$.ptr[u]: Index tracking $u$'s progress through its sorted list of neighbors.
- Simulation Loop:
DELIVER(t, sender, target): The 10-second transmission fromsendertotargetfinishes at $t$. Iftargethas not been reached yet, recordrecv[target] = t, set its parent, and schedule anADVANCE(t, target)event. Additionally, scheduleADVANCE(t, sender)becausesenderis now free to process its next neighbor.ADVANCE(t, u): Satellite $u$ checks its next neighbor in sorted order. If the neighbor is $u$'s parent or has already received the message (i.e., exists inrecv), $u$ skips it immediately (taking 0 seconds) and increments its neighbor index. When an unnotified neighbor is found, $u$ schedules aDELIVER(t + 10, u, neighbor).
- Report Computation:
Once the discrete-event simulation completes, all reachable satellites have their minimum reception times stored in
recv. For any reached satellite $u$, all of its neighbors will also eventually be reached. The report time for satellite $u$ is given by: $$T_{\text{report}}(u) = \max\left(\text{recv}[u], \max_{v \in \text{neighbors}(u)} \text{recv}[v]\right) + 30$$ We collect all tuple pairs $(T_{\text{report}}(u), u)$, sort them, and invokeOnSatelliteReportedBack(u)in order.
Python 3 Implementation
import heapq
DELIVER = 0
ADVANCE = 1
SEND_DELAY = 10
REPORT_DELAY = 30
class SatelliteNetwork:
def __init__(self, on_reported_back, err_duplicate_id, err_invalid_id):
self.on_reported_back = on_reported_back
self.err_duplicate_id = err_duplicate_id
self.err_invalid_id = err_invalid_id
self.adj = {}
self._sorted_neighbors_cache = {}
def satellite_connected(self, sid: int) -> None:
if sid in self.adj:
self.err_duplicate_id(sid)
return
self.adj[sid] = set()
def relationship_established(self, a: int, b: int) -> None:
if a not in self.adj:
self.err_invalid_id(a)
return
if b not in self.adj:
self.err_invalid_id(b)
return
if a == b:
return
self.adj[a].add(b)
self.adj[b].add(a)
self._sorted_neighbors_cache.pop(a, None)
self._sorted_neighbors_cache.pop(b, None)
def _get_sorted_neighbors(self, u: int) -> list:
if u not in self._sorted_neighbors_cache:
self._sorted_neighbors_cache[u] = sorted(self.adj[u])
return self._sorted_neighbors_cache[u]
def message_received(self, satellite_ids: list) -> None:
# Validate inputs
valid_sources = []
seen_sources = set()
for sid in satellite_ids:
if sid not in self.adj:
self.err_invalid_id(sid)
elif sid not in seen_sources:
seen_sources.add(sid)
valid_sources.append(sid)
if not valid_sources:
return
# Discrete Event Simulation setup
recv = {}
parent = {}
ptr = {}
heap = []
for s in valid_sources:
recv[s] = 0
parent[s] = None
ptr[s] = 0
heapq.heappush(heap, (0, ADVANCE, s, 0))
while heap:
t, event_type, u, v = heapq.heappop(heap)
if event_type == DELIVER:
sender, target = u, v
if target not in recv:
recv[target] = t
parent[target] = sender
ptr[target] = 0
heapq.heappush(heap, (t, ADVANCE, target, 0))
# Sender becomes unbusy at time t
heapq.heappush(heap, (t, ADVANCE, sender, 0))
elif event_type == ADVANCE:
curr = u
neighbors = self._get_sorted_neighbors(curr)
idx = ptr[curr]
# Fast-forward past neighbors already notified or parent
while idx < len(neighbors) and (neighbors[idx] == parent[curr] or neighbors[idx] in recv):
idx += 1
ptr[curr] = idx
if idx < len(neighbors):
target_nbr = neighbors[idx]
ptr[curr] = idx + 1
heapq.heappush(heap, (t + SEND_DELAY, DELIVER, curr, target_nbr))
# Calculate back-reporting timestamps
reports = []
for u in recv:
max_time = recv[u]
for nbr in self.adj[u]:
if nbr in recv and recv[nbr] > max_time:
max_time = recv[nbr]
reports.append((max_time + REPORT_DELAY, u))
# Sort primarily by delivery time, secondarily by satellite_id
reports.sort()
for _, sid in reports:
self.on_reported_back(sid)
Complexity Analysis
-
Time Complexity:
satellite_connected: $O(1)$ hash map insertion.relationship_established: $O(1)$ set insertion and cache invalidation.message_received:- Each satellite enters the heap as an
ADVANCEevent at most $O(\text{degree}(u))$ times. - Across all reached nodes, total heap pushes/pops are bounded by $O(E)$, where $E$ is the number of edges in connected components containing initial source satellites.
- Sorting neighbor lists is cached and amortized over dynamic network modifications.
- Final sorting of report times takes $O(V \log V)$ where $V$ is the number of reached satellites.
- Overall Time Complexity per simulation run: $O(E \log V + V \log V)$.
- Each satellite enters the heap as an
-
Space Complexity:
- Graph representation: $O(V + E)$ where $V$ is total satellites and $E$ total links.
- Simulation state (
recv,parent,ptr, priority queue): $O(V + E)$. - Total Space Complexity: $O(V + E)$.