← all topics

20 · The 45-minute coding interview script Code

Clarify, baseline, optimise, test, complexity, communicate · timed rehearsal

Why it matters for NPE. The guide says structure and communication are graded. Rehearsing the script matters as much as knowing the patterns.

Primer: the screen is a 45-minute performance, not a quiz

Meta's own guide says the interviewer grades efficiency, structure, syntax/language familiarity, bugs and correctness, on CoderPad, with hints offered along the way and constraints added once you have something working. Firsthand reports add the shape: two problems in 45 minutes, usually one file-handling task and one LeetCode easy or medium, and in most reports nothing executes. So the interviewer only sees what you say and type. A correct solution you did not explain, test out loud or time-box scores lower than a plain solution you narrated, traced and sized.

This page is the script. The patterns live in topic 1 (Python fluency), topic 5 (file parsing) and the topics between. The timed rehearsal with Meta's own linked problems is the final mock; do not open it until you have run this script at least three times.

One rule: say the plan before the code, say the trace after the code, say the complexity in the interviewer's variables. Plan, code, trace, cost. Every problem, every time, even the easy one.

Watch

Top 5 Coding Interview MISTAKES (from a Google Engineer)NeetCode · 8:02

The five failure modes map onto Meta's criteria. 0:38 jumping straight to code, 2:30 going silent, 4:24 tunnel vision, 5:54 not managing time. Eight minutes; watch it the night before.

How to Solve ANY Coding Interview Question in 6 StepsAnthony D. Mays · 12:33

Repeat, clarify, examples, brainstorm, implement, test. 7:48 covers what to do when you only have the naive solution, which the Meta guide says is a fine place to start.

How to: Work at Google — Example Coding/Engineering InterviewLife at Google · 24:02

A full staged interview on an easy problem. Watch how the candidate narrates, how 10:53 handles a new constraint (unsorted input) and how 19:16 handles the scale follow-up. This is the think-aloud model to copy.

Cracking the Facebook Coding Interview The ApproachSiamak Sobhany · 1:49:09

Linked from the Meta guide. This is a third-party re-upload of a Facebook recruiting session, not a Meta channel. Long; watch the first 30 minutes for the method and skip the rest once you can state it.

Cracking the Facebook Coding Interview Problem Walk ThroughSiamak Sobhany · 1:06:52

Also linked from the Meta guide, same third-party channel. Worked problems using the approach above. Optional. Pair it with a timer.

The 45-minute timeline

Two problems leave about 15-18 minutes each once you subtract the intro and your questions. The clock below is the target. Put it on a sticky note next to the screen for your rehearsals; you will not have it in the interview, so the rhythm has to be in your body.

MinuteWhat happensWhat you do
0-3Intro. Interviewer introduces themself and asks about you.Two sentences about your background and one about why this role. Do not run past a minute. Confirm Python.
3-5Problem 1 is pasted or read.Read it twice. Restate it. Ask your three clarifying questions. Write a tiny example and its expected output in a comment.
5-8Planning.Naive approach in one sentence with its cost. Better approach: name the key and the data structure. Get a nod before typing.
8-16Coding problem 1.Top-down. Signature first, helper names second, bodies third. Narrate decisions, not keystrokes.
16-19Testing problem 1.Trace the example and one edge case out loud. Fix what you find. State final time and space.
19-22Follow-ups on problem 1.Invite a constraint. Answer in words first; change code only if asked.
22-24Problem 2 is read.Same opening: restate, clarify, example.
24-26Planning.If you know the optimal approach, say so and go straight to it. Reports from candidates who passed say not to perform a fake brute force.
26-34Coding problem 2.Same discipline. The easy problem is where sloppy candidates lose points; be thorough.
34-37Testing problem 2.Trace, edge case, complexity.
37-40Follow-ups.Constraints table below.
40-45Your questions.Two prepared questions about the team's work. Thank them. Stop talking when time is called.

If problem 1 runs long. Set two checkpoints. At minute 12, if you are not typing yet, say: "I'll implement the straightforward version now and optimise if we have time." At minute 20, if the code is not finished, say: "I'm at the last piece; let me write what's left as a comment so we can keep moving, then I'll come back if there's time." Never let problem 1 pass minute 25 silently. A hint from the interviewer at this point is a gift; take it immediately. Two half-finished problems beat one polished problem and one you never saw, because the second problem is the one that shows your range.

The script per problem

