Column-Normalize a Random Binary Matrix
Arrays & HashingModel answerLast updated
Generate an n×n matrix of fair coin-flip entries and rescale each column so its values sum to 1, in O(n²) time.
Column-Normalize a Random Binary Matrix
Background
A common preprocessing step in data pipelines is normalizing feature columns so they form valid probability distributions — each entry non-negative and the column summing to exactly 1.
Task
Write a function that does the following:
- Builds a 100×100 matrix where every entry is drawn independently from a Bernoulli(0.5) distribution — each cell is 0 or 1 with equal probability.
- Rescales each column in place so that its entries sum to 1. That is, every entry in column
jis divided by the total of that column.
Requirements
- The overall algorithm must run in O(n²) time, where
n = 100. - Your solution should handle any degenerate columns gracefully. A column of all zeros cannot sum to 1 — define a clear policy for it and explain your choice.
- You may use any language. A NumPy-based Python solution is encouraged; a pure Python version is also acceptable.
What the interviewer is looking for
- Correct use of vectorized operations (axis selection, broadcasting,
keepdims). - Precise complexity analysis — both time and space.
- Proactive identification of the zero-column edge case and an explicit handling policy.
- A short verification step that confirms the result is correct.
Hints
Hint 1
To sum along columns rather than rows, you need to reduce across the row axis. In NumPy that means axis=0. Getting this backwards is the single most common bug — it normalizes rows instead of columns. A quick sanity check is to assert that B.sum(axis=0) is all ones after the operation.
Hint 2
After computing column sums as a length-n vector, you need to divide every row entry by the corresponding column total. If you reshape the sums to (1, n), NumPy will broadcast the division across all rows automatically — no loop required.
Hint 3
A column is all zeros when every one of its n entries independently came up 0. For n=100 that probability is 0.5^100, which is essentially impossible in practice — but a robust implementation handles it anyway. Two clean policies: leave the column as zeros (document that it is non-normalizable), or fill it with 1/n (the uniform distribution over n outcomes). Pick one and be ready to defend it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Column normalization is a two-step reduction-then-broadcast pattern:
- Reduce — sum each column into a length-n vector
swheres[j] = Σ_i A[i,j]. - Broadcast-divide — compute
B[i,j] = A[i,j] / s[j]for every entry.
Both steps touch every one of the n² entries exactly once, so the algorithm is O(n²) time. That is also the lower bound, since just writing the output requires n² writes.
Correctness check
For any column j with s[j] > 0:
Σ_i B[i,j] = Σ_i (A[i,j] / s[j]) = s[j] / s[j] = 1
Every entry is non-negative (it was 0 or a positive fraction), so each column is a valid probability distribution. Within a column, all the 1s are equally weighted at 1/s[j], and all the 0s stay 0.
The zero-column edge case
A column of all zeros appears with probability 0.5^100 ≈ 7.9 × 10⁻³¹. It essentially never happens for n=100, but it does occur at small n and the code needs a policy either way. Two defensible choices:
- Leave as zeros. Honest: the column has no information to distribute. Document that it cannot sum to 1.
- Replace with 1/n. Treats the column as a uniform distribution — the maximum-entropy fallback when you have no data. This is the right call if downstream code requires every column to sum to 1.
The solution below makes this a parameter. What matters in an interview is that you raise the case yourself and commit to a policy.
NumPy implementation
import numpy as np
def normalized_binomial_matrix(
n: int = 100,
p: float = 0.5,
seed: int | None = None,
zero_col: str = "uniform",
) -> np.ndarray:
"""
Build an n x n matrix of Bernoulli(p) entries and normalize each column
to sum to 1.
Parameters
----------
n : matrix side length
p : success probability for each cell
seed : RNG seed for reproducibility
zero_col : "uniform" → fill an all-zero column with 1/n
"zeros" → leave it as zeros (non-normalizable, document it)
Complexity: O(n²) time, O(n²) space (O(n) extra beyond the matrix itself).
"""
if n < 0:
raise ValueError("n must be non-negative")
if zero_col not in ("uniform", "zeros"):
raise ValueError("zero_col must be 'uniform' or 'zeros'")
rng = np.random.default_rng(seed)
# Each entry is Bernoulli(p); cast immediately to float to allow in-place division.
A = rng.binomial(1, p, size=(n, n)).astype(np.float64) # O(n²)
# keepdims=True preserves shape (1, n) so the division broadcasts correctly.
sums = A.sum(axis=0, keepdims=True) # O(n²), shape (1, n)
nonzero = sums != 0
# Divide in-place only where the column sum is positive; zeros stay zero.
np.divide(A, sums, out=A, where=nonzero) # O(n²), in-place
# Apply the chosen zero-column policy.
if zero_col == "uniform" and n > 0:
A[:, ~nonzero[0]] = 1.0 / n
return A
Pure Python version (no dependencies)
import random
def normalized_binomial_matrix_pure(
n: int = 100,
p: float = 0.5,
seed: int | None = None,
) -> list[list[float]]:
"""Same O(n²) complexity, slower due to Python interpreter overhead."""
rnd = random.Random(seed)
A = [[1.0 if rnd.random() < p else 0.0 for _ in range(n)] for _ in range(n)]
for j in range(n):
s = sum(A[i][j] for i in range(n))
for i in range(n):
A[i][j] = A[i][j] / s if s else 1.0 / n
return A
Complexity summary
| NumPy | Pure Python | |
|---|---|---|
| Time | O(n²), ~3n² operations in C | O(n²), ~3n² operations in CPython |
| Extra space | O(n) for the sums vector | O(n) for per-column accumulator |
| Practical speed | ~50–100× faster (SIMD, no interpreter overhead) | Baseline |
Both are O(n²) asymptotically. The difference is constant-factor overhead, not big-O class.
Common mistakes to avoid
- Wrong axis.
axis=1sums across columns and normalizes rows. Always verify withassert np.allclose(B.sum(axis=0), 1.0). - Skipping
keepdims. Without it,sumshas shape(n,)instead of(1, n). NumPy may still broadcast correctly in this specific case, but it is fragile and hard to reason about — usekeepdims=Trueexplicitly. - Integer dtype.
rng.binomialreturns integers. Dividing an int array truncates to zero. Cast to float before dividing. - Silent NaNs. A plain
A / sumsproducesNaNon zero-sum columns without warning. Usenp.divide(..., where=nonzero)or fill the zeros first. - Floating-point equality. Column sums will be 1.0 only up to rounding. Test with
np.allclose, not==.
How to frame this in an interview
Lead with the two-step plan (reduce, then broadcast-divide), name the complexity upfront, bring up the zero-column case before the interviewer asks, and finish by running the one-line assertion. That last step signals that you verify results rather than assume correctness.