KatInterview

Efficient Large File Tailer and Sensor Heartbeat Monitor

Data Structure DesignModel answer
MediumModel answerData Structure Designfile-iosliding-windowordered-dict

Last 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 than current_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_heartbeat should run in $O(1)$ time. get_unhealthy_sensors should 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.