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:

  • dataset1 begins with "NAME,LEG_LENGTH,DIET".
  • dataset2 begins 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 from dataset1, 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 in dataset1. Both "swift_a" and "tall_c" have a 1.5 stride-to-leg ratio, so "tall_c" wins due to its larger sqrt(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 in dataset1, 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, NAME strings are unique, non-empty, and contain only ASCII letters, digits, internal spaces, hyphens (-), or underscores (_).
  • LEG_LENGTH and STRIDE_LENGTH are positive base-10 decimals at most 10^6, written as one or more digits optionally followed by . and 1 to 6 digits (numbers below 1 include a leading 0, such as 0.4; signs and exponent notation never appear).
  • Unmatched rows are ignored, and [] is returned when no matched bipedal dinosaur exists.

Step-by-step walkthrough

  1. 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 NAME appears in both dataset1 and dataset2 (exact string match), and 2. Its STANCE in dataset2 is "bipedal".

    Scanning all of dataset1 for every row of dataset2 with nested loops would take O(N * M) time, which is too slow when both files hold 2 * 10^5 rows. Instead, we load dataset1[1:] into a dictionary leg_by_name (NAME -> LEG_LENGTH string) in one pass, then scan dataset2[1:] once and look up each "bipedal" dinosaur in O(1) average time.

  2. 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 Python float, 0.3 / 0.1 evaluates to 2.9999999999999996 instead of 3. As a result, (L = 0.1, S = 0.3) computes a slightly smaller float speed than (L = 0.4, S = 0.8), even though both equal 1.4 * sqrt(2) mathematically!
    • False tie on ultra-close speeds: Numbers near 10^6 that differ at the sixth decimal place can round to the exact same float, 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 float conversions and zero square roots.

  3. Eliminate the square root with a sign-preserving square

    Let L = LEG_LENGTH and S = 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 by sqrt(9.8) never changes which speed is larger or whether two speeds are equal. That leaves u = (S - L) / sqrt(L).

    Second, we cannot just square u, because squaring turns -5 into +25 and makes slow negative speeds look fast! Instead, apply the sign-preserving square phi(u) = sign(u) * u^2: - When u > 0 (S > L), phi(u) = +u^2 > 0: larger positive speeds give larger positive numbers. - When u == 0 (S == L), phi(0) = 0. - When u < 0 (S < L), phi(u) = -u^2 < 0: -1 maps to -1 and -2 maps to -4, so -1 still beats -2.

    Because phi(u) is strictly increasing across the entire number line, u1 > u2 if and only if phi(u1) > phi(u2). Applying phi cancels sqrt(L) cleanly:

    phi((S - L) / sqrt(L))  =  sign(S - L) * ((S - L) / sqrt(L))^2
                            =  sign(S - L) * (S - L)^2 / L
    

    Every dinosaur's speed rank is now an exact fraction!

  4. Convert decimal strings to exact integer fractions

    To parse a decimal string without float, split on "." and use scale = 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_scale and S = stride_num / stride_scale, both scales are powers of 10, so common_scale = max(leg_scale, stride_scale) is a common denominator for both: - L = leg_scaled / common_scale - S = stride_scaled / common_scale

    Let diff = stride_scaled - leg_scaled, so S - L = diff / common_scale. Substituting into (S - L)^2 / L gives:

    (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_den
    
  5. Compare fractions by cross-multiplication and trace Example 1

    Because LEG_LENGTH > 0 and common_scale >= 1, every denominator den = leg_scaled * common_scale is 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_left
    

    Python's int has arbitrary precision, so num_left * den_right never overflows. In Python, a two-argument comparator compare_records(left, right) returns -1 when left should appear before right, +1 when left should appear after right, and 0 when equal; functools.cmp_to_key adapts it into a sort(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"]
    
  6. 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). Building leg_by_name scans the N lines of dataset1 once with O(1) average hash-map insertions, scanning dataset2 takes O(M) time with O(1) average dictionary lookups and constant-time decimal parsing (at most ~13 characters per number), and sorting the K kept records performs O(K log K) comparisons on bounded integers (numerators up to 10^24, denominators up to 10^18).
  • Space: O(N + K). The leg_by_name dictionary stores up to N name-to-string entries, and the records list holds K tuples for sorting.

Edge cases

  • Header-only inputs (len(dataset) == 1): Slicing dataset1[1:] and dataset2[1:] produces empty loops and cleanly returns [].
  • Negative speeds (STRIDE_LENGTH < LEG_LENGTH): When S < L, (S / L) - 1 is negative. Preserving sign(diff) sets signed_sq_num = -(diff * diff), so milder negative speeds (like -0.045 for "Iguanodon") rank ahead of deeper negative speeds (like -0.200 for "Carnotaurus").
  • Zero speeds (STRIDE_LENGTH == LEG_LENGTH): diff == 0 yields 0 / 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"): Using 10 ** len(frac_part) rather than len(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) gives 4 * 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 dataset1 instead of dataset1[1:] crashes immediately when parsing "LEG_LENGTH" as a number.
  • Squaring speeds without preserving the sign: Sorting by (S - L)^2 / L without sign(S - L) turns speed -5 into +25, ranking slow negative-speed dinosaurs ahead of positive-speed ones.
  • Using float and math.sqrt directly: Binary floating-point rounding both breaks exact decimal ties (like 0.3 / 0.1) and collapses distinct ultra-close speeds into false ties.
  • Reversing name along with speed: Sorting (speed, name) with reverse=True puts "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 B buckets by hash(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-library csv.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 K candidates in O(K log K) time, keep a min-heap (a binary-tree priority queue that exposes its worst element in O(1) time and updates in O(log T) time) of capacity T whose root holds the slowest or tie-losing dinosaur among the current top T, reducing the selection step to O(K log T) time and O(T) extra candidate memory.

Follow-up questions

Similar questions

More Meta interview questions

All 787 Meta questions →