Efficient Large File Tailer and Sensor Heartbeat Monitor
Data Structure DesignModel answerLast updated
Read the last N lines of a huge file using reverse chunk seeking, and track active devices using an OrderedDict for fast sliding window health queries.
This task consists of two sub-problems focusing on system utility and state management:
Task 1: Backward File Reader (tail_file)
Write a function tail_file(filepath: str, n: int) -> list[str] that returns the final n lines of a file.
- The target file can be extremely large (far exceeding available RAM), so reading the full contents into memory is forbidden.
- The file is plain ASCII text.
- Minimize file read operations and avoid reading lines sequentially from the beginning.
Task 2: Health Monitoring System (SensorMonitor)
Design a monitoring class to track continuous health heartbeats from remote hardware units. Each record consists of (sensor_id: str, timestamp: int).
Implement the class with the following API:
record_heartbeat(sensor_id: str, timestamp: int) -> None: Registers a ping from a sensor.get_unhealthy_sensors(current_time: int, threshold: int) -> list[str]: Identifies all sensors whose latest reported timestamp is older thancurrent_time - threshold(i.e.,current_time - last_seen > threshold).
Assume incoming heartbeats arrive sequentially (non-decreasing timestamps over time).
Requirements & Constraints
- For Task 1: Handle edge cases like empty files, missing trailing newlines, and request counts exceeding total file lines.
- For Task 2:
record_heartbeatshould run in $O(1)$ time.get_unhealthy_sensorsshould be output-sensitive (i.e., bounded by the number of silent sensors, rather than scanning all registered sensors).
Hints
Hint 1
For Task 1: Open the file in binary mode ('rb') and move the read pointer backwards from the end using seek() in fixed-size byte blocks.
Hint 2
For Task 1: Check if the file ends with a newline byte. If it does, you will encounter one extra newline when reading backwards.
Hint 3
For Task 2: Since heartbeats are mostly chronological, maintaining insertion/update order via an OrderedDict allows you to iterate from the oldest active sensor and break early once you reach a healthy one.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
Task 1: Backward File Reader (tail_file)
Loading an entire file into memory using methods like readlines() will cause an Out-Of-Memory (OOM) error for multi-gigabyte or terabyte files.
To fetch only the end of the file efficiently:
- Open the file in binary mode (
"rb"). Text mode does not guarantee precise byte-offset seeking across platforms. - Jump directly to the end of the file (
seek(0, os.SEEK_END)). - Read backwards in fixed-size blocks (e.g., 4 KB chunks) while scanning for newline (
\n/b'\n') bytes. - Stop reading as soon as we have encountered enough newline markers to isolate the last
nlines, or when we hit the start of the file (offset 0). - Extract the target lines, decode them from bytes to ASCII strings, and return them.
Newline Off-by-One Details:
If a file ends with a newline character, that trailing \n marks the end of the final line rather than the start of a new line. We need to account for this: if the last byte of the file is \n, we must read until we encounter n + 1 newline characters to properly bound n lines.
Task 2: Health Monitoring System (SensorMonitor)
A naïve design uses a standard hash map sensor_id -> last_timestamp. While record_heartbeat is $O(1)$, get_unhealthy_sensors must inspect every tracked sensor, yielding $O(N)$ query time where $N$ is the total count of distinct sensors ever seen.
To achieve an output-sensitive query time of $O(k)$ (where $k$ is the number of stale sensors):
- Maintain an
OrderedDictmappingsensor_id -> last_timestamp. - When
record_heartbeatis called, update the stored timestamp and usemove_to_end(sensor_id)to relocate the sensor to the tail of theOrderedDict. This maintains the dictionary keys sorted in ascending order of their last ping time. - When
get_unhealthy_sensorsis called, iterate from the beginning (the oldest active timestamps). If a sensor's time delta exceedsthreshold, record it as unhealthy. The moment a sensor is found to be healthy, stop iteration immediately—all subsequent sensors were updated even more recently and are guaranteed to be healthy.
Python 3 Implementation
import os
from collections import OrderedDict
# ==========================================
# Task 1: File Tail Implementation
# ==========================================
def tail_file(filepath: str, n: int, block_size: int = 4096) -> list[str]:
"""
Returns the last n lines of a file without reading the whole file into memory.
Reads backwards from the file end using binary seeking.
"""
if n <= 0:
return []
with open(filepath, "rb") as f:
# Move to the end of the file
f.seek(0, os.SEEK_END)
file_size = f.tell()
if file_size == 0:
return []
# Determine if the file ends with a trailing newline
f.seek(file_size - 1)
ends_with_newline = (f.read(1) == b"\n")
required_newlines = n + 1 if ends_with_newline else n
pos = file_size
chunks = []
newline_count = 0
# Read backwards in fixed byte blocks
while pos > 0 and newline_count < required_newlines:
read_bytes = min(block_size, pos)
pos -= read_bytes
f.seek(pos)
chunk = f.read(read_bytes)
chunks.append(chunk)
newline_count += chunk.count(b"\n")
# Reconstruct buffer from reversed chunks
raw_buffer = b"".join(reversed(chunks))
decoded_lines = raw_buffer.decode("ascii").splitlines()
# Slice the last n lines
return decoded_lines[-n:]
# ==========================================
# Task 2: Sensor Health Monitor
# ==========================================
class SensorMonitor:
def __init__(self):
# Maps sensor_id -> timestamp in ascending order of timestamp
self._last_seen: OrderedDict[str, int] = OrderedDict()
def record_heartbeat(self, sensor_id: str, timestamp: int) -> None:
"""Registers a sensor ping. Updates timestamp and moves key to end."""
prev_time = self._last_seen.get(sensor_id)
if prev_time is not None and timestamp <= prev_time:
# Ignore stale/out-of-order pings
return
self._last_seen[sensor_id] = timestamp
self._last_seen.move_to_end(sensor_id)
def get_unhealthy_sensors(self, current_time: int, threshold: int) -> list[str]:
"""
Returns sensors that have not reported since current_time - threshold.
Runs in O(k + 1) time, where k is the number of unhealthy sensors.
"""
unhealthy_sensors = []
for sensor_id, last_timestamp in self._last_seen.items():
if current_time - last_timestamp > threshold:
unhealthy_sensors.append(sensor_id)
else:
# All remaining sensors in OrderedDict are newer and healthy
break
return unhealthy_sensors
Complexity Analysis
| Task / Method | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
Task 1: tail_file | $O(L / B)$ I/O reads | $O(L + B)$ | $L$ = byte length of last $n$ lines, $B$ = block size (4 KB). |
Task 2: record_heartbeat | $O(1)$ | $O(1)$ amortized | Hash map lookup and move_to_end linked-list pointer updates. |
Task 2: get_unhealthy_sensors | $O(k + 1)$ | $O(k)$ | $k$ = count of unhealthy sensors. Stops on first healthy sensor. |
Edge Cases to Consider
-
Task 1 (File Tail):
nlarger than total file line count: The loop hitspos == 0, decodes the entire buffer, and returns all lines correctly.- File without trailing
\n: Handled cleanly by checkingends_with_newline. - Single line larger than
block_size: The while-loop continues reading preceding blocks until a\norpos == 0is found.
-
Task 2 (Sensor Monitor):
- Out-of-order heartbeats: Late-arriving packets with smaller timestamps are dropped to avoid breaking the monotonic ordering invariant of the
OrderedDict. - Sensors reporting on exact threshold boundary (
current_time - ts == threshold): Treated as healthy based on strict inequality (> threshold).
- Out-of-order heartbeats: Late-arriving packets with smaller timestamps are dropped to avoid breaking the monotonic ordering invariant of the