Bird Physics Tick and Fee-Ratio Block Packing
Greedy & IntervalsModel answerLast updated
Two coding tasks: a one-tick bird movement function with inclusive bounds, and a greedy block builder that scores transactions together with their unconfirmed ancestors.
Solve both of the following tasks and explain your reasoning.
Task A: One simulation tick for a flying character
A side-scrolling game keeps a character at some vertical position. The ceiling is at y = 0, the floor is at y = height, and a positive velocity moves the character downward.
Write:
update_bird(y, velocity, jump_pressed, height, gravity, jump_velocity) -> (new_y, new_velocity, alive)
Per tick:
- If
jump_pressedis true, the current velocity is replaced byjump_velocity(usually negative). Otherwise the current velocity is kept. - Gravity is added to that velocity, giving
new_velocity. - The position moves by the new velocity:
new_y = y + new_velocity. - The character is alive only if
0 <= new_y <= height(both ends inclusive). - Return
(new_y, new_velocity, alive).
Say how your function behaves when a jump happens close to the ceiling, when the character falls past the floor, when it lands exactly on a boundary, and when gravity is zero.
Task B: Assembling a block from dependent transactions
A simplified miner has a pool of pending transactions. Each one has:
id: a unique stringfee: an integersize: an integer number of bytesparents: IDs of transactions that must appear earlier in the same block if this one is included
Given max_size, return an ordered list of transaction IDs for the block, along with the total fee and total size.
Rules:
- A transaction may be included only if every parent is also included and placed before it.
- The summed size of the block must not exceed
max_size. - Do not attempt the optimal knapsack. Use this greedy procedure:
- For each transaction not yet in the block, form its package: the transaction plus every ancestor not yet in the block.
- The package fee and package size are the sums over those not-yet-included transactions.
- Repeatedly pick the package with the highest
package_fee / package_sizeamong those that fit in the remaining space, and append its members in dependency order.
- If the dependency graph has a cycle, report an error.
- Return the ordered IDs, total fee and total size.
Finally, analyse the time complexity of your approach and describe how you would cache or incrementally maintain package data for a very large pool.
Hints
Hint 1
Task A is a direct translation of the rule order: choose the base velocity, add gravity, move by the updated velocity, then test the inclusive bounds. Do not clamp the returned position.
Hint 2
For Task B, run a topological sort once up front. It detects cycles, and its ordering gives you a ready-made way to sort any package into dependency order. Compare ratios by cross-multiplying instead of dividing.
Hint 3
A package that does not fit now can become smaller after some of its ancestors are included, so scores change over time. For the scalable version, ask which transactions' packages change after a package is added (only the descendants) and how a max-heap with lazy invalidation could exploit that.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Task A: Bird tick
Approach
The task is about applying the rules in the stated order. A jump replaces the velocity rather than adding to it, so a jump always has the same strength. Gravity is added after that, and the position is moved by the already-updated velocity. Two common mistakes are moving by the old velocity and adding gravity before the jump override.
def update_bird(y, velocity, jump_pressed, height, gravity, jump_velocity):
base = jump_velocity if jump_pressed else velocity
new_velocity = base + gravity
new_y = y + new_velocity
alive = 0 <= new_y <= height
return new_y, new_velocity, alive
Edge cases
- Jump near the ceiling:
y = 2,jump_velocity = -5,gravity = 1gives velocity-4andnew_y = -2, so the bird is dead. Return the raw position; clamping would hide the result. - Below the floor:
new_y > heightmeans dead. - Exactly on a boundary:
new_y == 0ornew_y == heightis alive because the check is inclusive. - Zero gravity: velocity never changes and the bird moves in a straight line.
- Numeric type: the code works for ints and floats. If you need reproducible physics, use integer sub-pixel units to avoid float drift.
Complexity is O(1) time and space.
Task B: Greedy package selection
Design decisions
- Validation: reject duplicate IDs and non-positive sizes, since the ratio would be undefined.
- Cycle detection: run Kahn's algorithm over parent edges once at the start. If it cannot order every transaction, raise
ValueError. A self-parent counts as a cycle. - Global rank: Kahn's order gives each transaction a rank. Sorting any package by rank yields a valid parents-first order.
- Unknown parents: a transaction with a missing parent, directly or through an ancestor, can never be included. Mark it blocked and skip it.
- Ratio comparison: use
f1 * s2 > f2 * s1to avoid floating-point ties. - Tie-breaking: higher ratio first, then larger package fee, then the smaller anchor ID. This makes the output deterministic.
- Recompute every round: once some ancestors are included, a package that previously did not fit may shrink and fit.
from collections import deque, defaultdict
def assemble_block(transactions, max_size):
pool = {}
for t in transactions:
if t["id"] in pool:
raise ValueError(f"duplicate id {t['id']}")
if t["size"] <= 0:
raise ValueError(f"non-positive size for {t['id']}")
pool[t["id"]] = t
# Kahn's algorithm on known parents; also yields a rank for ordering.
waiting = {i: len({p for p in t["parents"] if p in pool}) for i, t in pool.items()}
kids = defaultdict(list)
for i, t in pool.items():
for p in {p for p in t["parents"] if p in pool}:
kids[p].append(i)
q = deque(sorted(i for i, c in waiting.items() if c == 0))
rank = {}
while q:
i = q.popleft()
rank[i] = len(rank)
for c in kids[i]:
waiting[c] -= 1
if waiting[c] == 0:
q.append(c)
if len(rank) < len(pool):
raise ValueError("dependency cycle detected")
blocked = {}
for i in sorted(rank, key=rank.get):
blocked[i] = any(p not in pool or blocked[p] for p in pool[i]["parents"])
def missing_package(anchor, included):
seen, stack = {anchor}, [anchor]
while stack:
n = stack.pop()
for p in pool[n]["parents"]:
if p not in included and p not in seen:
seen.add(p)
stack.append(p)
return sorted(seen, key=rank.get)
included, block = set(), []
tot_fee = tot_size = 0
while True:
room = max_size - tot_size
best = None # (fee, size, anchor, package)
for tid in sorted(pool):
if tid in included or blocked[tid]:
continue
pkg = missing_package(tid, included)
fee = sum(pool[x]["fee"] for x in pkg)
size = sum(pool[x]["size"] for x in pkg)
if size > room:
continue
if best is None:
best = (fee, size, tid, pkg)
continue
bf, bs = best[0], best[1]
if fee * bs > bf * size or (fee * bs == bf * size and fee > bf):
best = (fee, size, tid, pkg)
if best is None:
break
fee, size, _, pkg = best
block.extend(pkg)
included.update(pkg)
tot_fee += fee
tot_size += size
return block, tot_fee, tot_size
Because candidates are scanned in sorted ID order and best is replaced only on a strict improvement, equal candidates keep the smallest anchor ID.
Correctness
- Dependencies: a package is sorted by topological rank, and every ancestor outside it is already in the block, so parents always come first.
- Capacity: a package is chosen only when
size <= room. - Termination: each round adds at least one transaction or exits.
- Optimality: this is a heuristic, not the optimal knapsack solution, and the spec asks for exactly that. Scoring by package rather than by single transaction is what lets a high-fee child pull in a cheap parent.
Complexity
Let n be the number of transactions and e the number of parent edges.
- Validation plus Kahn's algorithm: O(n + e) (plus O(n log n) for the sorts).
- One package: O(n + e) worst case, plus sorting it.
- One round: O(n · (n + e)).
- Up to n rounds, so the naive total is roughly O(n² · (n + e)). This is fine for tests and far too slow for a large pool.
Scaling and caching
- Cache aggregates per transaction: store
anc_fee,anc_sizeand the missing-ancestor set (or just counts) for every transaction, computed once in topological order. - Only descendants change: when a package is included, only descendants of its members get a smaller package. Walk the descendants, subtract the included members' fee and size from their aggregates, and recompute their scores. Everything else is untouched.
- Max-heap with lazy invalidation: keep entries
(ratio, anchor, version). When an anchor's aggregates change, bump its version and push a new entry. When popping, drop entries whose version is stale or whose anchor is already included. - Discard what does not fit: remaining room only shrinks, so a popped package that does not fit can be dropped. If it later shrinks because ancestors were included, it is re-pushed by step 2.
- Cost: each inclusion costs about O(d log n), where d is the number of affected descendants, instead of a full rescan. The total is bounded by the sum of descendant counts, which is manageable if you cap ancestor and descendant counts per transaction (a common practical limit).
- Memory trade-off: storing full ancestor sets costs O(n · depth) memory. Storing only counts and sums is cheaper, but you then need descendant traversal to maintain them.
Common mistakes
- Dividing floats and then comparing, which creates false ties.
- Scoring transactions alone and ignoring their ancestors.
- Computing packages once and never refreshing them after inclusions.
- Forgetting the unknown-parent case or self-cycles.
- Emitting a package in arbitrary order, which breaks the parent-first rule.