Normalize each row of a 2-D NumPy array to sum to 1 using keepdims broadcasting
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Given a 2-D NumPy array `a` of shape `(m, n)`, write `normalize_rows_to_unit_sum(a)` that returns a new array where each entry is divided by its row's sum, so each row sums to 1 (L1 row normalization).
Requirements:
- Return a float array of the same shape as the input.
- Each output row sums to 1 (for rows with a nonzero sum).
- Compute row sums with `axis=1` and `keepdims=True` (shape `(m, 1)`) so they broadcast without a manual reshape.
- Do not mutate the input array.
```python
a = np.array([[1., 1., 2.],
[0., 5., 5.]])
normalize_rows_to_unit_sum(a)
# array([[0.25, 0.25, 0.5 ],
# [0. , 0.5 , 0.5 ]])
```
```hint Line up the shapes
Write down the shape of `a` and the shape of the row sums, then align them from the rightmost axis the way broadcasting does. Ask what would happen if the sums had shape `(m,)` instead.
```
### Constraints & Assumptions
- Input is a 2-D array of numeric dtype.
- All-zero rows (division by zero) are out of scope.
### What a Strong Answer Covers
- Row sums computed with `axis=1` and `keepdims=True`, and a division that scales each row by its own sum
- Why the `(m, 1)` shape is needed, and what goes wrong with an `(m,)` vector on square and non-square input
- A float result of the same shape, with the input left unmodified
- How a plain row sum differs from the L1 norm when rows contain negative entries
### Follow-up Questions
- How would you handle a row whose sum is 0?
- Why is `keepdims=True` needed here?
- If rows can contain negative values, how does dividing by the row sum differ from dividing by the L1 norm?
- How would you normalize columns instead of rows?
Overview: Normalize every row of a 2-D NumPy array so that it sums to 1, returning a new float array without changing the input. It tests reductions with axis and keepdims, the broadcasting rules for row and column shapes, and how to treat zero-sum rows and negative values.