Outer Sum Table with NumPy Broadcasting
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `outer_sum(a, b)` taking 1-D arrays `a` (shape `n`) and `b` (shape `m`), returning the `(n, m)` array whose `(i, j)` entry is `a[i] + b[j]`.
Requirements:
- Compute `a[:, np.newaxis] + b` in a single vectorized expression.
- No explicit `for` loops or list comprehensions.
For example:
```python
a = np.array([1, 2, 3])
b = np.array([10, 20])
outer_sum(a, b)
# array([[11, 21],
# [12, 22],
# [13, 23]])
```
```hint How shapes line up
Work out the shape of each operand before adding. NumPy compares shapes starting from the last axis, and a missing leading axis counts as length 1.
```
### What a Strong Answer Covers
- A single broadcast expression that returns shape `(n, m)`, checked against the example.
- The broadcasting rule that makes it work: which axes are compared and when a size-1 axis stretches.
- The shape of each operand after adding the new axis, and why the order of operands and axes matters.
- Time and memory cost, plus edge cases such as empty inputs and arrays that are not 1D.
### Follow-up Questions
- What shape does `a + b[:, np.newaxis]` return, and how does it relate to the requested table?
- What happens if you write `a + b` with no new axis, both when n differs from m and when they are equal?
- How would you extend the same idea to a table of pairwise Euclidean distances between two sets of points of shape `(n, d)` and `(m, d)`?
Overview: Write a vectorized NumPy function that builds the table of all pairwise sums a[i] + b[j] for two 1D arrays. It tests the broadcasting rules, turning a vector into a column with a new axis, and avoiding Python loops.