NumPy Coding Interview Checklist: Arrays, Broadcasting, and Clean Answers
NumPy questions show up in data science, machine learning engineering, quant, and research engineering interviews. Sometimes the whole round is NumPy; sometimes it's one part of a broader Python round, like "now vectorize your loop." Either way, interviewers are usually checking two things: that you think in arrays instead of loops, and that you avoid the subtle shape bugs that break real code.
This NumPy coding interview checklist covers what to review and how to talk through your answers.
1. Array basics you should write without thinking
- Creating arrays:
np.array,np.zeros,np.ones,np.arange,np.linspace,np.full. - Inspecting:
.shape,.ndim,.dtype,.size. - Reshaping:
reshape,ravel,flatten,transpose,np.newaxisorNonefor new dimensions. - Combining:
np.concatenate,np.stack,np.vstack,np.hstack.
Know the difference between ravel (often returns a view) and flatten (always a copy). It's a common quick question.
2. Indexing and slicing
- Basic slicing like
a[1:5],a[:, 0], anda[::-1]. - Boolean masks:
a[a > 0]and combining conditions with&and|, with parentheses around each condition. - Fancy indexing with integer arrays:
a[[0, 2, 4]]. np.where(cond, x, y)for element-wise choices.
Remember that basic slices return views, while boolean and fancy indexing return copies. Modifying a slice can change the original array, which surprises people in interviews and in production.
3. Broadcasting
Broadcasting is the topic most likely to separate candidates. The rule: compare shapes from the right; dimensions are compatible if they're equal or one of them is 1.
Practice examples:
- Subtracting the column means:
X - X.mean(axis=0). - Normalizing each row:
X / X.sum(axis=1, keepdims=True). - Pairwise distances:
np.sqrt(((A[:, None, :] - B[None, :, :]) ** 2).sum(axis=-1)).
Say the shapes out loud as you go: "A is (n, d), B is (m, d), so after adding axes I get (n, 1, d) and (1, m, d), which broadcast to (n, m, d)." That narration shows real understanding.
4. The axis argument
Many bugs come from the wrong axis. Lock in this mental model: the axis you pass is the one that disappears. X.sum(axis=0) on an (n, d) array returns shape (d,), one value per column.
Use keepdims=True when you plan to broadcast the result back against the original.
5. Vectorization over loops
A classic prompt: "Here's a Python loop. Make it faster." Approach it in steps:
- Say what the loop computes in plain words.
- Identify which operations are element-wise and which are reductions.
- Rewrite with array operations, then check the shapes.
- Mention memory: vectorized code can create large intermediate arrays, like the (n, m, d) distance tensor above.
If the interviewer asks about trade-offs, mention that very large intermediates may call for chunking.
6. Useful functions to know
- Reductions:
sum,mean,std,min,max,argmin,argmax,cumsum. - Sorting and selection:
np.sort,np.argsort,np.argpartitionfor top-k without a full sort. - Uniques and counts:
np.unique(a, return_counts=True),np.bincount. - Linear algebra:
@for matrix multiply,np.linalg.norm,np.dot. - Random:
np.random.default_rng(seed)for reproducible results.
np.argpartition is a nice touch in top-k questions: it runs in linear time on average instead of a full sort.
7. Common pitfalls
- Integer division and dtypes: integer arrays can overflow silently with large values. Check
dtype. - NaN handling:
np.nan == np.nanis False. Usenp.isnan, and knownp.nanmean. - Float comparison: use
np.iscloseornp.allcloseinstead of==. - Shape (n,) vs (n, 1): these broadcast very differently. Reshape on purpose.
- Chained conditions:
a > 0 and a < 5fails on arrays; use(a > 0) & (a < 5).
8. How to talk through a NumPy answer
- Restate the input and output shapes.
- Describe the approach in terms of array operations.
- Write the code in small steps, checking shapes as you go.
- Test on a tiny example you can compute by hand, such as a 2×3 array.
- Mention complexity and memory, especially intermediate array sizes.
A quick practice set
- Normalize each row of a matrix to sum to 1.
- Find the index of the nearest centroid for each point.
- Compute a moving average with
np.convolveor cumulative sums. - Replace values below a threshold with the column median.
- Return the top-3 values per row.
Do each with a timer, out loud, and check your shapes before running anything.
Views, copies, and memory
Interviewers sometimes follow up with "what happens to memory here?" Have a short answer ready. Slicing creates a view that shares data with the original, so it's cheap but changes propagate. Use .copy() when you need independence. In-place operations such as a += 1 avoid allocating a new array, while a = a + 1 creates one. For very large arrays, mention chunked processing or memory-mapped files with np.memmap.
Practice under real conditions
NumPy questions are easy at your desk and harder with an interviewer watching and a clock running. Rehearse with a timer and narration so shape reasoning becomes automatic.
Luna Interview is a practice and calm-under-pressure companion for that kind of preparation, with timed sessions and structured hints in your browser. Try Luna Interview at https://lunainterview.xyz/.
Rehearse with an AI interview copilot, then browse commonly reported interview questions.