Skip to content
LumenaryAcademy
Scale 90 min

Technical interviews

How software engineering interviews generally work, a method for solving problems out loud, and the patterns worth practising.

Code tested · 9AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Computer Scientist, Margaret · The Experimenter, Gideon · The Verifier

MotivationH

What interviews try to measure

A company hiring a software engineer wants to know, in a few hours, whether this person will write correct, clear code, reason about cost, design systems that hold up, and work well with colleagues for years. No interview can measure that directly, so companies sample: small problems solved live, a design discussion, questions about past work. The sample is noisy. Strong engineers sometimes have a bad day; interviewers differ; one unlucky question can dominate. Companies know this, which is why they use several interviewers and several kinds of interview.

So treat this lesson as two things at once. It is practical preparation: how the process usually runs, a method that makes your thinking visible, and the problem patterns that appear again and again. And it is a reminder that the skills interviews sample — the ones you have built through this course — matter far more than interview technique. The best preparation is being good at the work; the second best is practising showing it.

ExplanationH

How the process generally works

Details differ between companies and change over time, so read each company's own pages (linked below) for the current picture. In general terms, a software engineering process at a large technology company looks like this:

  1. Application and recruiter conversation. A recruiter checks the role fits, explains the process and answers questions. Ask them what the interviews will cover; they want you to be prepared.
  2. Technical screen. One or two interviews of about 45–60 minutes, usually by video with a shared editor, solving one or two coding problems. Some companies use an online assessment instead or as well.
  3. The loop (often still called the "onsite", though frequently virtual). Typically four to six interviews in a day or spread over several days:
    • Coding interviews: a problem, discussed and solved in code, with attention to correctness, complexity, clarity and testing.
    • System design interviews, mainly for mid-level and senior roles: an open-ended design discussion like the ones in System design.
    • Behavioural interviews: questions about past situations — a conflict, a mistake, a project you led — to understand how you work with people. Some companies anchor these in published values; Amazon, for example, builds them around its Leadership Principles.
    • Sometimes a domain interview: machine learning, mobile, front-end, security, or a deep dive on a past project.
  4. Decision. Interviewers write independent feedback; a debrief or a separate hiring committee decides, and the level of the offer often depends on the design and behavioural signals as much as on coding.

Startups vary more: take-home projects, pair programming on a realistic task, or a conversation about something you built. The underlying questions are the same.

If you need accommodations — for a disability, for example — ask the recruiter early. Large companies have processes for this, and asking does not count against you.

ComputationC

A method: clarify, examples, brute force, optimise, test

Interviewers assess how you reach a solution, not only whether you do. A visible, repeatable method helps you think and lets them follow. Here it is, applied to an original problem.

Example— The conductor's shift

A bus route has nn stops; boarding[i] passengers board at stop ii. A stop is busy if more than cap passengers board there. A conductor works one contiguous stretch of stops, and union rules allow at most q busy stops in a shift. What is the largest total number of boardings one shift can cover?

1. Clarify. Ask about everything the statement leaves open. Can counts be negative? (No — so adding a stop never decreases the total; remember this.) Can the list be empty? (Yes; answer 0.) Can q be 0? (Yes.) How large is nn? (Up to 10510^5 — so quadratic time is too slow, and the target is about O(n)O(n) or O(nlog⁡n)O(n \log n).) Should I return the stretch or just the total? (Just the total.)

2. Examples. Make small ones, including awkward ones. With boarding = [4, 12, 3, 15, 2, 6], cap = 10, q = 1, the busy stops are the 12 and the 15. Stretches with at most one busy stop include [4, 12, 3] (19) and [3, 15, 2, 6] (26); the answer is 26. Edge cases: all stops busy and q = 0 gives 0; no stops busy gives the sum of everything.

3. Brute force. Try every stretch: for each start, extend the end while counting the total and the busy stops. That is O(n2)O(n^2) — correct, simple, and worth stating aloud even if you will not code it, because it gives you a baseline and a way to test.

