KatInterview

Grid Editor: Flip Rows, Swap Rows, and Turn Clockwise

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingmatrixsimulationstring-parsing

Last 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.

  1. "reverseRow r"

    • r is a 0-based row index.
    • Reverse the order of the values in row r.
  2. "swap r1 r2"

    • r1 and r2 are 0-based row indices.
    • Exchange row r1 with row r2. If r1 == r2, nothing changes.
  3. "rotate"

    • Turn the whole grid 90 degrees clockwise.
    • A grid with n rows and m columns becomes a grid with m rows and n columns.

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 of n lists, each holding m integers.
  • 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 grid has the same length.
  • Each value fits in a 32-bit signed integer.
  • For every reverseRow, swap instruction: 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.