Coding interview questions

Data structures, live coding and the running commentary that interviewers are actually grading.

Short answer

A coding interview gives you a small problem and watches how you solve it: 30 to 60 minutes, a shared editor or a whiteboard, and an interviewer who scores your reasoning as much as your code. Most questions reduce to a handful of patterns, such as hash map lookups, counting, two pointers, sorting and recursion. The reliable way to pass is to restate the problem, agree on examples, state your approach and its complexity, then write code you test out loud.

Last reviewed October 13, 2026

What a coding round actually scores

Harvard’s career office describes the format plainly: for coding roles, interviews may require live problem solving, either on a whiteboard or using online tools. That setting is the point. The employer already has your resume, so what they are buying with this hour is a look at how you behave when the answer is not known yet.

Four things get a score, usually on a form. Correctness, meaning the code does what the problem asked for the inputs you were given and the ones you thought of yourself. Complexity awareness, meaning you can say roughly how your solution scales and whether the obvious better version exists. Communication, meaning the interviewer could follow your reasoning without interrogating you. And code quality, meaning readable names, small functions and no dead ends left behind.

What is not scored is speed for its own sake, or recalling a textbook algorithm by name. A candidate who reaches a clean working solution with a clear explanation beats one who types a memorised optimal answer and cannot explain the invariant it depends on.

One implication is worth acting on: a working slow solution first, stated as such, is almost always the right opening move. You can then improve it with the interviewer watching, which is exactly the behaviour they want to observe. Silence while you search for the perfect approach is the most expensive habit in this round.

How to think aloud without losing the thread

Use the same opening sequence every time so you never have to invent one under pressure.

Restate the problem in your own words and get agreement. This catches misunderstandings in the cheapest thirty seconds of the interview. Then ask the clarifying questions that change the solution: how large can the input be, can values repeat, are they sorted, can they be negative or empty, is the input in memory, and what should happen on invalid input.

Next, write one small example and one awkward one by hand, and say what the correct output is for each. Interviewers rarely interrupt this, and it gives you test cases for later.

Only then describe your approach in two or three sentences, including the data structure you intend to use and the cost in time and space. If you can see a brute force version and a better one, say both and name the trade-off: for example, a nested loop at quadratic time against a dictionary that spends linear extra memory.

While you code, narrate at the level of intent rather than syntax. “Now I walk the array once, and for each number I check whether its complement is already in the dictionary” is useful. Reading your own code aloud character by character is not.

Finish by running your examples through the finished function out loud, including the awkward one, and fixing what breaks. Candidates who test unprompted stand out, because production code is mostly the part after it works once.

The patterns behind most questions

Interview problems repeat a small number of shapes. Learning the shapes is far more efficient than grinding hundreds of unrelated puzzles.

The first is the lookup table. Any question that asks whether a complement, a duplicate or a seen value exists is a dictionary or a set in disguise, trading memory for a constant time check.

def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i
    return []

two_sum([2, 7, 11, 15], 9)  # [0, 1]
two_sum([3, 2, 4], 6)       # [1, 2]

One pass, one dictionary, and the index is stored rather than the value, which is the detail an interviewer will ask about. Note also what the function does when nothing matches: deciding that behaviour out loud is part of the answer.

The second shape is counting. Frequencies answer anagrams, first unique characters, majority elements and most “can this be rearranged into” questions.

from collections import Counter

def first_unique(s):
    counts = Counter(s)
    for ch in s:
        if counts[ch] == 1:
            return ch
    return None

first_unique('swiss')  # 'w'
first_unique('aabb')   # None

Two passes, linear time, and it relies on iterating the original string rather than the counter so the first occurrence wins.

The remaining shapes are worth practising once each: two pointers for sorted arrays and palindromes, a sliding window for subarrays and substrings, a stack for brackets and nesting, breadth-first and depth-first traversal for trees and grids, binary search for anything sorted or monotonic, and recursion with memoisation for overlapping subproblems. Grouping by sorted letters covers the entire anagram family, because two words are anagrams exactly when their sorted characters match.

For each pattern, be able to state the time and space cost without thinking. That single sentence is often the difference between a hire and a lean hire.

Sorting questions and the details interviewers probe

Sorting rarely appears as “implement quicksort” any more. It appears as a sub-step, and the follow-up questions are about the guarantees your language gives you.

Python’s sorting guide is explicit about two of them. Sorts are guaranteed to be stable, which it defines as meaning that when multiple records have the same key, their original order is preserved. And the key parameter takes a callable applied to each element before comparisons, which the documentation notes is fast because the key function is called exactly once for each input record.

Stability is what makes multi-key sorting work without writing a comparator. The documentation describes the technique: to sort by descending grade and then ascending age, do the age sort first and then sort again by grade. It also states that the reverse parameter still maintains sort stability.

people = [('Dana', 3), ('Ash', 1), ('Bo', 3), ('Cy', 1)]
by_name = sorted(people, key=lambda p: p[0])
final = sorted(by_name, key=lambda p: p[1], reverse=True)
# [('Bo', 3), ('Dana', 3), ('Ash', 1), ('Cy', 1)]

The scores come out descending, and inside each score the names stay in the alphabetical order of the first pass. Explaining why is a good answer to “how would you sort by score then by name”.

Two more details come up often. The guide points out that list.sort() modifies the list in place and returns None, while sorted() builds a new list and accepts any iterable, so a candidate who writes x = y.sort() has handed the interviewer a question. And a key function need not depend only on the element: the documentation shows sorting names by looking their grades up in a separate dictionary, which is a tidy way to answer “sort these by a ranking I give you”.

