Observer Simulation and Manual Integer Conversion
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Tests event-driven simulation optimization and precise numeric string formatting including signed 32-bit boundary handling.
You must solve two independent problems.
Problem 1: Players on a Track with Observer
A horizontal track has integer positions from 0 to L. The finish line is at position L.
There are N players. Each player i starts at position players[i]. Every player wants to move rightward by one position per second.
An observer stands at position watcherPos and initially looks to the right. At each timestamp in the array turnTimes, the observer reverses their viewing direction. The array turnTimes may be unsorted and may contain duplicate values.
Movement rules for each one-second interval:
During each second from time t to time t+1, a player is blocked (cannot move) if the observer is currently watching that player's position. Otherwise, the player moves one position to the right.
A player at position p is watched if and only if:
- The observer is looking right AND
p >= watcherPos, OR - The observer is looking left AND
p <= watcherPos
Once a player reaches position L or beyond, they are finished and stop moving permanently.
Multiple players can occupy the same position.
Exact event ordering:
For each integer time t from 0 to T-1:
- First, apply all direction reversals scheduled at time
tby processing each occurrence oftinturnTimessequentially (each reversal toggles the direction) - Then, determine which players are currently watched based on the observer's resulting direction
- Finally, move each non-watched, unfinished player one position to the right
Given L, players, watcherPos, turnTimes, and ending time T, return how many players have reached position L by the end of time T.
Problem 2: Convert Integer to Decimal String
Implement a function that converts a 32-bit signed integer to its decimal string representation without using built-in conversion functions.
Write int_to_string(x) where x is in the range [-2147483648, 2147483647].
Requirements:
- Return
"0"whenxis zero - Negative numbers must start with
'-' - Do not use Python's
str(),format(), f-strings,repr(), or similar built-in conversions - Correctly handle
-2147483648(the minimum 32-bit signed integer)
Constraints:
0 <= L <= 10^90 <= len(players) <= 10^50 <= players[i] <= 10^9-10^9 <= watcherPos <= 10^90 <= len(turnTimes) <= 10^50 <= turnTimes[i] <= 10^90 <= T <= 10^9-2^31 <= x <= 2^31 - 1(for problem 2)
Examples
Example 1
Input: count_players_finished(5, [0, 1, 5], 2, [], 5)
Output: 1
Example 2
Input: count_players_finished(5, [0, 3], 2, [0], 5)
Output: 1
Example 3
Input: count_players_finished(5, [0, 3], 2, [3, 1, 1], 5)
Output: 1
Example 4
Input: count_players_finished(10, [2, 4, 8], 5, [1, 4], 6)
Output: 1
Hints
Hint 1
For the track problem: players on different sides of the observer are blocked during different time periods. Can you count these periods instead of simulating each second?
Hint 2
A player at exactly watcherPos is always watched no matter which direction the observer faces.
Hint 3
For integer conversion: extract digits from right to left using modulo and division, then reverse. In languages with fixed-width integers, negating -2147483648 would overflow.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Problem 1: Players on a Track with Observer
A naive second-by-second simulation has time complexity O(T × N), which becomes impractical when T reaches 10^9. The optimization relies on categorizing players by their position relative to the observer.
Three player categories:
- Left of observer (
p < watcherPos): blocked when observer looks left, free when looking right - Right of observer (
p > watcherPos): blocked when observer looks right, free when looking left - At observer position (
p == watcherPos): always blocked regardless of direction
Since a player who reaches the observer's position becomes permanently stuck there (unless it equals or exceeds L), each player remains in their initial category throughout the simulation. This means a player's advancement depends solely on counting how many seconds they are free to move.
Algorithm steps:
- Filter
turnTimesto include only events in[0, T) - Use Counter to handle duplicate timestamps (even duplicates cancel each other)
- Sort the filtered event times
- Process intervals between consecutive events, advancing players according to the current observer direction
- Left-side players advance toward
min(watcherPos, L), right-side players advance towardL
By processing intervals instead of individual seconds, we reduce complexity dramatically.
Correctness: Each player's final position equals their starting position plus the total number of seconds they were free to move, bounded by either the observer position (if trapped) or the finish line. The sequence of free seconds is irrelevant—only the cumulative count matters.
Time complexity: O(K log K + N × K) where K is the number of unique turn timestamps. Sorting takes K log K, and we advance positions K+1 times.
Space complexity: O(K + N) for event storage and position tracking.
Problem 2: Convert Integer to Decimal String
Build the decimal representation by repeatedly extracting the rightmost digit using modulo 10, then perform integer division by 10. Collect digits in reverse order, then reverse the entire result.
The edge case -2147483648 requires attention: in fixed-width languages like C++ or Java, negating this value overflows because 2147483648 exceeds the maximum positive 32-bit value. Python's arbitrary-precision integers handle this automatically, but production code in other languages would need to either maintain negative values throughout or widen to 64-bit before negation.
Time complexity: O(d) where d ≤ 10 is the digit count
Space complexity: O(d) for the digit array
Complete Solution
from typing import List
from collections import Counter
def count_players_finished(L: int, players: List[int], watcherPos: int, turnTimes: List[int], T: int) -> int:
if T <= 0:
return sum(position >= L for position in players)
events = Counter(t for t in turnTimes if 0 <= t < T)
event_times = sorted(events)
positions = list(players)
direction_right = True
current_time = 0
def advance(duration):
if duration <= 0:
return
for i, position in enumerate(positions):
if position >= L:
continue
if direction_right:
if position < watcherPos:
positions[i] = min(position + duration, watcherPos, L)
else:
if position > watcherPos:
positions[i] = min(position + duration, L)
for event_time in event_times:
advance(event_time - current_time)
if events[event_time] % 2:
direction_right = not direction_right
current_time = event_time
advance(T - current_time)
return sum(position >= L for position in positions)
def int_to_string(x: int) -> str:
if x == 0:
return "0"
is_negative = x < 0
n = abs(x)
digits = []
while n > 0:
digits.append(chr(ord('0') + n % 10))
n //= 10
if is_negative:
digits.append('-')
return ''.join(reversed(digits))