FastPrepLeaves Remaining After Wind

Leaves Remaining After Wind

Cresta logoCresta● MediumFULLTIMEOA
Learn

Problem statement

A rectangular grid stores a nonnegative number of leaves in each cell. For this exercise, assume each character in winds moves every remaining leaf exactly one cell in that direction: U up, D down, L left and R right.

All leaves move simultaneously for each character. A leaf that moves outside the grid is permanently removed. Process the wind characters in order and return the total number of leaves still inside the grid. An empty wind string leaves the grid unchanged.

Function

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

Examples

Example 1

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

Only leaves initially in the left column survive, for a total of 1 + 3 = 4.

Example 2

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

The second wind moves surviving leaves back, but removed leaves do not return; the total is still 4.

Example 3

grid = [[5]]winds = ""return = 5

No wind removes any leaf.

Constraints

  • 1 <= grid.length, grid[0].length <= 30; every row has the same length.
  • 0 <= grid[r][c] <= 10^9.
  • 0 <= winds.length <= 2000; characters are U, D, L or R.
  • Return the exact total as a signed64-bit integer.

More Cresta problems

See Cresta hiring insights
public long remainingLeaves(int[][] grid, String winds) {
    // write your code here
}
grid[[1,2],[3,4]]
winds"R"
expected4
Checking account…