Bipedal Dinosaur Speed Leaderboard
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given two string arrays, dataset1 and dataset2, each holding the lines of a three-column CSV table whose first element (index 0) is its header line:
dataset1begins with"NAME,LEG_LENGTH,DIET".dataset2begins with"NAME,STRIDE_LENGTH,STANCE".
Join rows across the two tables by exact NAME match, ignoring any dinosaur that appears in only one table. Among the joined dinosaurs, keep only those whose STANCE in dataset2 equals "bipedal".
For each bipedal dinosaur kept, evaluate its running speed from the exact decimal values of LEG_LENGTH and STRIDE_LENGTH:
speed = ((STRIDE_LENGTH / LEG_LENGTH) - 1) * sqrt(LEG_LENGTH * 9.8)
Return the kept dinosaur NAMEs ordered from highest speed to lowest speed. Treat every numeric string as an exact base-10 real number: if two dinosaurs have the exact same speed mathematically (not merely equal after floating-point rounding), place the lexicographically smaller NAME (by ASCII code order) first.
Examples
Example 1
- Input:
dataset1 = ["NAME,LEG_LENGTH,DIET", "Allosaurus,2.5,carnivore", "Compsognathus,0.4,carnivore", "Iguanodon,2.0,herbivore", "Carnotaurus,3.2,carnivore", "Stegosaurus,1.6,herbivore"], dataset2 = ["NAME,STRIDE_LENGTH,STANCE", "Iguanodon,1.7,bipedal", "Allosaurus,3.7,bipedal", "Stegosaurus,2.4,quadrupedal", "Compsognathus,0.9,bipedal", "Baryonyx,2.8,bipedal", "Carnotaurus,2.4,bipedal"] - Output:
["Compsognathus", "Allosaurus", "Iguanodon", "Carnotaurus"] - Explanation:
"Stegosaurus"is"quadrupedal"and"Baryonyx"is absent fromdataset1, so both are excluded. Among the four matched bipedal species,"Compsognathus"(~2.475) slightly edges out"Allosaurus"(~2.376), while"Iguanodon"(~-0.664) and"Carnotaurus"(~-1.400) have strides shorter than their legs, yielding negative speeds.
Example 2
- Input:
dataset1 = ["NAME,LEG_LENGTH,DIET", "swift_a,4,omnivore", "heavy_b,6,herbivore", "tall_c,16,carnivore"], dataset2 = ["NAME,STRIDE_LENGTH,STANCE", "swift_a,6,bipedal", "heavy_b,12,quadrupedal", "missing_d,50,bipedal", "tall_c,24,bipedal"] - Output:
["tall_c", "swift_a"] - Explanation:
"heavy_b"is quadrupedal and"missing_d"lacks a row indataset1. Both"swift_a"and"tall_c"have a1.5stride-to-leg ratio, so"tall_c"wins due to its largersqrt(LEG_LENGTH * 9.8)factor.
Example 3
- Input:
dataset1 = ["NAME,LEG_LENGTH,DIET", "rex_2,1,carnivore", "dino_1,4,herbivore"], dataset2 = ["NAME,STRIDE_LENGTH,STANCE", "rex_2,3,bipedal", "dino_1,8,bipedal"] - Output:
["dino_1", "rex_2"] - Explanation:
"rex_2"has speed((3 / 1) - 1) * sqrt(9.8) = 2 * sqrt(9.8)and"dino_1"has speed((8 / 4) - 1) * sqrt(4 * 9.8) = 2 * sqrt(9.8). Because their mathematical speeds are identical, lexicographical order places"dino_1"ahead of"rex_2".
Example 4
- Input:
dataset1 = ["NAME,LEG_LENGTH,DIET", "ankylo,1.2,herbivore", "tricera,2.1,herbivore"], dataset2 = ["NAME,STRIDE_LENGTH,STANCE", "ankylo,1.5,quadrupedal", "raptor,3.0,bipedal"] - Output:
[] - Explanation:
"ankylo"is not bipedal and"raptor"has no leg measurement indataset1, leaving zero qualifying dinosaurs.
Constraints
1 <= len(dataset1), len(dataset2) <= 2 * 10^5 + 1(header line included).- Every data line contains three comma-separated fields without leading or trailing spaces, and no field contains a comma.
- Within each dataset,
NAMEstrings are unique, non-empty, and contain only ASCII letters, digits, internal spaces, hyphens (-), or underscores (_). LEG_LENGTHandSTRIDE_LENGTHare positive base-10 decimals at most10^6, written as one or more digits optionally followed by.and1to6digits (numbers below1include a leading0, such as0.4; signs and exponent notation never appear).- Unmatched rows are ignored, and
[]is returned when no matched bipedal dinosaur exists.
Step-by-step walkthrough
Restate the join and filter rules
We receive two lists of CSV lines whose first elements (
index 0) are header rows:dataset1: NAME, LEG_LENGTH, DIET (e.g. "Allosaurus,2.5,carnivore") dataset2: NAME, STRIDE_LENGTH, STANCE (e.g. "Allosaurus,3.7,bipedal")We keep a dinosaur only when: 1. Its
NAMEappears in bothdataset1anddataset2(exact string match), and 2. ItsSTANCEindataset2is"bipedal".Scanning all of
dataset1for every row ofdataset2with nested loops would takeO(N * M)time, which is too slow when both files hold2 * 10^5rows. Instead, we loaddataset1[1:]into a dictionaryleg_by_name(NAME -> LEG_LENGTHstring) in one pass, then scandataset2[1:]once and look up each"bipedal"dinosaur inO(1)average time.Why naive floating-point math breaks the tie-breaking rule
The prompt requires us to treat each decimal string as its exact base-10 value and break ties alphabetically only when two speeds are equal mathematically, not merely after rounding. Standard 64-bit binary floating-point (
float) fails in both directions:- False inequality on equal speeds: Base-10 decimals like
"0.1"and"0.3"are repeating fractions in base 2. In Pythonfloat,0.3 / 0.1evaluates to2.9999999999999996instead of3. As a result,(L = 0.1, S = 0.3)computes a slightly smallerfloatspeed than(L = 0.4, S = 0.8), even though both equal1.4 * sqrt(2)mathematically! - False tie on ultra-close speeds: Numbers near
10^6that differ at the sixth decimal place can round to the exact samefloat, triggering alphabetical tie-breaking when one dinosaur is strictly faster.
We can avoid both bugs completely by rewriting the speed comparison into exact integer arithmetic with zero
floatconversions and zero square roots.- False inequality on equal speeds: Base-10 decimals like
Eliminate the square root with a sign-preserving square
Let
L = LEG_LENGTHandS = STRIDE_LENGTH(both strictly positive). Rewrite the speed formula step by step:speed = ((S / L) - 1) * sqrt(L * 9.8) = ((S / L) - (L / L)) * sqrt(L) * sqrt(9.8) = ((S - L) / L) * sqrt(L) * sqrt(9.8) = ((S - L) / sqrt(L)) * sqrt(9.8) (since sqrt(L) / L = 1 / sqrt(L))First,
sqrt(9.8)is a positive constant shared by every dinosaur, so dividing every speed bysqrt(9.8)never changes which speed is larger or whether two speeds are equal. That leavesu = (S - L) / sqrt(L).Second, we cannot just square
u, because squaring turns-5into+25and makes slow negative speeds look fast! Instead, apply the sign-preserving squarephi(u) = sign(u) * u^2: - Whenu > 0(S > L),phi(u) = +u^2 > 0: larger positive speeds give larger positive numbers. - Whenu == 0(S == L),phi(0) = 0. - Whenu < 0(S < L),phi(u) = -u^2 < 0:-1maps to-1and-2maps to-4, so-1still beats-2.Because
phi(u)is strictly increasing across the entire number line,u1 > u2if and only ifphi(u1) > phi(u2). Applyingphicancelssqrt(L)cleanly:phi((S - L) / sqrt(L)) = sign(S - L) * ((S - L) / sqrt(L))^2 = sign(S - L) * (S - L)^2 / LEvery dinosaur's speed rank is now an exact fraction!
Convert decimal strings to exact integer fractions
To parse a decimal string without
float, split on"."and usescale = 10 ** len(frac_part)so leading zeros after the decimal point stay intact (for example,"0.4"->(4, 10),"1.05"->(105, 100), and"6"->(6, 1)).Given
L = leg_num / leg_scaleandS = stride_num / stride_scale, both scales are powers of10, socommon_scale = max(leg_scale, stride_scale)is a common denominator for both: -L = leg_scaled / common_scale-S = stride_scaled / common_scaleLet
diff = stride_scaled - leg_scaled, soS - L = diff / common_scale. Substituting into(S - L)^2 / Lgives:(S - L)^2 / L = (diff / common_scale)^2 / (leg_scaled / common_scale) = (diff^2 / common_scale^2) * (common_scale / leg_scaled) = diff^2 / (leg_scaled * common_scale)from typing import Tuple def parse_decimal_parts(text: str) -> Tuple[int, int]: """Parse a positive decimal string into (digits_int, power_of_10_scale).""" if "." not in text: return int(text), 1 whole_part, frac_part = text.split(".") scale = 10 ** len(frac_part) numerator = int(whole_part) * scale + int(frac_part) return numerator, scale def signed_squared_speed_fraction(leg_text: str, stride_text: str) -> Tuple[int, int]: """Return exact (num, den) with den > 0 for sign(S - L) * (S - L)^2 / L.""" leg_num, leg_scale = parse_decimal_parts(leg_text) stride_num, stride_scale = parse_decimal_parts(stride_text) common_scale = max(leg_scale, stride_scale) leg_scaled = leg_num * (common_scale // leg_scale) stride_scaled = stride_num * (common_scale // stride_scale) diff = stride_scaled - leg_scaled if diff >= 0: signed_sq_num = diff * diff else: signed_sq_num = -(diff * diff) signed_sq_den = leg_scaled * common_scale return signed_sq_num, signed_sq_denCompare fractions by cross-multiplication and trace Example 1
Because
LEG_LENGTH > 0andcommon_scale >= 1, every denominatorden = leg_scaled * common_scaleis strictly positive. Multiplying an inequality by two positive denominators never flips<or>, so:num_left / den_left > num_right / den_right <==> num_left * den_right > num_right * den_leftPython's
inthas arbitrary precision, sonum_left * den_rightnever overflows. In Python, a two-argument comparatorcompare_records(left, right)returns-1whenleftshould appear beforeright,+1whenleftshould appear afterright, and0when equal;functools.cmp_to_keyadapts it into asort(key=...)key.Let's trace Example 1 with our exact fractions:
Dinosaur L S common_scale diff num / den ------------------------------------------------------------------------ Compsognathus 0.4 0.9 10 +5 +25 / 40 (= +0.625) Allosaurus 2.5 3.7 10 +12 +144 / 250 (= +0.576) Iguanodon 2.0 1.7 10 -3 -9 / 200 (= -0.045) Carnotaurus 3.2 2.4 10 -8 -64 / 320 (= -0.200) Stegosaurus (quadrupedal -> skipped) Baryonyx (absent from dataset1 -> skipped) Cross-check top two: 25 * 250 = 6,250 > 144 * 40 = 5,760 -> Compsognathus wins! Order: ["Compsognathus", "Allosaurus", "Iguanodon", "Carnotaurus"]Complete solution
Putting the hash-map join, bipedal filter, exact fraction builder, and cross-multiplying comparator together gives the complete solution:
from typing import Any, Dict, List, Optional, Set, Tuple import functools def parse_decimal_parts(text: str) -> Tuple[int, int]: """Parse a positive decimal string into (digits_int, power_of_10_scale).""" # Exact base-10 conversion without binary float rounding: # e.g., "0.4" -> (4, 10), "1.05" -> (105, 100), "6" -> (6, 1). if "." not in text: return int(text), 1 whole_part, frac_part = text.split(".") # Use string length `len(frac_part)` so leading zeros after "." (like "1.05") stay intact. scale = 10 ** len(frac_part) numerator = int(whole_part) * scale + int(frac_part) return numerator, scale def signed_squared_speed_fraction(leg_text: str, stride_text: str) -> Tuple[int, int]: """Return exact (num, den) with den > 0 for sign(S - L) * (S - L)^2 / L.""" leg_num, leg_scale = parse_decimal_parts(leg_text) stride_num, stride_scale = parse_decimal_parts(stride_text) # Put L and S over a common power-of-10 denominator: # L = leg_scaled / common_scale and S = stride_scaled / common_scale. common_scale = max(leg_scale, stride_scale) leg_scaled = leg_num * (common_scale // leg_scale) stride_scaled = stride_num * (common_scale // stride_scale) # Algebra: speed = ((S / L) - 1) * sqrt(L * 9.8) = ((S - L) / sqrt(L)) * sqrt(9.8). # Dropping the shared positive factor sqrt(9.8) and applying u -> sign(u) * u^2 # preserves strict <, ==, > order across negative, zero, and positive speeds. diff = stride_scaled - leg_scaled if diff >= 0: signed_sq_num = diff * diff else: signed_sq_num = -(diff * diff) # Denominator is strictly positive because LEG_LENGTH > 0 and common_scale >= 1. signed_sq_den = leg_scaled * common_scale return signed_sq_num, signed_sq_den def compare_records( left: Tuple[int, int, str], right: Tuple[int, int, str] ) -> int: """Comparator: descending exact speed, breaking exact math ties by ascending name.""" # Because both denominators are > 0, num_left / den_left > num_right / den_right # is equivalent to integer cross-multiplication num_left * den_right > num_right * den_left. left_cross = left[0] * right[1] right_cross = right[0] * left[1] if left_cross != right_cross: return -1 if left_cross > right_cross else 1 # Speeds are equal in exact math: lexicographically smaller name comes first. if left[2] < right[2]: return -1 if left[2] > right[2]: return 1 return 0 def rankBipedalDinosaurs(dataset1: List[str], dataset2: List[str]) -> List[str]: # leg_by_name: maps dinosaur NAME -> raw LEG_LENGTH string, e.g. {"Allosaurus": "2.5"}. leg_by_name: Dict[str, str] = {} for row in dataset1[1:]: name, leg_text, _diet = row.split(",") leg_by_name[name] = leg_text # records: list of (signed_sq_num, signed_sq_den, name), e.g. [(25, 40, "Compsognathus")]. records: List[Tuple[int, int, str]] = [] for row in dataset2[1:]: name, stride_text, stance = row.split(",") if stance == "bipedal" and name in leg_by_name: num, den = signed_squared_speed_fraction(leg_by_name[name], stride_text) records.append((num, den, name)) # Phase 3: Sort from fastest to slowest using our exact rational comparator. records.sort(key=functools.cmp_to_key(compare_records)) ranked_names: List[str] = [] for _num, _den, name in records: ranked_names.append(name) return ranked_names✅ Submit now — all tests should pass.
Intuition & how it works
Think of this task as a database hash join (matching rows from two tables by loading one table's keys into a hash map for fast lookup) followed by an exact-fraction sort. First, we index every dinosaur in dataset1 by its NAME so that as we read dataset2, we can immediately skip any dinosaur that is not "bipedal" or has no leg-length entry. Then, instead of calling floating-point math.sqrt, we algebraically rewrite the speed formula so that comparing two speeds becomes comparing two exact integer fractions via cross-multiplication (comparing a / b against c / d with positive denominators by comparing the integer products a * d and c * b).
Why does the obvious approach fall short? Scanning dataset1 linearly for every line of dataset2 takes O(N * M) time (4 * 10^10 checks at 2 * 10^5 rows). Worse, standard binary floating-point (float) cannot represent simple base-10 decimals like 0.1 or 0.3 exactly: 0.3 / 0.1 evaluates to 2.9999999999999996, breaking exact mathematical ties (such as L = 0.1, S = 0.3 versus L = 0.4, S = 0.8, which both equal 1.4 * sqrt(2)). In the opposite direction, two distinct speeds differing past ~16 significant digits round to the same float and wrongly tie-break by name.
By factoring out the shared positive constant sqrt(9.8) and applying the monotonic transformation u -> sign(u) * u^2 (a function that strictly preserves <, ==, and > across negative, zero, and positive values), speed = ((S - L) / sqrt(L)) * sqrt(9.8) becomes sign(S - L) * (S - L)^2 / L. Let's trace Example 2 (swift_a with L=4, S=6, heavy_b quadrupedal, missing_d absent from dataset1, tall_c with L=16, S=24):
1. Index dataset1 (skipping header):
leg_by_name = {"swift_a": "4", "heavy_b": "6", "tall_c": "16"}
2. Filter dataset2 (stance == "bipedal" and name in leg_by_name):
- "swift_a,6,bipedal" -> kept: diff = 6 - 4 = +2 -> +2^2 / 4 = 4 / 4
- "heavy_b,12,quadrupedal" -> skipped (not bipedal)
- "missing_d,50,bipedal" -> skipped (not in leg_by_name)
- "tall_c,24,bipedal" -> kept: diff = 24 - 16 = +8 -> +8^2 / 16 = 64 / 16
3. Cross-multiply to sort descending:
tall_c vs swift_a: 64 * 4 = 256 > 4 * 16 = 64 -> ["tall_c", "swift_a"]
Complexity
Let N be the number of rows in dataset1, M be the number of rows in dataset2, and K (K <= min(N, M)) be the number of matched bipedal dinosaurs.
- Time:
O(N + M + K log K). Buildingleg_by_namescans theNlines ofdataset1once withO(1)average hash-map insertions, scanningdataset2takesO(M)time withO(1)average dictionary lookups and constant-time decimal parsing (at most ~13 characters per number), and sorting theKkept records performsO(K log K)comparisons on bounded integers (numerators up to10^24, denominators up to10^18). - Space:
O(N + K). Theleg_by_namedictionary stores up toNname-to-string entries, and therecordslist holdsKtuples for sorting.
Edge cases
- Header-only inputs (
len(dataset) == 1): Slicingdataset1[1:]anddataset2[1:]produces empty loops and cleanly returns[]. - Negative speeds (
STRIDE_LENGTH < LEG_LENGTH): WhenS < L,(S / L) - 1is negative. Preservingsign(diff)setssigned_sq_num = -(diff * diff), so milder negative speeds (like-0.045for"Iguanodon") rank ahead of deeper negative speeds (like-0.200for"Carnotaurus"). - Zero speeds (
STRIDE_LENGTH == LEG_LENGTH):diff == 0yields0 / den, which ranks strictly below all positive speeds, strictly above all negative speeds, and ties with every other zero-speed dinosaur regardless of leg length. - Leading zeros after the decimal point (
"0.04","1.05"): Using10 ** len(frac_part)rather thanlen(str(int(frac_part)))preserves exact decimal place value. - Exact ties across different measurements: Comparing
(L=1, S=3)(4 / 1) against(L=4, S=8)(16 / 4) gives4 * 4 == 16 * 1, triggering lexicographical order (dictionary order by ASCII character code) so"dino_1"beats"rex_2".
Common mistakes
- Forgetting to skip the header row: Iterating over
dataset1instead ofdataset1[1:]crashes immediately when parsing"LEG_LENGTH"as a number. - Squaring speeds without preserving the sign: Sorting by
(S - L)^2 / Lwithoutsign(S - L)turns speed-5into+25, ranking slow negative-speed dinosaurs ahead of positive-speed ones. - Using
floatandmath.sqrtdirectly: Binary floating-point rounding both breaks exact decimal ties (like0.3 / 0.1) and collapses distinct ultra-close speeds into false ties. - Reversing
namealong withspeed: Sorting(speed, name)withreverse=Trueputs"rex_2"before"dino_1"on equal speeds — the opposite of lexicographical tie-breaking.
Follow-up questions
- How would you join and rank the records if both CSV files were tens of gigabytes on disk and exceeded available RAM? Stream both files onto disk partitioned into
Bbuckets byhash(name) % B— an external hash join (splitting large inputs into matching hash buckets so each bucket pair fits in RAM). Join one bucket pair at a time to emit(num, den, name)records, then sort the output on disk with external merge sort (sorting fixed-RAM runs and merging those sorted files sequentially). - What would you change if dinosaur names could include quoted commas such as "Rex, Jr.",6.5,carnivore? Swap
row.split(",")for Python's standard-librarycsv.reader(dataset), which parses RFC-4180 quoted fields and embedded commas cleanly while iterating line by line. - How can you optimize time and memory if the caller only asks for the top T fastest bipedal dinosaurs (T << K)? Instead of sorting all
Kcandidates inO(K log K)time, keep a min-heap (a binary-tree priority queue that exposes its worst element inO(1)time and updates inO(log T)time) of capacityTwhose root holds the slowest or tie-losing dinosaur among the current topT, reducing the selection step toO(K log T)time andO(T)extra candidate memory.
Follow-up questions
- How would you join and rank the records if both CSV files were tens of gigabytes on disk and exceeded available RAM?
- What would you change if dinosaur names could include quoted commas such as "Rex, Jr.",6.5,carnivore?
- How can you optimize time and memory if the caller only asks for the top T fastest bipedal dinosaurs (T << K)?
Similar questions
- Balanced BST from Ascending Linked Nodes
- Single-Typo Dictionary Word Matching
- Multi-Head Attention Forward Pass in NumPy
- Dot Product of Run-Compressed Vectors
- Mutual-Friend Recommendation
- Single-Transaction Stock Profit
More Meta interview questions
- Balance Parentheses with Fewest Deletions Medium
- Binary Tree Lowest Common Ancestor Medium
- Palindrome Check Under a Deletion Budget Medium Pro
- Moving Averages Over Fixed-Width Subarrays Easy Pro
- Merge Two Sorted Lists of Disjoint Intervals Medium Pro
- Mutual-Friend Recommendation Medium Pro
- Daily Active Ad Revenue by Source Easy Pro
- Subarray Sum Existence with Negatives Medium Pro
- Shortest Maze Path with Keys and Doors Medium Pro
- Multi-Stage Stateful In-Memory Service Simulations Easy Pro