Data structures & algorithms, section 4 of 4, 6h

Solving one under interview conditions

By the end: You can work through a problem out loud, at speed, without freezing.

  • The sequence that works
  • Complexity, stated without being asked
  • Testing your own solution
  • What to do when you are stuck

New to data structures & algorithms? Data structures are the standard ways of arranging data in memory, such as a list, a lookup table or a tree, and each makes some operations cheap and others expensive. Algorithms are the standard recipes for working through them. Big-O notation is the shorthand for how the cost grows as the data grows: a method that is fine on a hundred records can be unusable on a million, and this notation tells you which one you have before you find out in production. Why it matters

Knowing the patterns and producing a solution in front of a stranger in thirty-five minutes are separate skills, and only the second one is examined. This is the part no amount of solved problems teaches you, because solving alone trains the wrong half: alone you may stare silently for ten minutes and still get the tick, and in the room that same ten minutes is a fail. What follows is a sequence to run every time, then a full worked transcript of it, then the specific ways strong candidates lose.

A repeatable sequence#

  1. 1.Restate the problem in your own words and confirm you have it right.
  2. 2.Ask about input size, edge cases and invalid input.
  3. 3.Give the brute force out loud with its complexity. This buys you a working answer and time to think.
  4. 4.Say what is wasteful about it and what structure would remove that waste.
  5. 5.State the approach and its complexity before writing any code.
  6. 6.Write it, narrating as you go.
  7. 7.Walk through a small example by hand.
  8. 8.Name the edge cases and check the code handles them.

Never start by coding

Candidates who begin typing immediately lose marks even when they arrive at the right answer, because the interviewer cannot see any reasoning. Steps three to five take two minutes and are what is being assessed.

The sequence in a real thirty-five minutes#

Read this once as a script and once as a clock. The times on the left are what a good pace looks like; the lines in brackets are what the interviewer is writing down. The problem is deliberately ordinary — most of them are.

00:00  INTERVIEWER  Given a list of integers and a target, return the
                    indices of the two numbers that add to the target.

00:20  YOU   So: one list, one target, and I return two positions —
             not the values themselves. Is there always exactly one
             answer, or do I need to handle none and handle several?
             [asks before assuming — first thing on the rubric]

00:35  INT   Assume exactly one.

00:40  YOU   And how big does the list get? Are the numbers bounded,
             can they be negative, can the same element be used twice?

00:55  INT   Up to a million. Negatives are fine. Each element once.

01:05  YOU   Then a million rules out anything quadratic — that's 10^12
             operations. Let me still say the brute force so we agree
             on correctness: two nested loops, check every pair, O(n²)
             time and O(1) space. It's right, it's just too slow here.
             [brute force stated as a baseline, not offered as the answer]

01:30  INT   Agreed. What's better?

01:35  YOU   The waste is that for each element I rescan the whole list
             looking for target minus that element. That's a lookup, so
             it should be a hash map. One pass: for each number, check
             whether its complement has already been seen; if so I have
             my pair, and if not I record where this number is. O(n)
             time, O(n) space — I'm trading memory for the rescan.

02:10  INT   Go ahead.

02:15  YOU   [writes, narrating] I'll keep a dict from value to index.
             Checking the complement before inserting the current value
             is what stops it pairing an element with itself...
Two and a quarter minutes of talking before a line of code. That is the correct ratio.
def two_sum(nums, target):
    seen = {}                            # value -> index
    for i, n in enumerate(nums):
        if target - n in seen:           # check BEFORE inserting
            return [seen[target - n], i]
        seen[n] = i
    return []
04:30  YOU   Let me run it. nums = [2, 7, 11, 15], target = 9.
             i=0, n=2: is 7 in seen? No, seen is empty. Store 2 -> 0.
             i=1, n=7: is 2 in seen? Yes, at 0. Return [0, 1]. Correct.

             Edge cases: [3, 3] with target 6 — i=0 stores 3 -> 0,
             i=1 finds 3 in seen and returns [0, 1], so duplicates work
             because I check before I insert. Empty list returns [].
             Negatives are fine, the arithmetic doesn't care.
             [tests unprompted — the candidate most interviewers remember]

05:10  INT   Good. Now suppose the list doesn't fit in memory.

05:15  YOU   Then I can't hold the map...
The follow-up is where the interview actually happens. Finishing fast buys you more of it, not an early exit.

The clock is not the score

Reaching a working solution at minute five and handling two follow-ups well beats reaching it at minute thirty in silence, and it also beats reaching it at minute five and then sitting quietly. The signal being measured is how you think when the ground moves, which is why almost every loop ends with a change to the requirements. Expect it and stay engaged rather than treating the first working answer as the finish line.

