One-Hot Encode Integer Labels via Equality Broadcasting in NumPy
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `one_hot(labels, num_classes)` that turns a 1-D integer label array into an integer one-hot matrix of shape `(len(labels), num_classes)`. Row `i` has a 1 in column `labels[i]` and 0 elsewhere.
Requirements:
- Compute via broadcast equality `labels[:, None] == np.arange(num_classes)`, cast to int.
- No Python loops and no scatter/fancy-index assignment.
Example:
```python
labels = np.array([2, 0, 1])
num_classes = 3
# Output:
# [[0, 0, 1],
# [1, 0, 0],
# [0, 1, 0]]
```
```hint Read one cell
Work out the shapes of the two operands, then ask what a single entry `[i, j]` of the comparison is testing.
```
### Constraints & Assumptions
- All `labels` values are in `[0, num_classes)`.
- `num_classes >= 1`.
### What a Strong Answer Covers
- The shapes of `labels[:, None]`, `np.arange(num_classes)` and the broadcast result.
- Why entry `[i, j]` of the comparison is exactly the one-hot entry.
- The cast from boolean to integer and the choice of output dtype.
- Time and memory cost, and the behavior on empty input and on labels outside the range.
### Follow-up Questions
- How would you handle an empty `labels` array?
- How would you extend this to multi-dimensional label arrays?
- What does your function return for a label outside `[0, num_classes)`, and how would you catch that?
- How much memory does the output take with many labels and many classes, and how would you cut it?
Overview: Build an integer one-hot matrix from a 1-D NumPy label array with broadcast equality and no loops or index assignment. It tests broadcasting shapes, casting booleans to integers, memory cost, and edge cases such as empty input and out-of-range labels.