Track Sentry Simulation and Manual Integer Formatting

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Solve the two standalone programming tasks described below.

Part 1 — Counting Runners Past the Sentry

def count_players_finished(L: int, players: List[int], watcherPos: int, turnTimes: List[int], T: int) -> int:

A straight one-dimensional course spans integer coordinates with its goal line at L:

  • players[i] gives the starting integer coordinate of runner i. Any number of runners may stand on the same coordinate simultaneously without obstructing one another.
  • Once a runner is at coordinate >= L, that runner has finished and stays finished permanently.
  • A stationary sentry stands at integer coordinate watcherPos, initially facing right at timestamp 0.
  • turnTimes contains integer timestamps at which the sentry flips facing direction (right <-> left). turnTimes is not guaranteed to be sorted and may contain duplicate timestamps or timestamps outside [0, T).
  • For each integer second t = 0, 1, ..., T - 1 (representing the interval [t, t + 1)), resolve events in this strict sequence:
    1. Process every entry in turnTimes equal to t, toggling the sentry's facing direction once per occurrence.
    2. Determine visibility for [t, t + 1): when facing right, every coordinate p >= watcherPos is observed; when facing left, every coordinate p <= watcherPos is observed.
    3. Every unfinished runner (p < L) whose current coordinate is not observed steps +1 unit right (p -> p + 1); observed runners remain where they are.

Return how many runners are at coordinate >= L at timestamp T.

Part 2 — Manual Signed 32-Bit Integer Formatting

Also implement a standalone helper int_to_decimal_string(x: int) -> str (analogous to itoa) that converts a 32-bit signed integer x into its base-10 decimal string without calling built-in number-to-string utilities (str, format, repr, %-formatting, or f-strings):

  • Return "0" when x == 0.
  • Prefix negative values with '-' (for example, -4096 -> "-4096").
  • Handle every 32-bit signed integer from -2147483648 through 2147483647 accurately.

Examples

Example 1

Input: L = 6, players = [1, 3, 6, 6], watcherPos = 3, turnTimes = [], T = 4
Output: 2

Walk-through: With no direction flips, the sentry faces right for all 4 seconds and observes p >= 3. Both runners starting at 6 are already on the goal line (2 finishers). The runner at 3 is observed immediately, and the runner at 1 advances to 3 after two seconds and freezes there.

Example 2

Input: L = 7, players = [1, 4, 5], watcherPos = 3, turnTimes = [0], T = 3
Output: 2

Walk-through: At t = 0, the sentry flips left before movement begins and faces left across [0, 3), observing p <= 3. The runner at 1 cannot move, while the runners at 4 and 5 advance right every second (4 -> 7 in 3 seconds and 5 -> 7 in 2 seconds), so 2 runners finish.

Example 3

Input: L = 8, players = [2, 5, 6, 7], watcherPos = 4, turnTimes = [4, 2, 2, 1], T = 6
Output: 3

Walk-through: Sorting the reversals inside [0, 6) gives [1, 2, 2, 4]. The sentry faces right on [0, 1) (1s), flips left at t = 1 for [1, 2) (1s), flips twice at t = 2 so it continues facing left across [2, 4) (2s), and flips right at t = 4 for [4, 6) (2s)—giving 3 left-facing seconds in total. The runner at 2 becomes stuck on watcherPos = 4, whereas the runners at 5, 6, and 7 need 3, 2, and 1 left-facing seconds respectively and all 3 reach 8.

Example 4

Input: L = 12, players = [3, 8, 10], watcherPos = 6, turnTimes = [2, 5], T = 7
Output: 1

Walk-through: The sentry faces right on [0, 2), left on [2, 5) (3 left-facing seconds), and right on [5, 7). The runner at 3 reaches 6 and freezes; the runner at 8 reaches 11 (1 short of 12); the runner at 10 reaches 12, giving 1 finisher.

Constraints

  • 0 <= L <= 10^9
  • 0 <= len(players) <= 10^5 and 0 <= players[i] <= 10^9
  • -10^9 <= watcherPos <= 10^9
  • 0 <= len(turnTimes) <= 10^5; entries may be unsorted, duplicated, negative, or >= T
  • 0 <= T <= 10^9
  • Part 2 input range: -2147483648 <= x <= 2147483647