The questions worth asking#

Clarifying questions are scored, but only the ones that could change your solution. Asking four of these costs forty seconds and repeatedly saves candidates from building the wrong thing.

Question                          What it changes
How large is the input?           whether O(n log n) is acceptable at all
Sorted already?                   unlocks two pointers or binary search
Duplicates allowed?               set vs counter; changes the answer's shape
Negatives? zero? empty?           breaks prefix-sum and sliding-window tricks
One answer or all of them?        return-early vs collect
Can I mutate the input?           in-place saves the O(n) space
Streaming or in memory?           heap and sketches instead of a full scan
What should invalid input do?     raise, return empty, or clamp
Ask the two or three that matter for this problem. Reciting all eight reads as a memorised ritual.

Complexity, unprompted#

Give time and space complexity for every approach you mention, without being asked. It is a small thing that consistently reads as competence.

"Brute force is O(n²) time, O(1) space. The repeated work is
scanning for the complement, so a hash map removes it: O(n)
time, O(n) space. I'll do that unless memory is constrained."

Three things are routinely got wrong here, and each is a cheap fix. Recursion costs stack space, so a depth-first traversal is O(h) space even with no data structure allocated. Slicing a list in Python copies it, so a recursion that passes nums[1:] is quietly quadratic. And the complexity you state must be the complexity of what you wrote — say the sort dominates if you sorted, even when the clever part after it is linear.

Test it yourself#

Do not wait to be asked whether it works. Walk a small input through your code aloud, then name the edge cases: empty input, one element, all identical, negative numbers, the maximum size. Walking the example means reading your own variables line by line, out loud, and saying the values — not re-describing the algorithm you intended to write. The gap between the two is where the bug is, and the candidates who find their own bug at minute twenty score better than the ones whose bug the interviewer finds at minute thirty.

Stuck#

Say so, and say what you have ruled out. An interviewer will often give a hint, and taking a hint well is scored positively. Sitting silently is the only genuinely bad option.

"I'm stuck. Brute force is O(n²) and I need better. Sorting
doesn't help because I need the original indices. I think I want
something that remembers what I've seen, so let me try a hash map
keyed on the value."

That is three sentences: where I am, what I eliminated and why, what I will try next. It converts silence into something the interviewer can grade and can help with. If nothing comes, go back to the brute force and make it work — a correct slow solution with an honest account of why it is slow is a passing answer at most companies, and an empty editor is not.

How strong candidates lose#

What happens                        What it reads as     Instead
Silent thinking for 3+ minutes      cannot communicate   narrate the dead ends
Coding before agreeing an approach  does not plan        two minutes of talking
Recognising and reciting a memo     memorised, untested  derive it out loud
Arguing when given a hint           hard to work with    take it, say thanks
Waving at complexity ("fast")       cannot analyse       give both, every time
Saying "done" without testing       ships untested code  walk an example first
Freezing after a requirement change rigid                restate what changed
Hiding a bug you have noticed       not trustworthy      name it, then fix it
Every row is a communication failure, not a knowledge failure. That is the whole point of this section.

Practise the sequence out loud, against a timer, talking to an empty room — it feels absurd and it is the single highest-return hour in this route. Record one session and watch it back. Nearly everyone discovers they go silent for far longer than they believed, and that alone, once fixed, moves the outcome.

Where people go wrong

Optimising before you have anything working. Get the brute force stated, then improve it. Silence while you search for the clever solution is the worst use of interview time.

If this comes up in an interview

How do you approach a problem you have not seen before?

Restate it, clarify input size and edge cases, give the brute force with its complexity, identify the wasteful part, propose the improvement and its complexity, then write it while narrating. The brute force is not a concession, it is a working baseline and thinking time.

What do you do if you cannot solve it?

Say where I am and what I have eliminated, and propose the next thing to try. A working brute force with clear reasoning scores better than silence, and taking a hint well is a positive signal rather than a failure.

How important is finishing?

Less than candidates assume. A clear approach with correct complexity analysis, communicated well, usually scores better than a silently produced solution the interviewer could not follow.

Build this: Solve 20 problems out loud against a 25-minute timer, following the sequence every time. Record two of them and watch for silences and for skipped steps.

This is one section of Data structures & algorithms, 40 hours across 4 sections. Read it in full to get the whole topic in order.

Stop 44 of 50 on the AI Engineer route

0 of 50 topics done · 0h behind you, 603h to go

Next on this routeChoosing a modelMatching capability to the task, and re-checking.10h

What you have marked done is stored in this browser only. It does not reach a server, and clearing site data will clear it.