4. Optimise. Look for wasted work. When the brute force moves its start one step right, it recomputes almost the same stretches. Because counts are non-negative, for each end position the best start is the leftmost one that keeps at most q busy stops — and that leftmost start never moves backwards as the end moves forward. That is the signal for a sliding window: advance the right edge one stop at a time, and advance the left edge only when the window holds too many busy stops. Each stop enters and leaves the window once: O(n)O(n) time, O(1)O(1) extra space.

5. Test. Walk through your example by hand, then the edge cases. In practice — and in your own preparation — compare the fast solution with the brute force on many random inputs:

python
import random

def best_shift_brute(boarding, cap, q):
    """Try every stretch [i, j]: O(n^2) with a running total."""
    best = 0
    for i in range(len(boarding)):
        total = busy = 0
        for j in range(i, len(boarding)):
            total += boarding[j]
            busy += boarding[j] > cap
            if busy > q:
                break                     # extending further only adds busy stops
            best = max(best, total)
    return best

def best_shift(boarding, cap, q):
    """Sliding window: O(n). Valid because counts are never negative."""
    best = total = busy = left = 0
    for right, b in enumerate(boarding):
        total += b
        busy += b > cap
        while busy > q:                   # shrink from the left until the window is valid
            total -= boarding[left]
            busy -= boarding[left] > cap
            left += 1
        best = max(best, total)
    return best

# The examples worked out by hand while clarifying the problem:
assert best_shift([4, 12, 3, 15, 2, 6], cap=10, q=1) == 26      # stops 2-5: 3 + 15 + 2 + 6
assert best_shift([], cap=10, q=1) == 0
assert best_shift([30, 40], cap=10, q=0) == 0
assert best_shift([5, 5, 5], cap=10, q=0) == 15

# Test the fast version against the obviously correct slow one on many random inputs.
rng = random.Random(0)
for trial in range(2000):
    n = rng.randint(0, 12)
    stops = [rng.randint(0, 20) for _ in range(n)]
    cap, q = rng.randint(0, 20), rng.randint(0, 3)
    assert best_shift(stops, cap, q) == best_shift_brute(stops, cap, q), (stops, cap, q)
print("2000 random cases agree with the brute force")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Notice where the non-negativity from step 1 was used. If counts could be negative, extending a window could lower its total, the window argument would fail, and a different technique would be needed. Clarifying is not a formality; it often decides the algorithm.

Worked examplesH

Patterns worth practising

Most interview problems are built on a small number of ideas. Recognising which one applies is most of the work. Each pattern below comes with an original practice problem and a runnable solution with its own random tests; try each problem yourself before reading the code.

Two pointers

Signal: sorted input, or two sequences walked in step; pairs or ranges whose validity changes monotonically as an index moves.

Platform gaps. Two platforms of a station each have a sorted list of departure minutes. A departure at minute tt blocks minute tt. A cleaner needs kk consecutive minutes, within [start,end)[\text{start}, \text{end}), during which no train departs from either platform. Return the earliest starting minute, or −1. Merging the two sorted lists with one pointer each visits departures in time order without building a combined list: O(n+m)O(n + m).

Sliding window

Signal: "longest / shortest / best contiguous stretch such that…", where the condition gets easier to satisfy as the window shrinks. The conductor's shift above is this pattern. Beware: it needs a monotonic condition (like non-negative counts).

Hashing

Signal: "have I seen this before?", counting, grouping, or "find two things that combine to a target". A dictionary turns a repeated search into a lookup.