Step-by-step walkthrough

  1. Understand both tasks and the exact timing rules

    This problem asks for two self-contained implementations:

    1. Part 1 (count_players_finished, tested by the automated judge): Runners start at integer coordinates along a course with goal line L and try to advance +1 unit right per second. A sentry stands at watcherPos, initially facing right, and flips direction at every timestamp in turnTimes (which may be unsorted and may contain duplicates).
    2. Part 2 (int_to_decimal_string, built in its own step below): Format a 32-bit signed integer x as a base-10 string without str(), format(), or string formatting operators, handling 0 and -2147483648 cleanly.

    Let's pin down Part 1's exact event sequence during each integer second t = 0, 1, ..., T - 1:

    1. Apply all sentry reversals scheduled at timestamp t (so two entries equal to t flip the sentry twice and cancel out, while any entry < 0 or >= T never fires).
    2. Check visibility: facing right observes pos >= watcherPos; facing left observes pos <= watcherPos.
    3. Every unfinished runner (pos < L) who is not observed steps pos += 1. Once a runner reaches L, they stay finished forever.
  2. Why second-by-second simulation is too slow

    Ticking through each second t from 0 to T - 1 and updating every runner takes O(T * N) time. That works on tiny test cases (and serves as our brute-force reference in tests), but when T = 5 * 10^8 and N = 10^5, 5 * 10^13 operations will time out.

    We need a way to determine whether each runner reaches L without stepping through T seconds one at a time.

  3. Key insight: the sentry's coordinate is an impassable barrier

    Compare a runner's current coordinate pos against watcherPos under both facing directions:

    Course:  0 -------- pos < watcherPos -------- watcherPos -------- pos > watcherPos -------- L
    
    Position vs. watcherPos  | Sentry faces RIGHT      | Sentry faces LEFT
    -------------------------+-------------------------+------------------------
    pos < watcherPos         | UNOBSERVED (moves +1)   | observed   (stays put)
    pos == watcherPos        | observed   (pos >= w)   | observed   (pos <= w)  <-- FROZEN FOREVER!
    pos > watcherPos         | observed   (stays put)  | UNOBSERVED (moves +1)
    

    Look closely at the middle row (pos == watcherPos):

    1. Standing on the sentry (pos == watcherPos): Because visibility uses inclusive inequalities (>= when facing right and <= when facing left), watcherPos is observed in both directions! An unfinished runner on watcherPos can never move again.
    2. Starting left of the sentry (start_pos < watcherPos): Because runners advance +1 integer unit per step, they cannot jump over watcherPos without landing directly on watcherPos.
      • If watcherPos < L, the sentry stands strictly before the goal line: even with unlimited right-facing seconds, the runner walks onto watcherPos and freezes forever before reaching L.
      • If watcherPos >= L, the goal line L comes at or before watcherPos! Every step before L satisfies pos < L <= watcherPos, so the runner steps +1 on every right-facing second and finishes once they receive L - start_pos right-facing seconds.
    3. Starting right of the sentry (start_pos > watcherPos): Because runners only step right, their coordinate stays strictly greater than watcherPos forever. They step +1 on every left-facing second and finish once they receive L - start_pos left-facing seconds.

    Notice what just vanished: the chronological order of left and right seconds does not matter at all! Every runner's outcome depends solely on the total count of right_seconds and left_seconds across [0, T).

  4. Count right-facing and left-facing seconds by sweeping intervals

    To count how many seconds in [0, T) have the sentry facing right, copy only timestamps satisfying 0 <= t < T into valid_turns (leaving the caller's list untouched) and sort it. Between segment_start and the next turn_time, the sentry's direction stays constant:

    Example 3: turnTimes = [4, 2, 2, 1], T = 6  -->  valid_turns = [1, 2, 2, 4]
    
      t = 0        t = 1      t = 2    t = 2        t = 4            T = 6
      |--- right ---|-- left --| (flip) |--- left ---|---- right -----|
         +1 sec       (0 right)  +0 sec    (0 right)      +2 sec
                                (2nd flip!)
    
      Total right_seconds = 1 + 2 = 3,  left_seconds = 6 - 3 = 3
    

    Duplicate timestamps like [2, 2] cancel out naturally: the stretch from 2 to 2 has duration 2 - 2 = 0, and toggling looking_right twice restores the prior direction without any special-case logic.

    def count_right_seconds(turnTimes: List[int], T: int) -> int:
        """Return how many integer seconds t in [0, T) have the watcher looking right."""
        valid_turns: List[int] = []
        for t in turnTimes:
            if 0 <= t < T:
                valid_turns.append(t)
        valid_turns.sort()
    
        right_seconds = 0
        looking_right = True
        segment_start = 0
    
        for turn_time in valid_turns:
            if looking_right:
                right_seconds += turn_time - segment_start
            looking_right = not looking_right
            segment_start = turn_time
    
        if looking_right:
            right_seconds += T - segment_start
        return right_seconds
    
  5. Classify each runner in O(1) time

    Given right_seconds and left_seconds = total_seconds - right_seconds, classifying each runner takes one if / elif chain matching our barrier cases:

    • start_pos >= L: already finished at timestamp 0 (counts even when T == 0).
    • start_pos > watcherPos: requires L - start_pos left-facing seconds (left_seconds >= L - start_pos).
    • start_pos < watcherPos and watcherPos >= L: reaches L before hitting watcherPos if right_seconds >= L - start_pos.
    • Everything else (start_pos == watcherPos < L or start_pos < watcherPos < L): trapped at watcherPos, never finishes.
    def count_players_finished(L: int, players: List[int], watcherPos: int, turnTimes: List[int], T: int) -> int:
        total_seconds = max(T, 0)
        right_seconds = count_right_seconds(turnTimes, total_seconds)
        left_seconds = total_seconds - right_seconds
    
        finished_count = 0
        for start_pos in players:
            if start_pos >= L:
                finished_count += 1
            elif start_pos > watcherPos:
                if left_seconds >= L - start_pos:
                    finished_count += 1
            elif start_pos < watcherPos and watcherPos >= L:
                if right_seconds >= L - start_pos:
                    finished_count += 1
        return finished_count
    
  6. Trace Example 3 and Example 4 step by step

    Let's verify both examples by hand:

    Example 4: L = 12, players = [3, 8, 10], watcherPos = 6, turnTimes = [2, 5], T = 7
      valid_turns = [2, 5]
      Intervals:
        [0, 2) -> right (+2)
        [2, 5) -> left  (+0 right)
        [5, 7) -> right (+2)
      Totals: right_seconds = 4, left_seconds = 7 - 4 = 3
    
      - start_pos = 3:  3 < watcherPos (6) < L (12) -> freezes at 6, does not finish
      - start_pos = 8:  8 > watcherPos (6), needs 12 - 8 = 4 > left_seconds (3) -> reaches 11 (short)
      - start_pos = 10: 10 > watcherPos (6), needs 12 - 10 = 2 <= left_seconds (3) -> FINISHES!
      Result: 1
    
    Example 3: L = 8, players = [2, 5, 6, 7], watcherPos = 4, turnTimes = [4, 2, 2, 1], T = 6
      valid_turns = [1, 2, 2, 4] -> right_seconds = 3, left_seconds = 3
      - start_pos = 2: 2 < watcherPos (4) < L (8) -> trapped at 4
      - start_pos = 5: needs 8 - 5 = 3 <= 3 -> FINISHES!
      - start_pos = 6: needs 8 - 6 = 2 <= 3 -> FINISHES!
      - start_pos = 7: needs 8 - 7 = 1 <= 3 -> FINISHES!
      Result: 3
    
  7. Part 2: format a 32-bit signed integer without built-ins

    Although the automated judge only calls count_players_finished, Part 2 asks for int_to_decimal_string, so let's implement it cleanly and address all three classic pitfalls:

    1. Zero (x == 0): A while magnitude > 0 digit-extraction loop executes zero iterations on 0 and would return "", so check if x == 0: return "0" first.
    2. Digits extract least-significant-first: Taking magnitude % 10 peels off the ones digit first, then magnitude //= 10 shifts right. Convert each 0..9 digit d into its ASCII character via chr(ord("0") + d), append "-" afterward when x < 0, and reverse the character list once before joining:
    Tracing x = -4096:
      is_negative = True, magnitude = 4096
      4096 % 10 = 6 -> append '6', magnitude = 409
       409 % 10 = 9 -> append '9', magnitude = 40
        40 % 10 = 0 -> append '0', magnitude = 4
         4 % 10 = 4 -> append '4', magnitude = 0 (stop)
      append '-'    -> reversed_chars = ['6', '9', '0', '4', '-']
      reverse+join  -> "-4096"
    
    1. Minimum 32-bit signed integer (-2147483648): Signed 32-bit integers span -2147483648 to +2147483647. In C, C++, or Java, negating -2147483648 inside a 32-bit int overflows because +2147483648 exceeds INT32_MAX by 1! Python integers have arbitrary precision so -x never overflows here; in fixed-width languages, widen to a 64-bit integer (or negate in unsigned 32-bit arithmetic) before negating.
    def int_to_decimal_string(x: int) -> str:
        """Task 2: convert a 32-bit signed int `x` to base-10 text without built-in formatters."""
        if x == 0:
            return "0"
    
        is_negative = x < 0
        magnitude = -x if is_negative else x
    
        reversed_chars: List[str] = []
        while magnitude > 0:
            digit = magnitude % 10
            reversed_chars.append(chr(ord("0") + digit))
            magnitude //= 10
    
        if is_negative:
            reversed_chars.append("-")
    
        reversed_chars.reverse()
        return "".join(reversed_chars)
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_right_seconds(turnTimes: List[int], T: int) -> int:
        """Return how many integer seconds t in [0, T) have the watcher looking right."""
        # valid_turns: sorted copy of reversal timestamps inside [0, T), e.g. [1, 2, 2, 4].
        # Keeping duplicates matters because two flips at the same second cancel out.
        valid_turns: List[int] = []
        for t in turnTimes:
            if 0 <= t < T:
                valid_turns.append(t)
        valid_turns.sort()
    
        right_seconds = 0
        looking_right = True
        segment_start = 0
    
        for turn_time in valid_turns:
            # During [segment_start, turn_time), the watcher's direction stayed constant.
            if looking_right:
                right_seconds += turn_time - segment_start
            looking_right = not looking_right
            segment_start = turn_time
    
        # Account for the final stretch [segment_start, T) after the last reversal.
        if looking_right:
            right_seconds += T - segment_start
        return right_seconds
    
    
    def count_players_finished(L: int, players: List[int], watcherPos: int, turnTimes: List[int], T: int) -> int:
        # Phase 1: split [0, T) into total right-looking seconds and total left-looking seconds.
        total_seconds = max(T, 0)
        right_seconds = count_right_seconds(turnTimes, total_seconds)
        left_seconds = total_seconds - right_seconds
    
        # Phase 2: classify each player in O(1) using their start position vs. watcherPos and L.
        finished_count = 0
        for start_pos in players:
            if start_pos >= L:
                # Already at or past the finish line at time 0 (counts even if T == 0).
                finished_count += 1
            elif start_pos > watcherPos:
                # Strictly right of the watcher: position stays > watcherPos forever, so the
                # player steps +1 on every left-looking second without ever hitting the watcher.
                if left_seconds >= L - start_pos:
                    finished_count += 1
            elif start_pos < watcherPos and watcherPos >= L:
                # Strictly left of the watcher, and the finish line L comes at or before the
                # watcher: the player steps +1 on every right-looking second and reaches L first.
                if right_seconds >= L - start_pos:
                    finished_count += 1
            # Otherwise (start_pos == watcherPos, or start_pos < watcherPos < L):
            # watcherPos is watched in BOTH directions (>= when looking right, <= when looking left),
            # so anyone on watcherPos or forced to pass through it before L freezes forever.
    
        return finished_count
    
    
    def int_to_decimal_string(x: int) -> str:
        """Task 2: convert a 32-bit signed int `x` to base-10 text without built-in formatters."""
        if x == 0:
            return "0"
    
        is_negative = x < 0
        # Python ints have arbitrary precision, so -(-2147483648) cannot overflow here.
        # In C/C++/Java, widen to 64-bit before negating because +2147483648 overflows int32.
        magnitude = -x if is_negative else x
    
        # reversed_chars: collects digits least-significant-first, e.g. -120 -> ['0', '2', '1', '-']
        reversed_chars: List[str] = []
        while magnitude > 0:
            digit = magnitude % 10
            reversed_chars.append(chr(ord("0") + digit))
            magnitude //= 10
    
        if is_negative:
            reversed_chars.append("-")
    
        reversed_chars.reverse()
        return "".join(reversed_chars)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of Part 1 as a game of "Red Light, Green Light" where the sentry stands at watcherPos, swivels between facing right and facing left, and observes watcherPos itself in both directions (>= watcherPos when facing right, <= watcherPos when facing left). Because runners only step 1 integer unit at a time, watcherPos acts like flypaper: anyone standing on watcherPos (before the goal line L) is observed whichever way the sentry faces, so no runner starting behind the sentry can ever cross past watcherPos! Consequently, the order of the sentry's flips does not matter at all—only the total number of right-facing seconds and left-facing seconds across [0, T).

A naive simulation loops over t = 0, 1, ..., T - 1 and updates all N runners each second, costing O(T * N) time and timing out whenever T reaches hundreds of millions of seconds. Instead, we sort the reversal timestamps inside [0, T), sum the right-facing intervals to obtain right_seconds (and left_seconds = T - right_seconds), and classify each runner in O(1): runners starting at >= L finish immediately; runners starting right of watcherPos never encounter the sentry and finish when left_seconds >= L - start_pos; runners starting left of watcherPos finish only when watcherPos >= L (the goal line comes at or before the sentry) and right_seconds >= L - start_pos. For Part 2, we extract base-10 digits right to left via % 10 and // 10, map each digit d to chr(ord("0") + d), and reverse once while guarding 0 and -2147483648.

Walk through Example 4 (L = 12, players = [3, 8, 10], watcherPos = 6, turnTimes = [2, 5], T = 7):

  1. Sorted turns [2, 5] partition [0, 7) into [0, 2) facing right (2s), [2, 5) facing left (3s), and [5, 7) facing right (2s), yielding right_seconds = 4 and left_seconds = 3.
  2. Runner at 3 starts left of watcherPos = 6 < 12: after 3 right-facing steps they land on 6 == watcherPos and freeze permanently.
  3. Runner at 8 needs 12 - 8 = 4 left-facing seconds (> 3, reaches 11), while runner at 10 needs 12 - 10 = 2 <= 3 left-facing seconds and crosses 12 (1 finisher).

Complexity

Let N be len(players) and K be len(turnTimes).

  • Part 1 time — O(N + K log K): Filtering turnTimes into [0, T) scans K entries once, sorting valid_turns takes O(K log K) comparisons, sweeping the intervals takes O(K) steps, and classifying all N runners performs one O(1) check per runner—completely independent of T.
  • Part 1 space — O(K): valid_turns stores at most K integers so the caller's turnTimes list is never mutated, while runner classification uses O(1) extra space.
  • Part 2 time and space — O(d) (O(1) for 32-bit integers): A 32-bit signed integer has at most d = 10 decimal digits plus an optional '-' sign (11 characters max), so digit extraction, reversal, and "".join(...) finish in at most 11 constant-time steps.

Edge cases

  • Runner starting directly on watcherPos (start_pos == watcherPos < L): Observed when facing right (>=) and observed when facing left (<=), so they never advance a single unit.
  • Multiple reversals at the exact same second: Preserving duplicate timestamps in valid_turns toggles looking_right once per occurrence, so pairs of equal timestamps cancel out ([2, 2] in Example 3 leaves direction unchanged).
  • Reversals outside [0, T): Negative timestamps and timestamps >= T fall outside simulated seconds 0 .. T - 1 and are filtered out by 0 <= t < T.
  • Sentry positioned at or beyond the goal (watcherPos >= L): Runners starting at start_pos < L <= watcherPos reach L during right-facing seconds before (or right as) they touch watcherPos, counting as finished.
  • Runners starting at L or T == 0: Checking start_pos >= L first ensures runners already on the goal line count even when T == 0.
  • Part 2 boundary values: x = 0 returns "0" immediately; x = 2147483647 (2^31 - 1) and x = -2147483648 (-2^31) both convert cleanly without built-in formatters.

Common mistakes

  • Treating watcherPos as unobserved in one direction: Using > instead of >= (or < instead of <=) lets runners walk across watcherPos, violating the inclusive visibility rules.
  • Deduplicating turnTimes with set(...): Collapsing [4, 2, 2, 1] into {1, 2, 4} turns two cancelling flips at t = 2 into a single flip.
  • Assuming runners left of watcherPos finish given enough right_seconds: Whenever watcherPos < L, any runner starting below watcherPos halts permanently upon stepping onto watcherPos.
  • Sorting turnTimes in place: Calling turnTimes.sort() mutates the caller's input list when turnTimes was passed unsorted.
  • Part 2 — negating -2147483648 in a fixed 32-bit signed integer: Signed integers use two's complement (a binary encoding where 32-bit signed values span -2^31 to 2^31 - 1, leaving one extra negative number), so computing -(-2147483648) triggers integer overflow (wrapping past the maximum 32-bit value 2147483647) in C, C++, or Java unless promoted to 64-bit or unsigned first.
  • Part 2 — forgetting x == 0 or language-specific % on negatives: Omitting the x == 0 check returns "", and taking % 10 directly on negative x differs across languages (-7 % 10 is 3 in Python, whereas -7 % 10 is -7 in C/C++/Java).

Alternative approaches

  • Interval-by-interval runner simulation (O(K log K + K * N)): Sort the reversal timestamps into constant-direction stretches of length d, and on each stretch advance every unfinished runner by min(d, max_steps_before_blocked) (where max_steps_before_blocked is min(watcherPos, L) - pos when pos < watcherPos and facing right, L - pos when pos > watcherPos and facing left, and 0 otherwise). This avoids per-second loops without needing global order-independence, though O(K * N) is still too slow when both K and N reach 10^5.

Follow-up questions

  • How would you compute the exact timestamp at which each runner crosses L (or -1 if they never arrive)? Once we care when a runner finishes rather than just whether they finish, interval order matters again. Build prefix sums (running totals up to each interval boundary) of right_seconds and left_seconds across the sorted intervals in O(K log K) time; then for a runner right of watcherPos needing need = L - start_pos left-facing seconds, use binary search (repeatedly halving the sorted prefix-sum array in O(log K) steps) to locate the exact left-facing interval where the cumulative left total reaches need, and add the remaining offset within that interval.
  • How can you preprocess the inputs to answer Q queries with varying cutoff times T in logarithmic time per query? Pre-sort the non-negative turnTimes and store prefix sums of right_seconds at each reversal so any query T computes (right_seconds(T), left_seconds(T)) via binary search in O(log K) time. Also pre-sort the required distances L - start_pos for runners with start_pos > watcherPos (and separately for start_pos < watcherPos when watcherPos >= L), so counting how many runners satisfy need <= available_seconds takes one more binary search in O(log N)—answering each query in O(log K + log N) time.
  • What changes if runner i advances k_i >= 1 units per unobserved second rather than always 1 unit? When k_i > 1, a runner starting left of watcherPos (say at watcherPos - 1 with k_i = 3) can leap over watcherPos to watcherPos + 2 without landing on watcherPos! Even so, each runner crosses watcherPos at most once: compute m = ceil((watcherPos - start_pos) / k_i) right-facing seconds needed to reach or pass watcherPos (checking whether start_pos + m * k_i >= L finishes immediately or == watcherPos freezes forever), binary-search prefix sums for the timestamp t_cross of the m-th right-facing second, and check whether at least ceil((L - landing_pos) / k_i) left-facing seconds occur strictly after t_cross.
  • In Part 2, how would you format -2147483648 in C without using 64-bit integer types? Instead of negating x into a signed int32_t (which overflows), either compute the magnitude in an unsigned 32-bit integer (uint32_t mag = x < 0 ? 0u - (uint32_t)x : (uint32_t)x;, which represents 2147483648u cleanly in unsigned two's complement arithmetic), or fold positive numbers into the negative range (if (x > 0) x = -x;) so every 32-bit value including -2147483648 fits in int32_t and extract each digit via -(x % 10) and x /= 10.

Follow-up questions

Similar questions

More Hudson River Trading interview questions

All 55 Hudson River Trading questions →