Outer Product of Two Vectors in NumPy
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `outer_product(u, v)` that returns the outer product of 1D vectors `u` (length m) and `v` (length n): an `(m, n)` matrix where entry `[i, j]` equals `u[i] * v[j]`. Use `np.outer(u, v)` (unlike `np.inner`, which returns a scalar for two 1D vectors).
For example:
```python
u = np.array([1, 2, 3])
v = np.array([4, 5])
outer_product(u, v)
# array([[ 4, 5],
# [ 8, 10],
# [12, 15]])
np.inner(u, np.array([4, 5, 6])) # -> 32 (a scalar)
```
```hint Watch the shapes
Write down the shape of the result before you pick a function. A function that sums over a shared axis gives one number for two 1D inputs, and here you need one output entry for every (i, j) pair.
```
### What a Strong Answer Covers
- The output shape and what each entry holds, checked against the example.
- How the outer product differs from `np.inner` and `np.dot` on 1D inputs.
- The broadcasting equivalent, and why the reshaped operands produce an `(m, n)` result.
- Cost and edge cases: memory for large m and n, empty vectors, and inputs that are not 1D.
### Follow-up Questions
- How does `np.outer` relate to broadcasting, and how would you build an outer sum the same way?
- Given `U` of shape `(B, m)` and `V` of shape `(B, n)`, how would you compute all B outer products in one vectorized call?
- What does `np.outer` do when you pass it 2D arrays, and how does `np.multiply.outer` differ?
- If m and n are both 100,000, what goes wrong, and what would you do instead?
Overview: Write a NumPy function that returns the outer product of two 1D vectors as an m by n matrix of pairwise products. It tests array shapes, the difference between outer and inner products, and how broadcasting builds the same matrix.