Ten steps, with the sentences to say. Rehearse them until the words are automatic so your attention is free for the problem.

  1. Restate the problem. "So I'm given a file of host,status lines and I need to print each host's failure count, sorted by count descending. Is that right?"
  2. Ask three clarifying questions. Pick the three that matter for this problem from these four groups:
    • Input format and size: "Is the file plain CSV without quoting, and roughly how many lines? Does it fit in memory?"
    • Duplicates, empty, malformed: "Can a host appear on many lines? Can there be blank lines or lines with the wrong number of fields? Should I skip them or stop?"
    • Output order and ties: "Descending by count; if two hosts tie, alphabetical by name? Do you want all hosts or only the top k?"
    • In-memory or streaming: "Can I assume the whole thing fits in memory, or should I design for a stream from the start?"
  3. Give a small example and the expected output. Type it as a comment at the top of the pad. "With web-01 DOWN, web-02 UP, web-01 DOWN, I expect web-01: 2 and web-02: 0."
  4. State the naive approach and its cost in one sentence. "The naive way is to re-scan the file for every distinct host, which is O(n times u)."
  5. State the better approach before coding. Name the key and the data structure. "Better: one pass, a dictionary keyed by hostname holding the count, then sort the items. That's O(n) to count and O(u log u) to sort." Wait for the nod.
  6. Write the code top-down. Function signature, then the loop with helper calls whose names say what they do (parse_line, is_valid), then the helpers. Small functions, good names. Say why when you choose something: "I'll use Counter so a missing key reads as zero."
  7. Dry-run out loud with the example. Nothing executes, so you are the interpreter. "Line 1: parts is ['web-01','DOWN'], status is DOWN, counts['web-01'] becomes 1." Then one edge case: empty file, one host, malformed line, tie.
  8. State final time and space in the interviewer's variables. "Time O(n + u log u) for n lines and u distinct hosts, space O(u) for the dictionary. Nothing is proportional to the file size except the pass itself."
  9. Say what you did not handle, on purpose. "I'm skipping malformed lines and counting them; I'm not validating the hostname format. Does that matter here?"
  10. Invite the constraint. "Should we talk about what changes if the file doesn't fit in memory, or if you only want the top k?" Then use the table further down.

Steps 1 to 5 take three minutes with practice. If they take six, you are talking too much; if they take one, you skipped a question that will bite you at step 7.

Dry-running without an executor

Reports say you will not be able to run code, so you trace it. A trace table is a comment block with one column per variable and one row per loop step. Write it in a scratch area under the code. Here is a five-line function and its table on ['a', 'b', 'a'].

def first_repeated(words):
    seen = set()
    for w in words:
        if w in seen:
            return w
        seen.add(w)
    return None

# trace: words = ['a', 'b', 'a']
# step | w   | w in seen | seen after | returns
#  1   | 'a' | False     | {'a'}      |
#  2   | 'b' | False     | {'a','b'}  |
#  3   | 'a' | True      |            | 'a'
# edge: words = []  ->  loop body never runs  ->  returns None
# edge: words = ['a']  ->  step 1 False, loop ends  ->  returns None

Rules for the trace. Say every row out loud as you write it. Index from the same base the code uses. Track the loop variable and every piece of state the loop mutates; nothing else. Run at least one edge case where the loop body never executes, since off-by-one and wrong-default bugs live there. If a row surprises you, that is a bug, and you found it before the interviewer did. Say "good, that's wrong, let me fix it" and fix it; finding your own bug is a positive signal.

Dry-run order that catches the most bugs per minute: 1. the example you wrote in step 3 (does the happy path produce the expected output?) 2. empty input (does it return the right empty thing, not crash?) 3. one element / one line (does the loop reach the return?) 4. the tie or the duplicate (is the ordering rule actually applied?) 5. one malformed record (does the policy you stated happen?)

Handling "now add a constraint"

The guide says you could be asked to solve the problem in multiple ways and that the interviewer may add constraints. Answer in words first, in under a minute, then change code only if asked. The table is what changes.

