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.
Watch
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.
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.
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.
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.
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.
| Minute | What happens | What you do |
|---|---|---|
| 0-3 | Intro. 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-5 | Problem 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-8 | Planning. | Naive approach in one sentence with its cost. Better approach: name the key and the data structure. Get a nod before typing. |
| 8-16 | Coding problem 1. | Top-down. Signature first, helper names second, bodies third. Narrate decisions, not keystrokes. |
| 16-19 | Testing problem 1. | Trace the example and one edge case out loud. Fix what you find. State final time and space. |
| 19-22 | Follow-ups on problem 1. | Invite a constraint. Answer in words first; change code only if asked. |
| 22-24 | Problem 2 is read. | Same opening: restate, clarify, example. |
| 24-26 | Planning. | 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-34 | Coding problem 2. | Same discipline. The easy problem is where sloppy candidates lose points; be thorough. |
| 34-37 | Testing problem 2. | Trace, edge case, complexity. |
| 37-40 | Follow-ups. | Constraints table below. |
| 40-45 | Your 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.
- 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?"
- 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?"
- 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."
- 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)."
- 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.
- 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." - 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.
- 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."
- 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?"
- 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.
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.
| Constraint | What changes | What to say |
|---|---|---|
| File is bigger than RAM | Nothing 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 all | Replace 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 key | Index 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 input | Validate 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." |
| Ties | Make 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 1000 | The 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 sorted | Group 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
- Leave a placeholder for a forgotten name. The guide says so in plain words. "I don't remember whether it's
most_commonormostCommon; I'll writeTOP_K_CALLand fix it after." Then keep going. - Say why, not what. The guide does not want a play-by-play. It wants reasons for decisions. "Dictionary because I need O(1) lookup by host" is a reason. "Now I'm typing a for loop" is noise.
- Take hints. A hint means the interviewer wants you to succeed and has spotted the gap. Repeat it back: "So you're suggesting I key by region instead of host. Yes, that removes the second pass." Then use it.
- Change course early. The guide says the sooner the better. If at minute 10 the approach is wrong, say "this is heading the wrong way; let me restart with the dictionary approach" and restart. At minute 35, do not restart; patch.
- Do not over-engineer error handling. The guide says defensive coding matters but should not come at the expense of the overall solution. One validation check and a counter of bad rows is enough. Not a custom exception hierarchy.
- Ask whether an edge case matters. "Should I handle a hostname with mixed case as the same host?" takes five seconds and shows judgment. Guessing silently shows neither.
- Do not go silent. If you need to think, say "give me twenty seconds to think about the tie-break" and then think. Silence with no announcement reads as being stuck.
- Be upfront when you do not know. The guide says it is fine not to know. "I haven't used bisect much; I'd look up the exact signature, but the idea is binary search on the sorted timestamps."
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.
| Choice | Do | Not |
|---|---|---|
| Naming | failures_by_host, line_no, parts | d, x, tmp2 |
| Early returns | if not line: continue at the top of the loop body | Four levels of nested if |
| Helper functions | parse_line(line) -> (host, status) | None, called from a short main loop | One sixty-line function |
| Constants | VALID_STATUSES = {'UP', 'DOWN'} at the top | Literal strings repeated in three places |
| Comments | Only for why: # ties: alphabetical so output is reproducible | # increment the counter |
| Bad input | One policy, stated once, applied everywhere: skip and count | Skip in one place, raise in another, print in a third |
| Output | Return a data structure; print in a separate line or function | Printing 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.
- Zoom screen sharing enabled in advance (the guide links instructions; on macOS this needs the Screen Recording permission for Zoom, which requires a restart of Zoom). Test it on a call with yourself or a friend.
- No virtual background, no blurred background, no filters. The guide defines a filter as anything that alters the video feed and asks you to disable them all.
- Headset or headphones with a microphone. The guide recommends it; it also stops echo when you narrate over the interviewer.
- Quiet room, door closed, phone silenced, notifications off on the laptop (Do Not Disturb). Nothing else on the shared screen.
- Stable connection. Wired if you can; otherwise sit next to the router and have a phone hotspot ready as a fallback.
- Webcam on, face lit from the front, laptop plugged in.
- Know CoderPad before the day: the language picker, where the output pane is, how to resize. Expect the interview pad to be plain Python 3 with the standard library and nothing else; firsthand reports say the Meta screen does not let you run the code, so do not plan around the Run button. If it is enabled, treat it as a bonus after your own dry run, not a substitute for it.
- Keep a scratch area. Put your example and expected output in a comment at the top of the pad, and your trace table in a comment under the code. Ask if you may use the drawing mode for a quick diagram.
- Have your two questions for the interviewer written on paper, plus the sticky note with the timeline.
- No outside assistance of any kind. The guide names external resources, other people and AI tools. The shared screen and the unfiltered camera are how they check.
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.
- 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.
- 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.
- 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.
- 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.
- Only then run it against the lab's expected output or LeetCode's tests.
- 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
| Session | Shape | Goal |
|---|---|---|
| 1 | File task + LeetCode easy | Finish both with the full script. Time pressure should feel mild. Fix whatever broke in the trace step. |
| 2 | File task + LeetCode medium | Finish both. Practise the minute-12 and minute-20 checkpoints on the file task so the medium gets its 18 minutes. |
| 3 | Two LeetCode mediums | Go straight to the optimal approach when you know it. Handle two constraint follow-ups per problem from the table above, out loud. |
| 4 | Final mock | Two of Meta's four linked problems, blank editor, logged. The other two on another day. |
Six pairings from the problem set
| Pair | File task | LeetCode | Session |
|---|---|---|---|
| A | Lab 7 · Join inventory with traffic | 125 Valid Palindrome (Easy) | 1 |
| B | Lab 4 · Find the busiest clients | 20 Valid Parentheses (Easy) | 1 |
| C | Lab 10 · Detect repeated failures in a time window | 419 Battleships in a Board (Medium) | 2 |
| D | Lab 3 · Keep the latest health record | 56 Merge Intervals (Medium) | 2 |
| E | Lab 8 · Match addresses to the most specific prefix | 200 Number of Islands (Medium) | 2 |
| F | Word 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 thatparse_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 withbisect. 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
- Coding before clarifying. The number one failure in every source, and the one the guide names first. Three questions, one example, then type.
- Silence. Thirty seconds of unannounced quiet reads as stuck. Announce the pause or narrate the thought.
- Bluffing complexity. "O(n)" for code with a sort in it, or "constant space" with a list of every row. The interviewer reads the code; the bluff costs more than the honest answer would have.
- Ignoring the hint. A hint repeated twice and still ignored is a failed interview even with working code.
- Rewriting from scratch at minute 35. Patch what you have, say what you would do with more time. A rewrite that does not finish shows nothing.
- Over-long error handling. Ten minutes of try/except branches on problem 1 is why problem 2 was never attempted.
- Treating the easy problem as beneath you. Passing candidates say to be thorough on the easy one; it is where sloppiness shows most clearly.
- Skipping the trace because "it's obviously right". Nothing executes. The trace is your only test and the interviewer's only evidence that you test.
- Not stating the tie-break. Every "sort by count" question has one, and the interviewer will ask.
- A filter or virtual background still on when the call starts. It costs two minutes you needed and starts the interview with an apology.
Do before marking this topic done
- Write the ten script sentences for the host-failures problem on paper from memory, then compare with the list above.
- Run sessions 1, 2 and 3 above on three different days, recorded, logged in the tracker. Watch each recording once.
- For one recorded session, write down every silence over fifteen seconds and what you should have said instead.
- Pick any lab from the labs page and answer all eight constraint rows out loud for it, in under a minute each.
- Complete the setup checklist, including a real screen-share test on Zoom.
- 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' →