Implement MATLAB rot90 for Rectangular Matrices
Last updated: November 29, 2026
Quick Overview
Implement rot90(A, k) that rotates a possibly non-square matrix counterclockwise by k times 90 degrees, where k may be negative or larger than 3, matching MATLAB's behavior.
MathWorks
November 29, 20260
0
0 solved
Implement rot90(A, k) that rotates a possibly non-square matrix counterclockwise by k times 90 degrees, where k may be negative or larger than 3, matching MATLAB's behavior.
A short MathWorks phone screen question that checks index reasoning on a built-in the candidate may have used. The interviewer wants a correct index mapping for non-square inputs, normalization of k, and a quick hand trace.
What the Interviewer Expects
- Normalizes k with modulo 4 so negative values mean clockwise
- Derives the index mapping for a counterclockwise turn: new[r][c] = old[c][cols-1-r]
- Handles rectangular matrices, where the shape becomes cols x rows
- Does not mutate the input
- Traces a 2x3 example by hand
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Can you do k = 1 in place for a square matrix with O(1) extra memory?
- How would you implement rot90 on an N-dimensional array along a chosen pair of dimensions?
- Express rot90 using only transpose and flipping rows or columns.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: list of rows A (rectangular, possibly empty) and integer k (default 1). Output: a new matrix rotated counterclockwise 90 degrees k times. k = -1 is one clockwise turn, k = 4 is the iden...
High-Level Design
Reduce k modulo 4 (Python's % already maps -1 to 3). One counterclockwise turn of an r x c matrix gives a c x r matrix where the last column becomes the first row. So `new[r][c] = old[c][cols-1-r]...