ConstraintWhat changesWhat to say
File is bigger than RAMNothing in a line-by-line loop. The risk is state: distinct keys, kept rows. Partition by key hash to temp files, or aggregate per bucket, or use seek/tell offsets for random access."My loop already streams. What grows is the dictionary, so I'd ask how many distinct hosts there are; if unbounded, I'd partition by hash of the key to several files and aggregate each."
Top k instead of allReplace the full sort with heapq.nlargest(k, ...) or a size-k min-heap: O(u log k) instead of O(u log u). Define the tie-break. See topic 7."I'd keep a heap of size k; that drops the sort from u log u to u log k. Ties: count descending then name ascending."
Two files joined on a keyIndex the smaller file in a dictionary, stream the larger one and look up. Missing keys get an explicit policy (skip, UNKNOWN bucket, count). The dinosaur pattern in topic 5."Load the inventory into a dict keyed by host, stream traffic and look up each row. Unknown hosts go into an UNKNOWN bucket so nothing is silently lost."
Malformed inputValidate the field count and types per line; record line number and reason; continue. One narrow try/except around the conversion, not around the whole loop."I'd check len(parts) and int() per line, record bad rows with their line numbers and keep going. I would not wrap the whole loop in a bare except."
TiesMake the sort key a tuple with a deterministic secondary field. Python's sort is stable, so equal keys keep input order if that is the rule."Key becomes (-count, name) so ties are alphabetical and reproducible."
100 devices becomes 1000The per-device work is I/O bound, so use a thread pool with a bounded size, a per-connection timeout, and collect failures separately. Keep parsing in a pure function so it is testable."Sequential is 1000 round trips. I'd use ThreadPoolExecutor with maybe 20-50 workers, timeouts per device, and return successes and failures as two lists."
Memory limit (for example, 100 MB)Compute the state size: keys times bytes per entry. If it fits, say so with numbers. If not, bucket, approximate (reservoir sampling for a random record), or spill to disk."A million distinct hosts at roughly 100 bytes each is about 100 MB, so that's the edge. Below that the dict is fine; above it I'd partition."
Input is already sortedGroup with a single pass and a running key; no dictionary needed, O(1) extra space. Two sorted files merge with two pointers."Sorted input means I can group adjacent lines and emit as I go, dropping the dictionary entirely."

Communication rules, straight from the guide

Code quality that reads well on screen

The interviewer is reading your code on a shared screen while you type it. Structure is graded. These choices make a thirty-line solution readable at a glance.

ChoiceDoNot
Namingfailures_by_host, line_no, partsd, x, tmp2
Early returnsif not line: continue at the top of the loop bodyFour levels of nested if
Helper functionsparse_line(line) -> (host, status) | None, called from a short main loopOne sixty-line function
ConstantsVALID_STATUSES = {'UP', 'DOWN'} at the topLiteral strings repeated in three places
CommentsOnly for why: # ties: alphabetical so output is reproducible# increment the counter
Bad inputOne policy, stated once, applied everywhere: skip and countSkip in one place, raise in another, print in a third
OutputReturn a data structure; print in a separate line or functionPrinting from inside the counting loop
from collections import Counter

VALID_STATUSES = {'UP', 'DOWN'}

def parse_line(line):
    """Return (host, status) or None for a line that should be skipped."""
    parts = [p.strip() for p in line.strip().split(',')]
    if len(parts) != 2 or not parts[0]:
        return None
    host, status = parts[0].lower(), parts[1].upper()
    if status not in VALID_STATUSES:
        return None
    return host, status

def failures_by_host(path):
    counts = Counter()
    skipped = 0
    with open(path, encoding='utf-8') as f:
        for line in f:
            parsed = parse_line(line)
            if parsed is None:
                skipped += 1
                continue
            host, status = parsed
            counts[host] += status == 'DOWN'   # hosts that are only UP still appear with 0
    ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
    return ranked, skipped

Note what the interviewer sees without you saying a word: a constant, a helper with a docstring that states the contract, one skip policy, a sort key with the tie-break in it, and a return value instead of prints. That is the "structure" criterion, satisfied in silence.

CoderPad and Zoom setup checklist

Do this the day before, not ten minutes before. The guide says setup may take a few minutes and asks you to have it ready.

CoderPad Interview: Candidate's GuideCoderPad · 5:59

The actual tool, from the vendor. 0:43 the pad layout, 1:14 coding and running, 3:01 drawing mode. Six minutes so the interface is boring on the day.

Blank-editor rehearsal protocol

The guide's own advice: practise under similar circumstances, because a coding interview is an unnatural event even for people who code every day. The circumstances are a blank editor, a clock, and a listener. Recreate all three.

  1. Timer visible. 45 minutes for two problems, or 18 minutes for one. When it rings, stop typing and state where you are, exactly as you would in the interview.
  2. No autocomplete, no linter, no run button. A plain text editor or CoderPad's free sandbox with execution disabled by discipline. Browser closed except the problem statement.
  3. Talk out loud the whole time. Every step of the script, including the trace table. If no one is there, talk anyway. The habit is the point.
  4. Record yourself with screen and audio. Watch the playback at double speed and note every silence longer than fifteen seconds and every decision you did not explain.
  5. Only then run it against the lab's expected output or LeetCode's tests.
  6. Log honestly in the tracker. Independent means working code with no hints and no peeking. A hint used is a hint logged. Logging a near miss as a pass costs you the signal you need for the next session.

Play the two-minute reminder before each session: How to talk during your coding interview (Formation, 2:38).

Three sessions, then the mock