Balancing ledgers. Two branches of a cooperative record the same day's transactions, each in its own order. An auditor wants every point kk at which the first kk entries of both ledgers contain exactly the same amounts, with the same multiplicities — places where both ledgers can be cut and still balance. Sorting both prefixes at every kk costs O(n2log⁡n)O(n^2 \log n). Instead, keep a dictionary from amount to (count in the first ledger's prefix) − (count in the second's), and a running number of amounts whose difference is nonzero; each new pair of entries updates two counts in O(1)O(1), and the ledgers balance exactly when that number is zero. One pass, O(n)O(n).

python
import random

# Pattern 1, two pointers: the earliest free gap across two platforms' sorted timetables.
def earliest_gap(a, b, k, start, end):
    """a, b: sorted departure minutes; a departure at minute t blocks minute t.
    Return the earliest s with start <= s and s + k <= end such that no departure
    falls in [s, s + k), or -1."""
    i = j = 0
    s = start                                  # earliest candidate start so far
    while i < len(a) or j < len(b):
        # take the next departure in time order from either list (one step of a merge)
        if j == len(b) or (i < len(a) and a[i] <= b[j]):
            t, i = a[i], i + 1
        else:
            t, j = b[j], j + 1
        if t < s:
            continue                           # before the candidate window: irrelevant
        if s + k <= t:
            break                              # a long enough gap ends at this departure
        s = t + 1                              # this departure blocks the window: move past it
    return s if s + k <= end else -1

def gap_brute(a, b, k, start, end):
    busy = set(a) | set(b)
    for s in range(start, end - k + 1):
        if all(m not in busy for m in range(s, s + k)):
            return s
    return -1

assert earliest_gap([5, 20, 40], [12, 21, 30], k=8, start=0, end=60) == 22   # [22, 30)
assert earliest_gap([5, 20, 40], [12, 21, 30], k=5, start=0, end=60) == 0    # [0, 5)
assert earliest_gap([0, 1, 2], [3], k=2, start=0, end=5) == -1               # only [4, 5) is free
assert earliest_gap([10], [10], k=3, start=8, end=20) == 11                  # a shared minute

# Pattern 2, hashing: where do two branches' ledgers balance?
def balance_points(a, b):
    """a, b: the same day's transaction amounts as recorded by two branches, in different orders.
    Return every k such that the first k entries of a and of b hold exactly the same amounts,
    with the same multiplicities."""
    diff = {}                                  # amount -> (count in a's prefix) - (count in b's prefix)
    unbalanced = 0                             # how many amounts currently have a nonzero difference
    points = []
    for k, (x, y) in enumerate(zip(a, b), start=1):
        for amount, change in ((x, 1), (y, -1)):
            before = diff.get(amount, 0)
            after = before + change
            diff[amount] = after
            unbalanced += (after != 0) - (before != 0)
        if unbalanced == 0:
            points.append(k)
    return points

def balance_brute(a, b):
    return [k for k in range(1, len(a) + 1) if sorted(a[:k]) == sorted(b[:k])]

print("balance points:", balance_points([40, 15, 15, 70, 5, 30], [15, 40, 70, 15, 30, 5]))

rng = random.Random(3)
for _ in range(500):
    a = sorted(rng.sample(range(40), rng.randint(0, 8)))
    b = sorted(rng.sample(range(40), rng.randint(0, 8)))
    k, start = rng.randint(1, 8), rng.randint(0, 10)
    assert earliest_gap(a, b, k, start, 40) == gap_brute(a, b, k, start, 40), (a, b, k, start)
    a = [rng.choice([5, 10, 15, 20]) for _ in range(rng.randint(0, 10))]
    b = a[:]
    rng.shuffle(b)
    if b and rng.random() < 0.3:
        b[rng.randrange(len(b))] = 25          # sometimes the ledgers genuinely disagree
    assert balance_points(a, b) == balance_brute(a, b), (a, b)
print("500 random cases of each agree with brute force")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Breadth-first and depth-first search

Signal: grids, maps, networks, dependencies, "fewest steps", "is it reachable", "how many connected regions". BFS finds shortest paths when every step costs the same; DFS explores and detects cycles. (Revisit Graphs.) The crucial step is often choosing what a node is: not always a cell, but a state.

The drone's battery. A delivery drone flies on a grid (# blocked). Each move costs one unit of battery; it cannot move with an empty battery; landing on a charging pad C refills it. Find the fewest moves from S to T. A cell alone is not enough state — reaching a cell with more battery is better — so BFS runs over states (row, column, battery).

Binary search on the answer

Signal: "find the minimum (or maximum) value such that something is possible", where possibility is monotonic: if radius rr works, any larger radius works too. Then you can binary-search the value and only ever answer the easier yes/no question.

Village routers. Houses stand at integer positions along a road. You may install kk routers, each covering every house within distance rr. Find the smallest integer rr that covers every house. Checking a given rr is greedy: put a router just far enough right to cover the leftmost uncovered house, and repeat. Binary search over rr needs O(log⁡D)O(\log D) checks, each O(n)O(n) after sorting.

python
from collections import deque
import random

# Pattern 3, breadth-first search over states: a delivery drone with a battery.
def drone_moves(grid, battery):
    """Fewest moves from S to T. Each move (up/down/left/right) uses 1 unit of battery;
    the drone cannot move with an empty battery; landing on C recharges it to full.
    '#' cells are blocked. Returns -1 if T is unreachable."""
    rows, cols = len(grid), len(grid[0])
    start = next((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == "S")
    state = (start[0], start[1], battery)
    seen = {state}
    queue = deque([(state, 0)])
    while queue:
        (r, c, b), dist = queue.popleft()
        if grid[r][c] == "T":
            return dist                        # BFS: the first time we reach T is the fewest moves
        if b == 0:
            continue
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#":
                nb = battery if grid[nr][nc] == "C" else b - 1
                if (nr, nc, nb) not in seen:
                    seen.add((nr, nc, nb))
                    queue.append(((nr, nc, nb), dist + 1))
    return -1

city = ["S.........T",
        ".#########.",
        ".....C....."]
for b in (6, 7, 9, 10):
    print(f"battery {b:2d}: fewest moves {drone_moves(city, b)}")

# Pattern 4, binary search on the answer: the smallest router radius.
def enough_routers(houses, k, r):
    """Greedy check: can k routers of radius r cover every house? (houses sorted)"""
    used, covered_to = 0, None
    for x in houses:
        if covered_to is None or x > covered_to:
            used += 1                          # put a router at x + r: covers [x, x + 2r]
            covered_to = x + 2 * r
            if used > k:
                return False
    return True

def smallest_radius(houses, k):
    houses = sorted(houses)
    lo, hi = 0, (houses[-1] - houses[0] + 1) // 2      # hi always works: one router suffices
    while lo < hi:                             # invariant: the answer lies in [lo, hi]
        mid = (lo + hi) // 2
        if enough_routers(houses, k, mid):
            hi = mid                           # mid works: the answer is mid or smaller
        else:
            lo = mid + 1                       # mid fails: the answer is larger
    return lo

village = [1, 2, 3, 20, 21, 40, 46, 50]
for k in (1, 2, 3, 4):
    print(f"{k} routers: smallest radius {smallest_radius(village, k)}")

rng = random.Random(9)
for _ in range(300):
    hs = [rng.randint(0, 60) for _ in range(rng.randint(1, 9))]
    k = rng.randint(1, 4)
    brute = next(r for r in range(0, 61) if enough_routers(sorted(hs), k, r))
    assert smallest_radius(hs, k) == brute
print("binary search agrees with a linear scan on 300 random villages")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Heaps

Signal: "repeatedly take the smallest / largest / most urgent", "top kk", merging sorted streams, scheduling. A heap gives O(log⁡n)O(\log n) insert and remove-min (see Heaps).

The clinic. A clinic has one doctor. Patients arrive with an urgency level and an expected duration. Whenever the doctor is free, she sees the waiting patient with the highest urgency, ties going to the earlier arrival. Return the order in which patients are seen. A heap of waiting patients keyed by (−urgency, arrival) does exactly this; when nobody is waiting, the clock jumps to the next arrival.

Dynamic programming

Signal: "count the ways", "minimum cost", "maximum value", where the answer for a problem is built from answers to smaller versions of it, and the same smaller versions recur. Define the subproblem in words first, then the recurrence, then the order of computation (Dynamic programming).

Bread rolls. A bakery sells packs of rolls in several sizes and prices, as many of each as you like. What is the cheapest way to buy at least nn rolls? Let best[i] be the cheapest way to get at least ii rolls. Then best[i] = min over packs of price + best[max(0, i − size)]: buying a pack covers size of the rolls still needed, and anything beyond what is needed is simply extra. The max(0, …) is where "at least" enters, and it is easy to miss.

python
import heapq

# Pattern 5, heaps: the order in which a clinic's single doctor sees patients.
def clinic_order(patients):
    """patients: (name, arrival, duration, urgency). Whenever the doctor is free, she sees the
    waiting patient with the highest urgency, breaking ties by earlier arrival, then name."""
    by_arrival = sorted(patients, key=lambda p: p[1])
    waiting, order = [], []
    clock, i = 0, 0
    while i < len(by_arrival) or waiting:
        if not waiting and by_arrival[i][1] > clock:
            clock = by_arrival[i][1]           # nobody waiting: jump to the next arrival
        while i < len(by_arrival) and by_arrival[i][1] <= clock:
            name, arrival, duration, urgency = by_arrival[i]
            heapq.heappush(waiting, (-urgency, arrival, name, duration))
            i += 1
        _, _, name, duration = heapq.heappop(waiting)
        order.append(name)
        clock += duration
    return order

patients = [("Ama", 0, 30, 2), ("Bo", 5, 10, 5), ("Chidi", 10, 20, 2),
            ("Dilnoza", 12, 15, 4), ("Emre", 50, 5, 1), ("Farah", 90, 10, 3)]
print("clinic order:", clinic_order(patients))
assert clinic_order(patients) == ["Ama", "Bo", "Dilnoza", "Chidi", "Emre", "Farah"]

# Pattern 6, dynamic programming: the cheapest way to buy AT LEAST n bread rolls.
def cheapest_rolls(n, packs):
    """packs: (size, price) pairs, each available in unlimited number."""
    best = [0] + [float("inf")] * n            # best[i] = cheapest way to get at least i rolls
    for i in range(1, n + 1):
        for size, price in packs:
            best[i] = min(best[i], price + best[max(0, i - size)])
    return best[n]

packs = [(4, 7), (6, 10), (10, 15)]            # 4 rolls for 7, 6 for 10, 10 for 15
for n in (5, 12, 19, 21):
    print(f"at least {n:2d} rolls: cheapest {cheapest_rolls(n, packs)}")

def cheapest_brute(n, packs):
    """Try every combination of pack counts that could matter."""
    best = float("inf")
    def go(k, need, cost):
        nonlocal best
        if need <= 0 or k == len(packs):
            if need <= 0:
                best = min(best, cost)
            return
        size, price = packs[k]
        for c in range(need // size + 2):
            go(k + 1, need - c * size, cost + c * price)
    go(0, n, 0)
    return best

for n in range(0, 40):
    assert cheapest_rolls(n, packs) == cheapest_brute(n, packs), n
print("DP agrees with exhaustive search for n = 0..39")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
ExplanationH

Communicating while you code

The interviewer cannot see inside your head, and silence looks the same whether you are thinking brilliantly or stuck. Some habits make your thinking visible without turning it into a performance:

  • Narrate decisions, not keystrokes. "I'll keep a dictionary of count differences, so each new entry costs constant time" is useful; reading out each line as you type it is not.
  • State complexity as you choose. "This is O(nlog⁡n)O(n \log n) because of the sort; the loop is linear."
  • Write readable code. Good names, a helper function for the feasibility check, no clever one-liners you have to explain twice.
  • When stuck, say what you are trying. "I'm looking for a monotonic property — if radius 5 works, does 6?" gives the interviewer something to respond to, and hints are a normal part of the conversation.
  • Treat the interviewer as a colleague. Check assumptions with them, and take suggestions seriously rather than defending your first idea.
  • Test before you say "done". Trace a small example through the code line by line; check the empty input and the boundary cases. Finding your own bug is a good signal, not a bad one.

Behavioural interviews reward the same honesty. Prepare a handful of real stories — a hard bug, a disagreement, a mistake and what you changed afterwards, something you led — and tell each with its situation, your actions and the result, including what you would do differently. Do not invent or embellish; interviewers ask follow-up questions, and specific, true stories are both more convincing and easier to tell.

For system design, use the method in System design: requirements and estimates first, a simple design next, deep dives on the hardest parts, and trade-offs stated plainly.

ExplanationH

Honest advice, and keeping it in proportion

Some things are worth saying plainly.

  • Nothing guarantees an offer. Not a number of practice problems, not a course, not this lesson. Hiring depends on the role, the team's needs, the interviewers and the day. Rejections are common for excellent engineers, and many people who now work at the companies above were turned down before.
  • Practise solving, not memorising. Interviewers vary problems precisely to defeat memorisation. Twenty problems understood deeply — why the pattern applies, what breaks it, how to test it — are worth more than two hundred skimmed.
  • Practise out loud and under time. Solve on a plain editor without autocomplete, explain as you go, and occasionally practise with a friend playing interviewer.
  • Keep it in proportion. Weeks of interview drills do not replace building real things. Projects, open-source contributions and the material of this course make you better at the job and give you true stories to tell. Spend most of your time on skill, some on interview form.
  • Look after yourself. Sleep before an interview matters more than one more problem. A rejection says something about one sample on one day; it is not a measure of your worth.

Misconception

"Interviews only test whether you get the optimal answer." Interviewers look at the whole process: clarifying, a correct baseline, reasoning towards better complexity, clean code and testing. A well-communicated good solution often beats a silently produced optimal one.

Misconception

"If I recognise the problem, I should jump straight to the trick." Skipping clarification is how candidates solve a different problem from the one asked. Recognition speeds up the method; it does not replace it.

Optional Christian reflection · Worth that does not depend on the result

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

Interviews can make it feel as if your value is being weighed in an hour. It is not. A hiring decision measures fit for a role from a small sample; it cannot measure a person. Christians speak of a worth that is given rather than earned, and whatever your own convictions, it is a sound footing for walking into an interview room: prepare diligently, do your honest best, and leave the outcome where it belongs.

Exercises

Exercises

1. Technical interviews

Warm-upHuman

An interviewer says: "Given a list of temperatures, find the longest run of days that stays within some range." What is the best first thing to do?

Choose one

2. Technical interviews

Warm-upComputational

Dialect survey. Field linguists record observations as (word, region) pairs, with many repeats. Write widespread(observations, k) returning the sorted list of words observed in at least k distinct regions.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

3. Technical interviews

CoreComputational

Water rationing. Villages have daily water demands demands (non-negative integers), and the reservoir can supply supply units today. With a per-village cap cc, village ii receives min⁡(di,c)\min(d_i, c). Write largest_cap(demands, supply) returning the largest integer cc with 0≤c≤max⁡(d)0 \le c \le \max(d) such that the total delivered is at most supply. (If even c=max⁡(d)c = \max(d) fits, return max⁡(d)\max(d); assume demands is non-empty.)

Use binary search on cc.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

4. Technical interviews

CoreComputational

The leaper. On an n×nn \times n board, a "leaper" piece moves like a stretched knight: 1 square in one direction and 3 in the perpendicular direction (8 possible moves). Some squares are blocked. Write leaper_moves(n, blocked, start, target) returning the fewest moves from start to target (both (row, col) tuples), or −1 if impossible. blocked is a set of squares the leaper may not land on (it jumps over anything).

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

5. Technical interviews

CoreComputational

Ovens. A bakery has m ovens, all free at time 0. Loaves must be started in the given order; each loaf goes into whichever oven becomes free earliest (ties: lowest oven index), starting as soon as that oven is free. Write bake(times, m) returning (finish, ovens): the time when the last loaf finishes, and the list of oven indices used for each loaf.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

6. Technical interviews

StretchComputational

Melody distance. Melodies are lists of pitches (integers, as in MIDI note numbers). To turn melody a into melody b you may delete a note or insert a note at cost gap each, or change a note of pitch xx into pitch yy at cost ∣x−y∣|x - y| (zero if they are equal). Write melody_distance(a, b, gap) returning the minimum total cost.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

7. Technical interviews

Warm-upHuman

Fifteen minutes into a coding interview you have a correct O(n2)O(n^2) solution, the interviewer has asked whether you can do better, and you do not yet see how. What is the most useful thing to do?

Choose one

Further reading and resources