Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 5/ 160
01. Python & Data Wrangling

Broadcasting & Linear Algebra Ops

Master NumPy broadcasting rules plus dot products, norms, and matrix ops used in ML math.

IntermediateBroadcasting · Dot Product3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

NumPy can combine a small array with a big one by repeating the small one as needed, as long as the shapes line up from the right.

Think of it like…

Stretching a single row of a table downwards like a sticker that repeats on every line, without printing copies: the program behaves as if the row were repeated, but memory isn't duplicated. If rows and columns don't line up, the sticker can't be stretched and you get an error.

Where you’ve seen it

To standardise a (10000, 5) feature matrix X, the code (X - X.mean(axis=0)) / X.std(axis=0) subtracts a (5,) mean vector from every row and divides by a (5,) std vector: no loops, no copies of the vectors. To score a linear model, X @ w + b multiplies (10000, 5) by (5,) to get 10,000 predictions in one call.

Words you’ll hear

Broadcasting rule
Align shapes from the right; dimensions must be equal or 1.
np.newaxis / None
Adds a length-1 dimension so shapes can broadcast as intended.
Dot product / matmul
a @ b: sum of products for vectors; row-by-column product for matrices.
Norm
A vector's length: np.linalg.norm(v); ‖v‖₂ is Euclidean.

Visual diagram

Loading interactive diagram

Theory & deep dive

The broadcasting rules, with examples

Write the two shapes one above the other, right-aligned, and pad the shorter one with 1s on the left. Each column of dimensions must be equal or contain a 1; the output takes the larger of the two. (3, 4) with (4,) works (the vector is a row repeated 3 times). (3, 4) with (3,) fails, because 4 ≠ 3, but (3, 4) with (3, 1) works, because the column vector repeats across 4 columns. (3, 1) with (1, 4) gives a full (3, 4) grid, the basis of pairwise-difference tables.

Use x[:, np.newaxis] or x.reshape(-1, 1) to turn a vector into a column and keepdims=True on reductions to preserve dimensions. The trap is accidental outer products: a - b where a has shape (n,) and b has shape (n, 1) returns (n, n), which may be huge and silently wrong. Always check .shape of the result.

Pairwise distances without loops

For points P of shape (n, 2): diff = P[:, None, :] - P[None, :, :] has shape (n, n, 2), and dist = np.sqrt((diff ** 2).sum(axis=-1)) is the (n, n) distance matrix. It uses O(n²) memory, so chunk it for large n.

Key takeaway: Right-align shapes; equal or 1 works; add axes deliberately; check result shapes.

Linear algebra you'll use constantly

a @ b is matrix multiplication: (m, k) @ (k, n) gives (m, n), so inner dimensions must match; a * b is element-wise, a common mix-up. The dot product of two vectors is the sum of their element-wise products, and cosine similarity is that dot product divided by the product of norms. np.linalg.norm(v) computes length, np.linalg.norm(A, axis=1) row norms. A.T transposes.

To solve linear systems use np.linalg.solve(A, b) rather than computing np.linalg.inv(A) @ b, which is slower and less numerically stable; least squares regression is np.linalg.lstsq(X, y, rcond=None). Eigen and singular value decompositions (np.linalg.eigh, np.linalg.svd) underlie PCA and recommender models. Watch dtypes and conditioning: nearly collinear features make matrices close to singular and results unstable.

Linear regression by least squares

X1 = np.column_stack([np.ones(len(X)), X]); coef, *_ = np.linalg.lstsq(X1, y, rcond=None) returns the intercept and slopes minimising squared error; predictions are X1 @ coef.

Key takeaway: @ for matrix products, solve and lstsq instead of inv, SVD/eigh for decompositions.

How it works, step by step

Step 1 of 4
Plan

1. Write down both shapes

Right-align the shapes and check each dimension pair is equal or 1.

(10000, 5) with (5,) ✓
Key numbers at this step
Mismatch
raises ValueError

When to use it & trade-offs

What it is

Broadcasting is NumPy's rule for combining arrays of different shapes without copying data: compare shapes from the right, and two dimensions are compatible if they are equal or one of them is 1 (a missing dimension counts as 1). A (1000, 3) matrix minus a (3,) vector subtracts the vector from every row. Linear algebra operations such as the dot product (a @ b), norms (np.linalg.norm) and matrix inverse or solve are the core arithmetic behind regression, PCA and neural networks.

Why it matters: Standardising columns, computing distances, scoring a model and many loss functions are one-liners with broadcasting and matrix products. Misunderstanding the rules produces the most confusing bug in NumPy: a calculation that runs without error but silently broadcasts an (n,) against an (n, 1) into an n × n matrix. Interviews for ML roles often ask you to reason about shapes.

When to reach for it

  • Standardising features by column
  • Distances and similarity matrices
  • Scoring linear models with matrix products

When to avoid or be careful

  • Using np.linalg.inv to solve equations
  • Mixing * and @ without thinking about shapes
  • Building n × n arrays for large n without chunking

Ways to combine arrays of different shapes

Broadcasting
Best for: Applying a vector to every row or column, pairwise tables

Strengths: No loops or copies; concise.

Watch out: Silent shape surprises; big temporaries for outer-style ops.

np.tile / np.repeat
Best for: When an explicit copy is genuinely needed

Strengths: Explicit result array.

Watch out: Uses real memory; rarely necessary.

Python loops
Best for: Rare irregular cases

Strengths: Maximum flexibility.

Watch out: Much slower on large arrays.

Interview signals & numbers to know

When this topic comes up

  • “What shape is the result of this operation?”
  • “Standardise each column without a loop”
  • “Compute pairwise distances”
  • @ vs *
  • Numerical stability

Benchmarks & rules of thumb

right-aligned -
how shapes are compared
(n,) vs (n, 1) -
the classic broadcasting trap
O(n²) -
memory of pairwise distance matrices

Common mistakes & follow-ups

Common interview mistakes

  • Subtracting a (n, 1) column from a (n,) vector and getting an unintended (n, n) matrix.
  • Using * where @ was needed, producing an element-wise result of the wrong shape or meaning.
  • Computing the inverse of an ill-conditioned matrix and trusting the result.

Likely interviewer follow-ups

  • What are the broadcasting rules?
  • How do you compute pairwise distances without loops?
  • Why prefer np.linalg.solve to inv?
Interview tip: When reasoning about shapes aloud, write them one above the other and right-align them. It shows you apply the rule instead of guessing.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Broadcasting & Linear Algebra Ops with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
NumPy Arrays & Vectorization
Next topic
Pandas Series & DataFrames