SessionShapeGoal
1File task + LeetCode easyFinish both with the full script. Time pressure should feel mild. Fix whatever broke in the trace step.
2File task + LeetCode mediumFinish both. Practise the minute-12 and minute-20 checkpoints on the file task so the medium gets its 18 minutes.
3Two LeetCode mediumsGo straight to the optimal approach when you know it. Handle two constraint follow-ups per problem from the table above, out loud.
4Final mockTwo of Meta's four linked problems, blank editor, logged. The other two on another day.

Six pairings from the problem set

PairFile taskLeetCodeSession
ALab 7 · Join inventory with traffic125 Valid Palindrome (Easy)1
BLab 4 · Find the busiest clients20 Valid Parentheses (Easy)1
CLab 10 · Detect repeated failures in a time window419 Battleships in a Board (Medium)2
DLab 3 · Keep the latest health record56 Merge Intervals (Medium)2
ELab 8 · Match addresses to the most specific prefix200 Number of Islands (Medium)2
FWord frequency from topic 5 (top 10 words, case-insensitive, punctuation stripped)347 Top K Frequent Elements (Medium)2 or 3

For session 3, pair two mediums that use different patterns, for example 811 Subdomain Visit Count with 56, or 937 Reorder Data in Log Files with 200. Both pairings put a parsing problem next to a structural one, which is the mix the reports describe.

Interview questions

These are the meta-questions an interviewer asks about your code, as opposed to the problem itself. Answer in the interviewer's variables and in under four sentences.

1. What's the complexity?Name the variables first, then the cost. "For n lines and u distinct hosts: O(n) to count, O(u log u) to sort, so O(n + u log u) time and O(u) space." If you sorted only top k, say O(u log k). Never say "linear-ish".
2. Can you do it in one pass?Counting is already one pass; the sort is a second pass over u items, not n. If the question is about a two-pass algorithm (for example first-unique-character), the answer is usually "one pass over the input plus a pass over the much smaller state", and say which is which. If true single-pass is required, ask what can be assumed about the input (sorted? bounded alphabet?).
3. How would you test this?"The example we wrote, then empty input, one record, a duplicate key, a tie, a malformed line, and a file with only a header." Then mention that parse_line is a pure function, so it gets unit tests on its own without a file.
4. What if the input is sorted?Grouping becomes a single pass with a running key and O(1) extra space, with no dictionary. Two sorted inputs merge with two pointers. Lookup becomes binary search with bisect. Say which of those applies to this problem.
5. What if the file doesn't fit in memory?The streaming loop is unchanged. The dictionary is the risk, so I would ask about key cardinality. If it is unbounded: partition by hash of the key to temp files and aggregate each, or aggregate per time bucket, or if a random record is wanted use reservoir sampling or byte offsets with seek. Details in topic 5.
6. Why a dictionary and not a list?Lookup by key is O(1) expected versus O(n) for a list scan, so n lookups cost O(n) rather than O(n squared). A list is right when the data is positional or needs to be sorted in place.
7. What if k is larger than the number of distinct items?heapq.nlargest and slicing both return everything available with no error, but I'd say so explicitly and confirm that is the wanted behaviour rather than an error.
8. Can you do it without the extra set or dictionary?Usually yes with a trade: sort first for O(n log n) time and O(1) extra space, or use the input itself as storage if mutation is allowed. State the trade and ask which resource matters more.
9. What happens on a line with the wrong number of fields?"My parse function returns None, the loop counts it and continues. I'd report the skipped count at the end." Then ask whether the interviewer would rather fail fast, since for a config file that might be the right policy.
10. How would you scale this from 100 devices to 1000?The per-device work is network I/O, so a thread pool with a bounded number of workers, a per-device timeout, and a result list plus a failure list. Parsing stays a pure function. Beyond a few thousand, asyncio or a job queue; say that only if asked.
11. Why Python?"It's the language I'm fastest and most correct in, and the guide says to use the strongest language. It's also what the role's automation is written in." The guide warns against picking a language to impress.
12. Walk me through your code again.Go top-down: the contract of the main function, then each helper's contract, then the one loop. Do not re-read lines. Thirty seconds.

Traps

Do before marking this topic done

  1. Write the ten script sentences for the host-failures problem on paper from memory, then compare with the list above.
  2. Run sessions 1, 2 and 3 above on three different days, recorded, logged in the tracker. Watch each recording once.
  3. For one recorded session, write down every silence over fifteen seconds and what you should have said instead.
  4. Pick any lab from the labs page and answer all eight constraint rows out loud for it, in under a minute each.
  5. Complete the setup checklist, including a real screen-share test on Zoom.
  6. Then open the final mock. The network script is the same idea for the other 45 minutes.

← 19 · Troubleshooting walkthroughs · all topics · 21 · Network interview script, behavioral and 'Why Meta' →