Gather NumPy Array Elements by an Integer Index Array
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D NumPy array `data` and a 1-D integer array `idx`, return a new array of `data`'s elements at the positions in `idx`, in `idx` order, using fancy (integer-array) indexing. Positions may repeat, so the result length equals `len(idx)`.
For example:
```python
data = np.array([10, 20, 30, 40, 50])
idx = np.array([0, 2, 2, 4])
# Output: array([10, 30, 30, 50])
```
```hint Index dtype
NumPy reads an index array differently depending on its dtype. Check what an integer array, a boolean array and a float array each do when used as an index.
```
### Constraints & Assumptions
- Every value `i` in `idx` satisfies `0 <= i < len(data)`.
- Do not mutate `data`.
### What a Strong Answer Covers
- A single vectorized index expression with no Python loop over `idx`.
- Why the output keeps the order of `idx`, repeats duplicated positions, and has the shape of `idx`.
- Whether the result shares memory with `data`, and how that relates to the no-mutation rule.
- The index dtype, and what happens with boolean, float, negative or out-of-range positions.
- Time and space cost in terms of `len(idx)`.
### Follow-up Questions
- Why does `data[idx]` return a copy, while a slice such as `data[1:4]` returns a view?
- How would you extend this to gather rows from a 2-D array, or one element from each row?
- If `idx` could contain negative or out-of-range positions, how would you handle them?
Overview: Write a NumPy function that returns the elements of a 1-D array at the positions listed in an integer index array, keeping their order and any repeats. It tests integer-array indexing, how the index dtype changes the result, and whether the output shares memory with the input.