easy +8 pts

Reshape array dimensions

Reshape a 1D list into a 2D grid with row-major order.

Write a function `reshape_array(arr, rows, cols)` that takes a 1D list `arr` of length `rows * cols` and returns a 2D list (list of lists) with shape `(rows, cols)` filled row-wise (row-major order). Raise a `ValueError` with message `'Invalid dimensions'` if the total number of elements does not match `rows * cols`. The function should preserve the input order. Do not import numpy. Important edge case: if `rows` or `cols` is 0, return `[]` (the empty list) instead of `[[]]`.

Constraints

`arr` is a 1D list. `rows` and `cols` are non-negative integers. The length of `arr` may be zero; if `rows * cols == 0` then `arr` must be empty (otherwise raise `ValueError`). The function should return a list of lists. Complexity: O(n) time and O(n) memory.

Example

```python
# Example 1
arr = [1, 2, 3, 4, 5, 6]
reshape_array(arr, 2, 3)
# [[1, 2, 3], [4, 5, 6]]

# Example 2: invalid dimensions
reshape_array([1, 2, 3], 2, 2)
# ValueError: Invalid dimensions

# Example 3: zero dimension
reshape_array([], 1, 0)
# []
```
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Check if len(arr) equals rows * cols first.
If `rows == 0` or `cols == 0`, return an empty list.
Use slicing with a step of `cols` to build each row.
Simpler: use a loop to append sublists of size `cols`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.