Wind Field Tracker for Hot Air Balloons
Data Structure DesignModel answerLast updated
Build a system that tracks balloon altitudes, computes spatially-varying wind exposure from multiple sources, and identifies stable balloons above a threshold.
You're building a real-time tracking system for a hot air balloon competition. Your task is to implement a BalloonFestival class that manages balloon positions, wind conditions at different altitudes, and determines which of your team's balloons are performing well.
API Specification
Constructor
__init__(yourBalloonNames: list[str])
Initialize the system with the names of your team's balloons. Any balloon names encountered later that aren't in this list belong to competing teams. Each balloon name is unique across all teams. Constraint: 1 ≤ len(yourBalloonNames) < 2^20.
Methods
BalloonAscended(timestamp: float, balloonName: str, altitude: float) -> bool
Records that a balloon has launched or moved to a new altitude at the given timestamp. Balloons start in a stable state when they ascend. Returns True if successful, False otherwise.
BalloonDescended(timestamp: float, balloonName: str) -> bool
Records that a balloon has landed and is no longer airborne. Returns True if successful, False otherwise.
SetWindSpeed(timestamp: float, altitude: float, windSpeed: float) -> bool
Updates the wind speed centered at a specific altitude. Constraints: 0 < altitude < 2^15 and 0 ≤ windSpeed < 2^5. Returns True if successful, False otherwise.
InspectBalloons(timestamp: float) -> list[str]
Returns a sorted list of your team's balloon names that meet both criteria at the given timestamp:
- The balloon is stable
- The balloon's altitude is at or above the highest stable competitor balloon
If no balloons qualify, return an empty list.
Wind Physics Model
Wind sources at different altitudes contribute to the total wind experienced by a balloon. For each defined wind source:
contribution = windSpeed / (1 + ((balloonAltitude - sourceAltitude) / 100)²)
The total wind speed at a balloon's altitude is the sum of all source contributions.
Stability Rules
- A balloon becomes unstable immediately when the wind speed at its altitude exceeds 15 m/s
- An unstable balloon regains stability only after experiencing wind ≤ 15 m/s continuously for at least 300 seconds
- When a balloon moves to a new altitude, it resets to stable state and then immediately checks wind conditions at the new location
Additional Requirements
- Timestamps must be non-decreasing; operations with earlier timestamps than previously seen should fail
- Design efficient data structures to handle many events over time
- Handle edge cases like balloons moving while unstable, overlapping wind sources, and boundary conditions
Hints
Hint 1
Wind conditions are piecewise constant between events—nothing changes until someone moves a balloon or adjusts a wind source
Hint 2
Track per-balloon state lazily: record when calm conditions began rather than scheduling future recovery events
Hint 3
When a wind source changes, you can update all affected balloons incrementally rather than recomputing from scratch
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that wind conditions remain constant between discrete events. We only need to update balloon states when:
- A wind source is added or modified
- A balloon changes altitude
- Someone queries the system
This enables a lazy evaluation strategy for stability tracking.
Data Structures
Per-Balloon State:
altitude: current heightwindSpeed: cached total wind at current positionisUnstable: whether the balloon has been knocked unstablecalmStartTime: when continuous calm conditions began (null if currently windy)
Global State:
teamBalloons: set of your team's balloon nameswindSources: map from altitude → wind speedactiveBalloons: map from balloon name → balloon statelastTimestamp: most recent timestamp seen
Stability Transitions
When wind at a balloon's location changes:
- Wind > 15: Mark
isUnstable = true, setcalmStartTime = null - Wind ≤ 15 and was windy: Set
calmStartTime = currentTime - Wind ≤ 15 and was already calm: Keep existing
calmStartTime(calm period continues)
A balloon is stable at time t if:
- It's not marked unstable, OR
calmStartTimeexists andt - calmStartTime ≥ 300
When checking stability, we can "promote" a recovered balloon from unstable back to stable lazily.
Wind Field Updates
When a wind source changes from oldSpeed to newSpeed at altitude a, update every airborne balloon at height h:
Δwind = (newSpeed - oldSpeed) / (1 + ((h - a) / 100)²)
balloon.windSpeed += Δwind
This incremental update is O(1) per balloon rather than O(sources) per balloon.
Inspection Algorithm
- Find the maximum altitude among stable competitor balloons (or -∞ if none exist)
- Filter your team's balloons: stable AND altitude ≥ threshold
- Sort by name and return
Complexity Analysis
Let B = number of airborne balloons, S = number of wind sources, and K = qualifying balloons returned.
| Operation | Time Complexity | Explanation |
|---|---|---|
BalloonAscended | O(S) | Must compute full wind sum at new altitude |
BalloonDescended | O(1) | Simple state removal |
SetWindSpeed | O(B) | Incremental update to each airborne balloon |
InspectBalloons | O(B + K log K) | Scan all balloons, sort results |
Space: O(N + S) where N is total distinct balloon names.
Optimization opportunity: Balloons at the same altitude experience identical wind. Grouping by altitude reduces SetWindSpeed to O(distinct altitudes) instead of O(B). This is worth mentioning but likely over-engineered for an assessment.
Edge Cases
- Boundary values: Wind exactly 15.0 is stable; 300 seconds exactly is sufficient for recovery
- Re-ascending while unstable: Balloon resets to stable, then immediately checks new altitude's wind
- Descend and re-ascend: Balloon starts completely fresh, no memory of previous instability
- No stable competitors: Threshold is effectively -∞, so all your stable balloons qualify
- Ties: A balloon at exactly the competitor's altitude qualifies (≥ not >)
- Invalid operations: Non-monotonic timestamps, unknown balloons, out-of-range parameters all return False
- Floating-point precision: Incremental updates can accumulate rounding errors near threshold boundaries
Implementation
import math
from typing import Dict, List, Optional, Set
class _BalloonState:
__slots__ = ("altitude", "windSpeed", "isUnstable", "calmStartTime")
def __init__(self, altitude: float):
self.altitude = altitude
self.windSpeed = 0.0
self.isUnstable = False
self.calmStartTime: Optional[float] = None
class BalloonFestival:
WIND_THRESHOLD = 15.0
CALM_DURATION = 300.0
def __init__(self, yourBalloonNames: List[str]):
self.teamBalloons: Set[str] = set(yourBalloonNames)
self.windSources: Dict[float, float] = {}
self.activeBalloons: Dict[str, _BalloonState] = {}
self.lastTimestamp = -math.inf
def _isValidTimestamp(self, t: float) -> bool:
return isinstance(t, (int, float)) and math.isfinite(t) and t >= self.lastTimestamp
def _computeContribution(self, sourceAlt: float, sourceSpeed: float, balloonAlt: float) -> float:
delta = (balloonAlt - sourceAlt) / 100.0
return sourceSpeed / (1.0 + delta * delta)
def _computeTotalWind(self, altitude: float) -> float:
return sum(
self._computeContribution(srcAlt, srcSpeed, altitude)
for srcAlt, srcSpeed in self.windSources.items()
)
def _updateBalloonWind(self, balloon: _BalloonState, newWind: float, timestamp: float) -> None:
balloon.windSpeed = newWind
if newWind > self.WIND_THRESHOLD:
balloon.isUnstable = True
balloon.calmStartTime = None
elif balloon.calmStartTime is None:
balloon.calmStartTime = timestamp
def _isStable(self, balloon: _BalloonState, timestamp: float) -> bool:
if not balloon.isUnstable:
return True
if balloon.calmStartTime is not None:
if timestamp - balloon.calmStartTime >= self.CALM_DURATION:
balloon.isUnstable = False
return True
return False
def BalloonAscended(self, timestamp: float, balloonName: str, altitude: float) -> bool:
if not self._isValidTimestamp(timestamp):
return False
if not isinstance(altitude, (int, float)) or not math.isfinite(altitude) or altitude < 0:
return False
self.lastTimestamp = timestamp
state = _BalloonState(altitude)
totalWind = self._computeTotalWind(altitude)
self._updateBalloonWind(state, totalWind, timestamp)
self.activeBalloons[balloonName] = state
return True
def BalloonDescended(self, timestamp: float, balloonName: str) -> bool:
if not self._isValidTimestamp(timestamp):
return False
if balloonName not in self.activeBalloons:
return False
self.lastTimestamp = timestamp
del self.activeBalloons[balloonName]
return True
def SetWindSpeed(self, timestamp: float, altitude: float, windSpeed: float) -> bool:
if not self._isValidTimestamp(timestamp):
return False
if not (0 < altitude < 2**15 and 0 <= windSpeed < 2**5):
return False
self.lastTimestamp = timestamp
oldSpeed = self.windSources.get(altitude, 0.0)
self.windSources[altitude] = windSpeed
deltaSpeed = windSpeed - oldSpeed
for balloon in self.activeBalloons.values():
contribution = self._computeContribution(altitude, deltaSpeed, balloon.altitude)
newWind = balloon.windSpeed + contribution
self._updateBalloonWind(balloon, newWind, timestamp)
return True
def InspectBalloons(self, timestamp: float) -> List[str]:
if not self._isValidTimestamp(timestamp):
return []
self.lastTimestamp = timestamp
maxCompetitorAltitude = -math.inf
for name, balloon in self.activeBalloons.items():
if name not in self.teamBalloons and self._isStable(balloon, timestamp):
maxCompetitorAltitude = max(maxCompetitorAltitude, balloon.altitude)
qualifyingBalloons = []
for name, balloon in self.activeBalloons.items():
if name in self.teamBalloons:
if self._isStable(balloon, timestamp) and balloon.altitude >= maxCompetitorAltitude:
qualifyingBalloons.append(name)
return sorted(qualifyingBalloons)
Common Mistakes
- Eager scheduling: Attempting to schedule "becomes stable at t+300" events creates complexity. Lazy evaluation is cleaner.
- Recomputing wind from scratch: On every wind update, recalculating total wind for all balloons is O(B×S). Incremental updates are O(B).
- Missing re-ascend reset: Forgetting that moving to a new altitude resets stability state leads to incorrect tracking.
- Confusing "stable at t" with "becomes stable at t": The stability check is evaluated at inspection time, not when conditions first become favorable.
- Off-by-one on recovery time: The rule is "at least 300 seconds", meaning
t - calmStart >= 300(inclusive), not>.