Rotate a 2-D NumPy array counter-clockwise by k times 90 degrees
Quick Overview
Implement a NumPy function that rotates a 2-D array counter-clockwise by any integer multiple of 90 degrees, with negative counts turning clockwise. It tests modulo reduction of the turn count, rotation direction, the output shape for non-square arrays, and whether np.rot90 returns a view or a copy.
Rotate a 2-D NumPy array counter-clockwise by k times 90 degrees
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `rotate_90(a, k)` that rotates a 2-D NumPy array counter-clockwise by `k * 90` degrees and returns the result.
A positive `k` rotates counter-clockwise and a negative `k` rotates clockwise. The function must handle any integer `k`, including values whose magnitude is greater than 4, by reducing it modulo 4 (for example `k % 4`). You may use `np.rot90`.
For example:
```python
a = np.array([[1, 2],
[3, 4]])
rotate_90(a, 1) # [[2, 4],
# [1, 3]]
rotate_90(a, -1) # [[3, 1],
# [4, 2]]
rotate_90(a, 6) # same as k=2: [[4, 3],
# [2, 1]]
```
```hint Check the direction and the shape
Before trusting a library call, confirm which way it turns for a positive `k` against the example, and work out what happens to the shape of a non-square array.
```
### What a Strong Answer Covers
- Reduces `k` modulo 4 and explains why Python's `%` maps a negative `k` to the right direction
- Gets the rotation direction right and checks it against the example
- States the output shape for a non-square array and an odd `k`
- Says whether the result shares memory with the input, and the time and memory cost that follows
### Follow-up Questions
- Does `np.rot90` return a copy or a view?
- How would you rotate along chosen axes of an N-D array?
- How would you implement the rotation without `np.rot90`, using only transposes and slices?
Overview: Implement a NumPy function that rotates a 2-D array counter-clockwise by any integer multiple of 90 degrees, with negative counts turning clockwise. It tests modulo reduction of the turn count, rotation direction, the output shape for non-square arrays, and whether np.rot90 returns a view or a copy.
Implement rotate_90(a, k) that rotates a 2-D NumPy array counter-clockwise by k * 90 degrees and returns the result.
A positive k rotates counter-clockwise and a negative k rotates clockwise. The function must handle any integer k, including values whose magnitude is greater than 4, by reducing it modulo 4 (for example k % 4). You may use np.rot90.