Four Algorithm Problems: Graphs, Search, Simulation, and Design
Data Structure DesignModel answerLast updated
Solve four independent problems covering Eulerian path reconstruction, timestamped key-value lookup, ray reflection simulation, and a high-throughput score tracker.
Overview
Four self-contained problems. Each tests a different skill. Solve them in order — they increase in design complexity. For problems with ambiguous behavior, state your assumptions before writing code.
Problem 1: Reconstruct a Flight Route
You are given a list of one-way flight tickets, each represented as [origin, destination]. Reconstruct a single route that uses every ticket exactly once. If more than one valid route exists, return the lexicographically smallest one. If no valid route exists (the tickets cannot form a single continuous path), return an empty list.
def find_itinerary(tickets: list[list[str]]) -> list[str]
Example:
tickets = [["LAX","ORD"],["JFK","LAX"],["ORD","JFK"]]
→ ["JFK","LAX","ORD","JFK"]
Constraints:
- Up to 10,000 tickets.
- Airport codes are uppercase strings.
- Duplicate tickets are allowed and represent distinct flights.
Problem 2: Versioned Key-Value Store
Build a class that stores values tagged with integer timestamps. It must support two operations:
put(key, value, timestamp)— store the value for the given key at the given timestamp.get(key, timestamp)— return the value stored for that key at the largest timestamp less than or equal to the given one. ReturnNoneif no such entry exists.
class TimeMap:
def put(self, key: str, value, timestamp: int) -> None: ...
def get(self, key: str, timestamp: int): ...
Example:
tm = TimeMap()
tm.put("city", "Paris", 10)
tm.get("city", 15) → "Paris"
tm.get("city", 5) → None
Constraints:
- For any given key,
putcalls arrive in strictly increasing timestamp order. - Optimize
getfor O(log n) time.
Problem 3: Bouncing Ray on a Grid
You have an N×M grid where each cell is either 0 (open) or 1 (blocked). A ray starts at cell (r, c) traveling in direction (dr, dc). At each step:
- Look at the next cell in the current direction.
- If it is outside the grid, the ray exits — stop.
- If it is blocked (
1), rotate the direction 90° clockwise without moving. - If it is open (
0), move there.
Return the list of coordinates the ray visits (including the start), stopping when the ray exits the grid or enters an infinite loop.
def ray_path(grid: list[list[int]], r: int, c: int, dr: int, dc: int) -> list[tuple[int,int]]
Constraints:
- Grid dimensions up to 1,000×1,000.
- The starting cell is always open.
- Directions use row/column convention: up is
(-1,0), right is(0,1).
Problem 4: Real-Time Score Leaderboard
Design a leaderboard for a game with up to 1,000,000 players and a very high rate of score updates.
Support these operations:
update_score(player_id, score)— set the player's score to the new value (replacing any previous score).top_k(k)— return the IDs of the top k players by score, highest first.
top_k must run in sub-linear time relative to the total number of players. Explain your data structure choice and the complexity of each operation.
Hints
Hint 1
For Problem 1, think of each ticket as a directed edge and the whole problem as finding an Eulerian path. The tricky part is choosing the start node correctly when no origin is explicitly given — derive it from in/out degree counts.
Hint 2
For Problem 2, since timestamps are strictly increasing per key, the stored list is always sorted. That means you can use binary search directly — no sorting needed at query time.
Hint 3
For Problem 4, a plain heap won't work because it can't efficiently update or delete an arbitrary entry. Think about what data structure supports O(log n) insert, delete, and ordered iteration — that's your ordered index.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Mindset
Each problem maps to a well-known pattern. The interviewer's goal is to see whether you recognize the pattern quickly, handle the edge cases that break naive solutions, and implement cleanly. State assumptions out loud on Problems 1 and 3 — both are underspecified in ways that matter.
Problem 1: Reconstruct a Flight Route
Pattern: Eulerian path via Hierholzer's algorithm.
Every ticket is a directed edge. Using every ticket exactly once is exactly the definition of an Eulerian path. Hierholzer's algorithm finds it efficiently:
- Store each airport's outgoing destinations in a min-heap (so you always try the lexicographically smallest next hop).
- Run an iterative DFS. Push a node onto the result only when it has no outgoing edges left (post-order).
- Reverse the result at the end.
Post-order insertion is the key insight. A naive greedy approach can reach a dead end too early. Post-order ensures dead-end branches end up at the tail of the route after reversal, preserving lexicographic minimality for the rest.
Choosing the start node. With no fixed origin given, compute in/out degrees:
- If a node has
out - in = 1, it must be the start. - If all nodes are balanced, start at the lexicographically smallest node with outgoing edges (indicating a circuit).
- If more than one node has a surplus or deficit, no Eulerian path exists — return
[].
Verify connectivity at the end: the route must contain exactly len(tickets) + 1 airports. If not, the graph was disconnected.
Complexity: O(E log E) time due to heap operations, O(E) space.
import heapq
from collections import defaultdict
def find_itinerary(tickets: list[list[str]]) -> list[str]:
if not tickets:
return []
graph = defaultdict(list)
out_deg, in_deg = defaultdict(int), defaultdict(int)
for a, b in tickets:
heapq.heappush(graph[a], b)
out_deg[a] += 1
in_deg[b] += 1
start = None
starts = ends = 0
for node in set(out_deg) | set(in_deg):
diff = out_deg[node] - in_deg[node]
if diff == 1:
starts += 1
start = node
elif diff == -1:
ends += 1
elif diff != 0:
return []
if starts > 1 or ends > 1 or starts != ends:
return []
if start is None:
start = min(n for n in out_deg if out_deg[n] > 0)
route, stack = [], [start]
while stack:
node = stack[-1]
if graph[node]:
stack.append(heapq.heappop(graph[node]))
else:
route.append(stack.pop())
route.reverse()
return route if len(route) == len(tickets) + 1 else []
The iterative DFS avoids Python's recursion limit at 10,000 tickets.
Problem 2: Versioned Key-Value Store
Pattern: binary search on a sorted list.
Since put calls for a given key always arrive in increasing timestamp order, the stored timestamp list is always sorted — no work needed to maintain that invariant. For get, use bisect_right(times, t) which returns the number of timestamps ≤ t. The answer is at index i - 1; if i == 0, no valid entry exists.
Complexity: put is O(1). get is O(log n). Space is O(total puts).
Common mistake: using bisect_left instead of bisect_right. With bisect_left, a query timestamp that exactly matches a stored one returns the correct index, but a query between two stored timestamps returns the wrong side. bisect_right handles both cases correctly by always returning the count of timestamps strictly ≤ t.
from bisect import bisect_right
from collections import defaultdict
class TimeMap:
def __init__(self):
self.times = defaultdict(list)
self.values = defaultdict(list)
def put(self, key: str, value, timestamp: int) -> None:
self.times[key].append(timestamp)
self.values[key].append(value)
def get(self, key: str, timestamp: int):
times = self.times.get(key)
if not times:
return None
i = bisect_right(times, timestamp)
return self.values[key][i - 1] if i else None
Problem 3: Bouncing Ray on a Grid
Key assumption to state upfront: when the ray hits a blocked cell, it rotates in place without advancing. A clockwise 90° rotation maps (dr, dc) to (dc, -dr). You can verify: up (-1, 0) → right (0, 1) → down (1, 0) → left (0, -1) → up. This works for diagonal directions too.
Cycle detection: the motion is fully determined by the state (r, c, dr, dc). Track visited states in a set; if a state repeats, the ray is looping — return immediately.
Complexity: at most 4·N·M distinct states for orthogonal directions, so O(N·M) time and space in the worst case.
Edge cases worth mentioning: a cell blocked in all four directions causes the direction to cycle through all four rotations before a state repeats — the visited-state check catches it cleanly. Starting on a boundary cell facing outward produces a single-element path.
def ray_path(grid, r, c, dr, dc):
n, m = len(grid), len(grid[0])
path = [(r, c)]
seen = set()
while True:
state = (r, c, dr, dc)
if state in seen:
return path # infinite loop
seen.add(state)
nr, nc = r + dr, c + dc
if not (0 <= nr < n and 0 <= nc < m):
return path # exits grid
if grid[nr][nc] == 1:
dr, dc = dc, -dr # rotate clockwise, stay in place
else:
r, c = nr, nc
path.append((r, c))
Problem 4: Real-Time Score Leaderboard
Why a heap alone fails: a max-heap gives O(1) peek at the top, but updating an arbitrary player's score requires O(n) to find and remove the old entry. With a million players and high write frequency, that's unacceptable.
The right structure: pair a hash map with a sorted list (backed by a balanced BST internally):
- Hash map:
player_id → scorefor O(1) lookups of current scores. SortedListof(-score, player_id)tuples: negating score keeps the highest score at the front.
Operations:
update_score: look up old score in the hash map, remove(-old_score, player_id)from the sorted list, insert the new tuple, and update the hash map. Each step is O(log N).top_k: slice the first k entries from the sorted list. O(log N + k), which is sub-linear in N.
from sortedcontainers import SortedList
class Leaderboard:
def __init__(self):
self.scores = {}
self.ranked = SortedList() # stores (-score, player_id)
def update_score(self, player_id, score) -> None:
old = self.scores.get(player_id)
if old is not None:
self.ranked.remove((-old, player_id))
self.scores[player_id] = score
self.ranked.add((-score, player_id))
def top_k(self, k: int) -> list:
return [player_id for _, player_id in self.ranked[:k]]
Trade-off to mention: SortedList from sortedcontainers is a pure-Python skip-list-style structure with O(log N) updates. In a production system, a Redis sorted set would serve the same role and scale across machines. If players can only ever increase their score (no decreases), you could optimize further, but the general solution handles both directions cleanly.