Search~20 min2s · 256 MBtarget O(cells + ops) time, O(cells) spacetraversal
An image search app has a small editor for result thumbnails. A thumbnail is a grid of brightness values. The editor has three buttons: turn a quarter clockwise, flip left to right, and flip top to bottom.
A user can press the buttons many times, and the app keeps the whole history of presses. When the thumbnail is saved, the app must produce the final picture, without redrawing it once for every press.
Write edit_thumbnail(grid, ops).
grid is a rectangle of values: grid[r][c] is the value in row r and column c. It need not be square.ops is a string of presses, in order. R turns the picture a quarter clockwise, H flips it left to right, and V flips it top to bottom.Input: grid = [[1, 2, 3], [4, 5, 6]], ops = "RHV"
Output: [[3, 6], [2, 5], [1, 4]]The table shows the picture after each press, and the two numbers that describe the whole history so far: the quarter turns and whether it is flipped.
| Edit | Picture after the edit | Turns | Flipped |
|---|---|---|---|
| start | [[1, 2, 3], [4, 5, 6]] | 0 | no |
| R | [[4, 1], [5, 2], [6, 3]] | 1 | no |
| H | [[1, 4], [2, 5], [3, 6]] | 3 | yes |
| V | [[3, 6], [2, 5], [1, 4]] | 3 | no |
The picture changes shape at the quarter turn and keeps its new shape after the flips.
Input: grid = [[7]], ops = "VRRH"
Output: [[7]]A grid of one value never changes.
Input: grid = [[1, 2], [3, 4]], ops = "V"
Output: [[3, 4], [1, 2]]A flip top to bottom swaps the two rows.
1 ≤ grid.length ≤ 1,000 rows, each with 1 to 1,000 values, all rows of the same length0 ≤ grid[r][c] ≤ 255 (brightness)1 ≤ ops.length ≤ 100,000 presses, each one of R, H, VA grid can hold 10^6 values and the history 10^5 presses. Redrawing the picture for every press costs about 10^11 steps. Every press changes the picture in one of a few fixed ways, so the whole history is one of only eight pictures, and one redraw is enough.