Problem 392163 · medium · Phase 03 Linear Management & Searching

Apply a Sequence of Grid Transforms

matrix · transpose · composition

Given an m x n grid matrix and a string ops, apply the operations in ops from left to right and return the resulting grid (the input must not be modified). Each character is one of:

  • T - transpose: rows become columns (new[j][i] = old[i][j]), so an m x n grid becomes n x m;
  • H - horizontal flip: reverse every row (mirror left-right);
  • V - vertical flip: reverse the order of the rows (mirror top-bottom).

Examples

Input:  matrix = [[1, 2], [3, 4]], ops = "TH"
Output: [[3, 1], [4, 2]]
Explanation: transpose gives [[1, 3], [2, 4]]; flipping each row gives [[3, 1], [4, 2]].

Input:  matrix = [[1, 2, 3]], ops = "TV"
Output: [[3], [2], [1]]

Constraints

  • 1 <= m, n <= 200, 0 <= len(ops) <= 20
  • Target: O(len(ops) * m * n) time.

Goals

  • Implement transpose, horizontal flip and vertical flip as small functions
  • Apply a sequence of operations left to right, letting dimensions change
  • Reason about which combinations cancel out
Starting Python…