Skip to main content

A 20 GB server log has one request per line with date, time, method, path and status code. Count the 500 errors per path without loading the file into memory. For example, three lines with status 500, two for /predict and one for /health, give /predict 2 and /health 1.

Coding rounds · Intermediate 1

Short answer

Open the file and iterate over it line by line, because a file object is a lazy iterator that holds one line at a time. Split each line, skip malformed ones, and update a Counter keyed by path. Time is O(n) in lines; memory is O(p) for p distinct paths, not the file size.

Deeper answer

First clarify the format. Ask which field holds the status, whether fields are separated by spaces, whether some lines are malformed or span several lines, and what encoding the file uses. Ask if the output is small enough to hold in memory, which is true for counts per path.

The core is with open(path, encoding="utf-8", errors="replace") as f, then for line in f. Do not call f.read() or f.readlines(), because both load everything. For each line run parts = line.split(). If len(parts) != 5, add one to a bad-line count and continue. If parts[4] == "500", run counts[parts[3]] += 1, where counts is a Counter. At the end, counts.most_common(10) gives the worst paths.

One pass is O(n) time and memory stays constant apart from the Counter. Test an empty file, blank lines, a broken line and a final line with no newline. Say that you report how many lines were skipped, that gzip.open reads compressed logs the same way, and that a generator function keeps parsing separate from counting.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Files and errors

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.