FastPrepWind-Blown Leaves Remaining in a Grid

Wind-Blown Leaves Remaining in a Grid

Abridge logoAbridge● EasyNEW GRADOA

Problem statement

A garden is a grid. grid[i][j] is the number of leaves in the cell at row i and column j. Row 0 is the top row and column 0 is the left column.

The string winds lists gusts of wind in order. Each gust moves every leaf still in the grid exactly one cell:

  • U moves leaves one row up.
  • D moves leaves one row down.
  • L moves leaves one column left.
  • R moves leaves one column right.

All leaves move at the same time during a gust. A leaf that is moved outside the grid is gone for good, even if a later gust blows the other way.

Return the total number of leaves left in the grid after all gusts.

Interviewer Follow-up

Why should each gust build a new grid instead of updating the grid in place? What can go wrong with an in-place update? This follow-up is for discussion; the tests check only the returned total.

Function

remainingLeaves(grid: int[][], winds: String) → long

Examples

Example 1

grid = [[1,2,3],[4,5,6]]winds = "R"return = 12

Every leaf moves one column right. The leaves in the last column, 3 and 6, leave the grid. The rest stay: 1 + 2 + 4 + 5 = 12.

Example 2

grid = [[0,5,0],[0,0,0],[7,0,0]]winds = "DL"return = 5

After D, the 7 leaves in the bottom row are blown out, and the 5 leaves move to row 1, column 1. After L, they move to row 1, column 0, which is still inside. So 5 leaves remain.

Example 3

grid = [[4,1],[2,3]]winds = "LR"return = 4

The first wind L blows the left column (4 and 2) out of the grid. The second wind R moves the other leaves back to the right column. Leaves that left do not come back, so 1 + 3 = 4 remain.

Constraints

  • 1 <= grid.length <= 50
  • 1 <= grid[i].length <= 50, and every row has the same length.
  • 0 <= grid[i][j] <= 10^6
  • 0 <= winds.length <= 2000
  • Each character of winds is U, D, L or R.

More Abridge problems

See Abridge hiring insights
Saved
public long remainingLeaves(int[][] grid, String winds) {
    // Write your code here.
}
Checking account…