Grid Editor: Flip Rows, Swap Rows, and Turn Clockwise
Arrays & HashingAuto-graded · 18 test casesLast updated
Simulate a sequence of string commands (row reversal, row swap, 90-degree clockwise turn) on a rectangular grid whose shape changes after each turn.
Grid Editor
You are given a rectangular grid of integers grid with n rows and m columns, and a list of text instructions ops. Apply the instructions one after another, in the order given, and return the resulting grid.
Instructions
Every instruction is a string in one of these three forms. Tokens are separated by single spaces.
-
"reverseRow r"ris a 0-based row index.- Reverse the order of the values in row
r.
-
"swap r1 r2"r1andr2are 0-based row indices.- Exchange row
r1with rowr2. Ifr1 == r2, nothing changes.
-
"rotate"- Turn the whole grid 90 degrees clockwise.
- A grid with
nrows andmcolumns becomes a grid withmrows andncolumns.
Row indices in an instruction always refer to the grid as it looks at the moment that instruction runs, so after a rotate the row count and row length are different from before.
Input
grid: a list ofnlists, each holdingmintegers.ops: a list of instruction strings, possibly empty.
Output
Return the final grid as a list of lists of integers. If ops is empty, return a grid equal to the input. The input grid should not be modified.
Constraints
n, m >= 1- Every row of
gridhas the same length. - Each value fits in a 32-bit signed integer.
- For every
reverseRow,swapinstruction:0 <= r, r1, r2 <the number of rows at the time the instruction is executed. - Every instruction string is well formed and matches one of the three forms above.
Examples
Example 1
Input: run_grid_ops([[1, 2, 3], [4, 5, 6]], ['reverseRow 0', 'rotate'])
Output: [[4, 3], [5, 2], [6, 1]]
Example 2
Input: run_grid_ops([[1, 2], [3, 4], [5, 6]], ['rotate'])
Output: [[5, 3, 1], [6, 4, 2]]
Example 3
Input: run_grid_ops([[1, 2, 3], [4, 5, 6], [7, 8, 9]], ['swap 0 2', 'reverseRow 1', 'rotate', 'reverseRow 0'])
Output: [[7, 6, 1], [2, 5, 8], [3, 4, 9]]
Hints
Hint 1
Keep a working copy of the grid and process the instructions in order, splitting each string on spaces and branching on the first token.
Hint 2
Always derive the current row and column counts from the current grid; never cache n and m, because a rotate swaps them.
Hint 3
A clockwise turn can be built by reading the rows from bottom to top and taking columns: new[j][i] = old[n-1-i][j]. Make sure the result consists of lists, not tuples.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a straightforward simulation. Copy the grid, then handle each instruction in turn:
- reverseRow r: reverse the list at index
r. - swap r1 r2: exchange the two row lists. Only references move, so this is cheap, and
r1 == r2is naturally a no-op. - rotate: build a new grid that is the old one turned 90 degrees clockwise. Reverse the order of the rows (bottom row first), then transpose with
zip(*...). Convert each resulting tuple to a list.
The clockwise rotation satisfies new[j][i] = old[n-1-i][j], where n is the current number of rows. Reversing the rows and then transposing yields exactly this: new row j is old column j read from bottom to top.
Why it is correct
Each instruction is a deterministic transformation of the current grid, and we apply them in the given order, so the final grid matches the definition. Because rotate rebinds the working grid to a freshly built m x n grid, every later instruction automatically sees the new shape, which is what the index constraint requires. Copying every row at the start guarantees the caller's input is never changed. Converting tuples back into lists keeps later reverseRow calls valid.
Complexity
Let N = n * m and let k be the number of instructions.
- Time:
reverseRowcosts O(current columns),swapcosts O(1), androtatecosts O(N). The worst case is O(N + k * N), when every instruction is a rotate. - Space: O(N), since at most two grids exist at once during a rotation.
Reference solution
from typing import List
def run_grid_ops(grid: List[List[int]], ops: List[str]) -> List[List[int]]:
current = [row[:] for row in grid]
for op in ops:
parts = op.split()
name = parts[0]
if name == "reverseRow":
r = int(parts[1])
current[r].reverse()
elif name == "swap":
r1 = int(parts[1])
r2 = int(parts[2])
current[r1], current[r2] = current[r2], current[r1]
elif name == "rotate":
current = [list(row) for row in zip(*current[::-1])]
return current