Explain NumPy's memory model: C vs. Fortran order, strides, and how views, reshape and transpose avoid copies
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Discuss NumPy's memory model, including contiguous memory, C-order (row-major) vs. Fortran-order (column-major), and how strides implement views, reshape, and transpose without copying.
```hint Address arithmetic
Write the byte offset of element (i, j) as a formula in terms of the strides. Then see what transpose and slicing have to change in that formula.
```
```hint When a view is impossible
Try reshaping a transposed 2-D array to one dimension and ask whether the resulting element order can be reached with a single fixed step through memory.
```
### What a Strong Answer Covers
- What an array is in memory: a data buffer plus shape, dtype, strides and a starting offset
- How C order and Fortran order map indices to byte offsets, and which one is the default
- How slicing, transpose and reshape produce views by changing strides and offset
- When NumPy has to copy, and how to tell a view from a copy
- Practical consequences such as cache behavior, aliasing bugs, and code that expects a particular layout
### Follow-up Questions
- How does broadcasting use a stride of zero?
- What is the difference between `ravel` and `flatten`?
- Why can passing a C-order array to a Fortran-based linear algebra routine cost extra time or memory?
- A function returns a small slice of a 2 GB array and memory usage stays high after the big array goes out of scope. Why, and how do you fix it?
Overview: Asks how NumPy lays arrays out in memory and how strides let slicing, transpose and reshape return views over the same buffer. Tests knowledge of C and Fortran order, contiguity, when NumPy must copy, and the performance and aliasing consequences.