Array Reshaping
Problem Statement
Reshape arrays into different dimensions.
Background
NumPy reshape operations:
- arr.reshape(m, n) - reshape to m×n
- arr.reshape(-1) - flatten
- arr.reshape(-1, 1) - column vector
- arr.T or arr.transpose() - transpose
Your Task
Write a function reshape_array(arr, rows, cols) that reshapes a 1D array.
Output Format
Return a dictionary with:
- "reshaped": Array reshaped to (rows, cols) as list
- "transposed": Transposed (cols, rows) as list
- "flattened": Flattened back to 1D as list
- "column_vec": As column vector (n, 1) as list
Example:
arr = [1,2,3,4,5,6], rows = 2, cols = 3
{'reshaped': [[1, 2, 3], [4, 5, 6]], ...}reshape(2,3) creates 2 rows of 3, transpose swaps dimensions
Constraints:
- Array size must equal rows * cols
- Use -1 for automatic dimension calculation
More from NumPy Foundations
Background Knowledge
NumPy arrays are the foundational data structure for numerical computing in Python, enabling efficient multi-dimensional array operations without explicit loops. The reshape() method changes an array's shape (dimensions) while preserving the total number of elements and their order in memory, making it ideal for transforming 1D vectors into matrices or higher-dimensional tensors. For example, arr.reshape(m, n) reorganizes data into an m×n grid, where the product m×n must equal the original array length; the -1 wildcard infers one dimension automatically (e.g., reshape(-1, 1) for a column vector).
Transpose operations like arr.T or arr.transpose() swap row and column indices without copying data, creating a view into the original array for memory efficiency. Flattening with reshape(-1) converts any array back to 1D, useful for serialization or feeding into models. These operations leverage NumPy's vectorized computation, avoiding Python loops for speed—critical for large datasets in science and engineering.
Algorithm/Approach
The core pattern is shape transformation via NumPy's reshaping utilities:
- Validate input array length matches rows * cols.
- Apply targeted reshape operations to generate required views.
- Convert NumPy arrays to nested Python lists for output.
- Package results in a dictionary matching the specified keys.
This leverages NumPy's zero-copy views where possible, ensuring O(1) time for most transformations.
Step-by-Step Strategy
- Input Handling: Accept 1D NumPy array arr, integers rows, cols. Check if len(arr) == rows * cols to ensure reshape is possible.
- Reshape to Target: Use arr.reshape(rows, cols) to create the primary matrix.
- Generate Variants:
- Transpose: Apply .T to the reshaped array for (cols, rows).
- Flatten: Use reshape(-1) on original or reshaped array.
- Column Vector: Use reshape(-1, 1) on original array.
- Convert to Lists: Use .tolist() on each NumPy array to produce nested Python lists.
- Return Dictionary: Populate with keys "reshaped", "transposed", "flattened", "column_vec".
Test with sample: np.array([1,2,3,4,5,6]) → (2,3) yields [[1,2,3],[4,5,6]].
Common Pitfalls
- Shape Mismatch: Forgetting to verify len(arr) == rows * cols causes ValueError; always check first.
- Data Type Issues: Input might not be numeric—ensure arr is np.ndarray via isinstance().
- List Conversion: .tolist() produces correct nesting, but manual loops create wrong structures (e.g., flat list instead of [,]).
- Modifying Views: Transpose/reshape are views; changes propagate—use .copy() if mutation is a risk (not needed here).
- Negative Dimensions: -1 only for one axis; multiple -1 fails.
Time & Space Complexity
- Time: O(N) where N= array length—dominated by .tolist() traversal; reshape/transpose are O(1) views.
- Space: O(N) for output lists (copies data); intermediate views add negligible O(1). Total output dictionary uses O(N) extra space.