Track and Analyze Obstacle Course Runs
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate obstacle course data structures, track per-stage times, calculate target metrics, and run Monte Carlo probability estimation.
Design an analytics engine to evaluate athlete performance on a multi-stage obstacle course.
The system processes commands operating on two core domain concepts:
-
Run: Represents a single athlete's attempt on a course with
course_obstacle_counttotal obstacles.- It maintains an ordered sequence of completed obstacle durations (in seconds).
- A run is considered complete if the number of recorded obstacle durations equals
course_obstacle_count. - Adding an obstacle time to an already complete run raises a
ValueError. - Summing recorded times gives the current elapsed duration of the run.
-
RunCollection: Manages a set of runs sharing the same
course_obstacle_count.personal_best(): Returns the minimum total completion time among complete runs only. If no complete runs exist, returnsNone.best_of_bests(): Calculates the ideal hypothetical completion time by taking the minimum observed time for each obstacle indexi(from $0$ to $\text{course_obstacle_count} - 1$) across all registered runs (both complete and incomplete) that reached indexi. If any obstacle index has zero recorded times across all runs, returnsNone.chance_of_personal_best(test_run): Uses Monte Carlo simulation ($10{,}000$ iterations) to estimate the probability that an in-progress run will equal or beat (i.e., total time $\le$) the currentpersonal_best().- For each uncompleted obstacle index $i$ in
test_run, sample a duration uniformly at random (with replacement) from the set of all historical times recorded at index $i$ across all runs in the collection. - The simulation uses pseudo-random sampling with a fixed random seed (
seed=0). - If
test_runis already complete, raise aValueError. - If
personal_best()isNone(no finished runs exist), return0.0. - If any remaining obstacle index has no historical recorded times across registered runs, raise a
ValueError. - Returns the fraction of trials where the simulated total run time is $\le$
personal_best().
- For each uncompleted obstacle index $i$ in
You are to implement run_collection_results(course_obstacle_count, operations, arguments) which simulates a sequence of operational instructions and returns a list containing the result of each step (or None for operations that produce no direct output).
Supported Operations
"create_run":args = [run_id]— Instantiates a new run labeledrun_id."add_obstacle_time":args = [run_id, time]— Appendstimeto runrun_id."add_run":args = [run_id]— Registers runrun_idinto the collection."get_run_time":args = [run_id]— Returns the sum of recorded times forrun_id."is_complete":args = [run_id]— ReturnsTrueifrun_idhas completed all obstacles,Falseotherwise."personal_best":args = []— Evaluates and returns the best time among complete runs in the collection."best_of_bests":args = []— Evaluates and returns the theoretical best time across all obstacle stages."chance_of_personal_best":args = [run_id]— Estimates the probability ofrun_idmatching or breakingpersonal_best().
Constraints
- $1 \le \text{course_obstacle_count} \le 100$
- $1 \le \text{len(operations)} \le 1000$
- All obstacle time inputs are positive integers.
- Operations reference valid
run_idvalues created earlier.
Examples
Example 1
Input: run_collection_results(3, ['create_run', 'add_obstacle_time', 'add_obstacle_time', 'create_run', 'add_obstacle_time', 'add_obstacle_time', 'add_obstacle_time', 'add_run', 'create_run', 'add_obstacle_time', 'add_obstacle_time', 'add_run', 'add_run', 'personal_best', 'best_of_bests'], [['a'], ['a', 10], ['a', 5], ['b'], ['b', 4], ['b', 8], ['b', 6], ['b'], ['c'], ['c', 7], ['c', 3], ['c'], ['a'], [], []])
Output: [None, None, None, None, None, None, None, None, None, None, None, None, None, 18, 13]
Example 2
Input: run_collection_results(3, ['create_run', 'add_obstacle_time', 'create_run', 'add_obstacle_time', 'add_run', 'create_run', 'add_obstacle_time', 'add_obstacle_time', 'add_run', 'create_run', 'add_obstacle_time', 'add_obstacle_time', 'add_run', 'best_of_bests'], [['a'], ['a', 9], ['b'], ['b', 2], ['b'], ['c'], ['c', 8], ['c', 4], ['c'], ['d'], ['d', 6], ['d', 5], ['d'], []])
Output: [None, None, None, None, None, None, None, None, None, None, None, None, None, None]
Hints
Hint 1
Make sure personal_best only considers finished runs—partial runs with fewer completed obstacles have smaller sums that must be ignored.
Hint 2
For best_of_bests, gather all recorded times at each position index i across both complete and incomplete runs. If any position has no recorded times, return None.
Hint 3
Pre-compute the candidate pool of historical times for each missing stage index before running the 10,000 Monte Carlo trials to maintain good performance.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires implementing and managing state across domain concepts: Run and RunCollection.
-
State Tracking (
RunandRunCollection):Runkeeps track of its recorded obstacle durations. It determines completeness by comparinglen(obstacle_times)toobstacle_count.RunCollectionholds references to addedRuninstances.
-
Metrics Computation:
personal_best(): Filters runs in the collection to only those wherecompleteisTrue, sums each complete run's times, and takes the minimum sum. If no complete runs exist, it returnsNone.best_of_bests(): For each stage index $i \in [0, \text{obstacle_count} - 1]$, collectsobstacle_times[i]from all runs having at least $i+1$ recorded times. If any index $i$ has an empty collection of recorded times, returnsNone. Otherwise, sums the minimum recorded time at each index $i$.
-
Monte Carlo Simulation (
chance_of_personal_best):- Collects the available historical times at each uncompleted stage $i \ge \text{len}(\text{test_run.obstacle_times})$.
- Uses
random.Random(seed=0)to generate $10{,}000$ trial runs. - In each trial, independent stage durations are drawn via
rng.choice(times). - Counts the proportion of trials where
elapsed_time + simulated_remaining_time <= personal_best().
Complexity Analysis
- Time Complexity:
personal_best(): $\mathcal{O}(R \cdot K)$ where $R$ is the number of runs in the collection and $K$ is the course length.best_of_bests(): $\mathcal{O}(R \cdot K)$ to scan recorded obstacle times across all runs.chance_of_personal_best(): $\mathcal{O}(R \cdot K + T \cdot M)$ where $T = 10{,}000$ is the trial count and $M \le K$ is the remaining obstacles.
- Space Complexity:
- $\mathcal{O}(R \cdot K)$ total memory stored for all runs and their logged split times.
import random
from typing import List
class Run:
def __init__(self, obstacle_count: int):
self.obstacle_count = obstacle_count
self.obstacle_times = []
@property
def complete(self) -> bool:
return len(self.obstacle_times) == self.obstacle_count
def add_obstacle_time(self, t: int):
if self.complete:
raise ValueError("run is already complete")
self.obstacle_times.append(t)
def get_run_time(self) -> int:
return sum(self.obstacle_times)
class RunCollection:
def __init__(self, obstacle_count: int):
self.obstacle_count = obstacle_count
self.runs = []
def add_run(self, run: Run):
if run.obstacle_count != self.obstacle_count:
raise ValueError("run belongs to a different course")
self.runs.append(run)
def personal_best(self):
complete_times = [run.get_run_time() for run in self.runs if run.complete]
return min(complete_times) if complete_times else None
def best_of_bests(self):
minima = []
for i in range(self.obstacle_count):
observed = [run.obstacle_times[i] for run in self.runs if len(run.obstacle_times) > i]
if not observed:
return None
minima.append(min(observed))
return sum(minima)
def chance_of_personal_best(self, test_run: Run, trials: int = 10000, seed: int = 0) -> float:
if test_run.complete:
raise ValueError("test_run must be in progress")
if test_run.obstacle_count != self.obstacle_count:
raise ValueError("run belongs to a different course")
best = self.personal_best()
if best is None:
return 0.0
remaining = []
for i in range(len(test_run.obstacle_times), self.obstacle_count):
observed = [run.obstacle_times[i] for run in self.runs if len(run.obstacle_times) > i]
if not observed:
raise ValueError("no historical time for a remaining obstacle")
remaining.append(observed)
rng = random.Random(seed)
elapsed = test_run.get_run_time()
successes = 0
for _ in range(trials):
total = elapsed + sum(rng.choice(times) for times in remaining)
if total <= best:
successes += 1
return successes / trials
def run_collection_results(course_obstacle_count: int, operations: List[str], arguments: List[List]) -> List:
runs = {}
collection = RunCollection(course_obstacle_count)
results = []
for operation, args in zip(operations, arguments):
if operation == "create_run":
run_id = args[0]
runs[run_id] = Run(course_obstacle_count)
results.append(None)
elif operation == "add_obstacle_time":
run_id, time = args
runs[run_id].add_obstacle_time(time)
results.append(None)
elif operation == "add_run":
collection.add_run(runs[args[0]])
results.append(None)
elif operation == "get_run_time":
results.append(runs[args[0]].get_run_time())
elif operation == "is_complete":
results.append(runs[args[0]].complete)
elif operation == "personal_best":
results.append(collection.personal_best())
elif operation == "best_of_bests":
results.append(collection.best_of_bests())
elif operation == "chance_of_personal_best":
results.append(collection.chance_of_personal_best(runs[args[0]], seed=0))
else:
raise ValueError("unknown operation")
return results