Transpose a 2-D NumPy Array
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `transpose_matrix(a)` that takes a 2-D NumPy array of shape `(m, n)` and returns its transpose of shape `(n, m)`.
Requirements:
- Element `a[i, j]` must appear at position `[j, i]` in the result.
- No Python `for` or `while` loop and no comprehension. Use NumPy (for example `.T` or `np.transpose`).
For example:
```python
a = np.array([[1, 2, 3],
[4, 5, 6]])
transpose_matrix(a)
# array([[1, 4],
# [2, 5],
# [3, 6]])
```
```hint Look at the memory
Ask whether the result needs its own copy of the data or whether a new shape and strides over the same buffer are enough. Decide which one your function returns and what that means for a caller who writes to the result.
```
### What a Strong Answer Covers
- A vectorized transpose with `.T` or `np.transpose`, and why it meets the `a[i, j]` to `[j, i]` requirement.
- Whether the result is a view or a copy, and what writing to it does to `a`.
- How the shape and strides change, and what that means for memory layout and contiguity.
- When an explicit contiguous copy is worth its cost.
### Follow-up Questions
- Does `.T` copy the data or return a view?
- How would you transpose only two specific axes of a 3-D array?
- Why can code that reads a transposed array row by row run slower than the same code on the original, and what would you do about it?
Overview: Transpose a 2-D NumPy array of shape (m, n) into shape (n, m) without Python loops. The question tests vectorized transposes, how shape and strides change, whether the result is a view or a copy, and how to swap specific axes of a higher-dimensional array.