SQL coding questions

Many engineering and data loops include a SQL exercise, and it is usually one of three things: a join with a filter, an aggregation with grouping, or a ranking inside groups. The third is where candidates fall over, and window functions are the tool for it.

The PostgreSQL documentation defines a window function as one that performs a calculation across a set of table rows somehow related to the current row, and notes the difference from a plain aggregate: the rows retain their separate identities instead of being grouped into one output row. The OVER clause determines how the rows are split for processing, and PARTITION BY inside it divides rows into groups sharing the same values.

The detail that catches people out is also documented: window functions are permitted only in the SELECT list and the ORDER BY clause, and are forbidden in GROUP BY, HAVING and WHERE clauses, because they logically execute after those clauses are processed. The documented workaround is a sub-select, which is exactly how you answer “give me the two highest paid employees per department”.

SELECT depname, empno, salary
FROM (
  SELECT depname, empno, salary,
         row_number() OVER (PARTITION BY depname ORDER BY salary DESC, empno) AS pos
  FROM empsalary
) AS ss
WHERE pos < 3;

When you present a query like this, say why the tiebreaker column is in the ORDER BY: without empno, two employees on the same salary would get an arbitrary order, and an interviewer will ask. Be ready as well for the follow-up on row_number against rank and dense_rank, and for the reminder that rows removed by the query’s WHERE clause are never seen by the window function at all.

JavaScript coding questions

Front-end and full-stack loops often run the coding round in JavaScript, where the classic trap is the default sort order. MDN states it directly: the default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code unit values. The documentation’s own example is worth memorising.

[1, 30, 4, 21].sort();              // [1, 21, 30, 4]
[1, 30, 4, 21].sort((a, b) => a - b); // [1, 4, 21, 30]

MDN also gives the comparator contract: a negative value means a comes before b, a positive value means a comes after b, and zero or NaN means they are considered equal. It offers the mnemonic that (a, b) => a - b sorts numbers ascending, and it warns that your comparator must be consistent, because inconsistent comparators produce different results in different engines.

Two further facts answer common follow-ups. Sort mutates: MDN describes sort() as sorting in place and returning a reference to the same array, so mutating the returned array mutates the original, with toSorted() or a copy as the non-mutating alternative. And stability is guaranteed now but was not always: since version 10, corresponding to ECMAScript 2019, the specification dictates that Array.prototype.sort is stable, and before that stability was not guaranteed.

Beyond sorting, JavaScript rounds reuse a predictable set: debounce and throttle, deep clone, flatten a nested array, group objects by a key, a small event emitter, and promise sequencing with async and await. Expect at least one question on asynchrony, because that is where candidates reveal whether they understand the event loop.

How to practise, and what to do when you are stuck

Volume is the wrong target. Working through two problems a day thoroughly beats twenty skimmed, because what you are training is a procedure, not a memory.

Make each session resemble the real thing. Set a timer of 30 minutes, write code in a plain editor without autocomplete, and talk out loud even when alone. Record yourself occasionally; the gap between what you think you explained and what you actually said is instructive.

Afterwards, review deliberately. Write down the pattern the problem belonged to, the mistake you made, and the one sentence that would have saved you. Revisit it a week later from scratch rather than rereading the solution, which is the step that makes a pattern stick.

If your time is short, take breadth over depth: one problem from each major pattern, plus the language and SQL details above, carries you further than twenty variations of the same tree traversal.

In the interview, when you are genuinely stuck, do three things in order. Say which part is blocking you. Work one of your examples through by hand, because concrete inputs break abstraction loops. Then propose the brute force solution as a starting point and ask whether the interviewer would rather you optimise or implement it. That is not surrender; it is a collaborating engineer, which is what the round was designed to find.

Finally, say what you would add with more time: more tests, input validation, a clearer name, the faster version you did not get to. Interviewers hear the difference between a candidate who ran out of time and one who did not know what was missing.

Practice it now

Answer out loud, as if the interviewer just asked. Then check yourself against the list.

“Given a list of integers and a target, return the indexes of the two numbers that add up to the target. Narrate your approach and its complexity before you write any code.”

Aim for 25 minutes
  • You restated the problem and asked whether values repeat or can be negative.
  • You wrote one small example and one awkward one before coding.
  • You stated the time and space cost of your approach.
  • You said what the function returns when no pair matches.
  • You ran both examples through the finished code out loud.
  • You named one thing you would improve with more time.

Frequently asked questions

How long is a coding interview?

Usually 30 to 60 minutes per round, with one problem and sometimes a short follow-up variation. Onsite loops often include two such rounds with different interviewers.

Which language should I use in a coding round?

The one you write fastest without reference, unless the posting requires a specific language. Python and JavaScript are common because they are compact, but a confident Java or C# solution scores the same.

Is it acceptable to give a brute force answer first?

Yes, as long as you label it. State the simple solution and its cost, then improve it. That sequence shows the reasoning interviewers are scoring, and it protects you from having nothing written down.

What do I do if I cannot solve the problem?

Say which part is blocking you, work a concrete example by hand, and ask whether to implement the simpler solution. Partial credit is real, and interviewers record how you use a hint.

How much SQL do I need for a software engineering coding round?

Joins, grouping and filtering, plus ranking within groups using window functions and a sub-select to filter on the result. Those cover most exercises outside specialist data roles.

Sources

  1. Python documentation: Sorting Techniques (HOW TO)
  2. PostgreSQL documentation: Window Functions
  3. MDN Web Docs: Array.prototype.sort()
  4. Harvard FAS Mignone Center for Career Success: Interviewing