Cyclic Array Shift With roll_array
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `roll_array(a, k)` that cyclically shifts a 1-D NumPy array `a` by `k` positions and returns a new array of the same length. Elements shifted off one end wrap around to the other.
Requirements:
- Positive `k` rotates right, negative `k` rotates left.
- Handle `|k|` larger than the length by taking `k % n`.
- Do not modify the input array.
- An empty array returns an empty array.
For example:
```text
Input: a = np.array([1, 2, 3, 4, 5]), k = 2
Output: [4, 5, 1, 2, 3]
Input: a = np.array([1, 2, 3, 4, 5]), k = -1
Output: [2, 3, 4, 5, 1]
```
```hint Normalize the shift
Check what Python's `%` returns for `k = -1` and for `k = 7` when `n = 5`, and which split point of the array each result describes. Then decide what happens when `n` is 0.
```
### Constraints & Assumptions
- `a` is a 1-D array of length `n`, where `n >= 0`.
- `k` is any integer, positive, negative or zero, and may be larger than `n` in absolute value.
### What a Strong Answer Covers
- How the sign of `k` maps to the direction of rotation, and how `k % n` turns negative and oversized shifts into one valid shift
- That the function returns a new array and leaves the input unchanged
- The empty array and the case where `k % n` is 0
- The time and space cost of the shift
### Follow-up Questions
- How would you implement this without `np.roll`, using only slicing?
- How would you extend this to roll along a chosen axis of a 2-D array?
Overview: Implement a cyclic shift of a 1-D NumPy array where positive shifts rotate right, negative shifts rotate left, and shifts longer than the array wrap around. It tests modulo index arithmetic, empty-array handling, leaving the input unchanged, and rolling along one axis of a 2-D array.