NumPy View vs Copy Semantics
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D NumPy array, write `split_view_copy(arr)` that returns a tuple `(view, copy)`. The grader mutates the input afterward and asserts `view` reflects the change while `copy` does not.
For example:
```python
arr = np.array([1, 2, 3, 4])
view, copy = split_view_copy(arr)
arr[0] = 99
view[0] # 99 (shares memory)
copy[0] # 1 (independent)
```
```hint Check what you return
Before returning, test each result against the input with `np.shares_memory`, and confirm the view is a different Python object from `arr`. Look at `.base` on both results too.
```
### Constraints & Assumptions
- `view` shares memory with the input (for example the slice `arr[:]`).
- `copy` is independent (for example `arr.copy()` or `np.array(arr)`).
- Both are 1-D and equal the input's values at call time.
- Do not mutate the input inside the function.
- Views may be checked with `np.shares_memory(view, arr)` or `view.base`.
### What a Strong Answer Covers
- Which operations return a view and which allocate a new buffer, and why basic slicing is able to share memory.
- A function that returns a view that is a separate object from the input plus an independent copy, without touching the input.
- How to verify the relationship (`np.shares_memory`, `.base`, `flags.owndata`) and the limits of each check.
- Practical consequences of views: writes that leak back into the source, and large buffers kept alive by small slices.
### Follow-up Questions
- When does fancy or boolean indexing produce a copy instead of a view?
- How does `.base` help detect views, and what are its limits?
- Why can keeping a small slice of a very large array waste memory, and how do you avoid it?
- What is the difference between `arr[[0, 2]] = 0` and `arr[[0, 2]][0] = 0`?
Overview: Write a NumPy function that returns two arrays from one input: one that shares memory with it and one that stays independent after the input changes. It tests how slicing, fancy indexing and copies handle memory, and how to check views with .base and np.shares_memory.