KatInterview

Column-Normalize a Random Binary Matrix

Arrays & HashingModel answer
MediumModel answerArrays & Hashingnumpymatrixnormalization

Last 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:

  1. 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.
  2. Rescales each column in place so that its entries sum to 1. That is, every entry in column j is 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.