Remaining Grid Leaves After Wind Shifts

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

You are given an R x C matrix grid of non-negative integers where grid[r][c] denotes how many leaves initially sit in row r and column c (r = 0 is the northernmost row and c = 0 is the westernmost column). You are also given an ordered list winds, where each entry is a single-letter cardinal step: "U" (north), "D" (south), "L" (west), or "R" (east).

def leaves_remaining(grid: list[list[int]], winds: list[str]) -> int:

Process winds from first element to last under these mechanics:

  • During a single step, every leaf still on the board translates one unit simultaneously in that step's direction:
    • "U" moves (r, c) to (r - 1, c).
    • "D" moves (r, c) to (r + 1, c).
    • "L" moves (r, c) to (r, c - 1).
    • "R" moves (r, c) to (r, c + 1). Every leaf occupying a given cell moves together as one pile.
  • Any pile whose target coordinates fall outside 0 <= r < len(grid) or 0 <= c < len(grid[0]) drops off the board permanently; reversing direction on a later step never recovers discarded leaves.
  • After executing the entire winds sequence, return the sum of leaves remaining across all cells on the board. When winds is empty, no movement occurs and the initial board total is returned.

Examples

Example 1

Input: grid = [[2, 4, 1], [3, 0, 5], [6, 2, 1]], winds = ["L", "U"]
Output: 8
  • Step "L" shifts every cell one column west. Column 0 (2 + 3 + 6 = 11 leaves) exits past the left border, producing [[4, 1, 0], [0, 5, 0], [2, 1, 0]].
  • Step "U" shifts every cell one row north. Row 0 (4 + 1 + 0 = 5 leaves) exits past the top border, leaving [[0, 5, 0], [2, 1, 0], [0, 0, 0]] with 5 + 2 + 1 = 8 leaves.

Example 2

Input: grid = [[3, 2], [1, 4]], winds = ["D", "U"]
Output: 5
  • Step "D" pushes the bottom row (1 + 4 = 5 leaves) off the south border and moves the top row down to [[0, 0], [3, 2]].
  • Step "U" shifts those surviving leaves back up to [[3, 2], [0, 0]]. Because fallen leaves never return, 3 + 2 = 5 leaves remain.

Example 3

Input: grid = [[4, 0, 7, 2]], winds = []
Output: 13

With zero wind steps, every initial cell keeps its starting leaves (4 + 0 + 7 + 2 = 13).

Constraints

  • 1 <= len(grid) <= 50 and 1 <= len(grid[r]) <= 50, with identical length across all rows.
  • 0 <= grid[r][c] <= 10^5 (the sum of all cells fits within a signed 32-bit integer).
  • 0 <= len(winds) <= 200.
  • Every element in winds is "U", "D", "L", or "R".

Step-by-step walkthrough

  1. Understand the grid and the wind rules

    We start with a rectangular num_rows x num_cols grid of leaf counts and a list of wind gusts ("U", "D", "L", "R"). Row 0 is the top row and column 0 is the leftmost column.

    Each gust pushes every leaf on the board one cell in that direction at the exact same moment. Any leaf pushed outside the borders disappears permanently—a later gust in the opposite direction never brings lost leaves back:

    Example 2: grid = [[3, 2], [1, 4]], winds = ["D", "U"]
    
    Start       --("D")-->  Bottom row falls off  --("U")-->  Survivors shift up
    [3, 2]                  [0, 0]                             [3, 2]
    [1, 4]                  [3, 2]                             [0, 0]   (5 leaves left)
    

    We only need to return the total number of leaves still on the grid after the final gust.

  2. Start with gust-by-gust simulation

    The most literal approach simulates one gust at a time: for each gust, create a fresh num_rows x num_cols grid filled with zeros, copy every cell (r, c) into (r + delta_row, c + delta_col) if that destination is inside the grid, and discard anything that lands outside.

    Writing into a fresh grid on each gust is critical: if you update grid in place while scanning left to right during an "R" gust, leaves moved from column 0 to column 1 get picked up again on the next iteration and pushed all the way off the right edge in a single gust!

    With at most 200 gusts on a 50 x 50 grid (500,000 cell updates), simulation is fast enough to pass. However, we can do something much cleaner that reads each grid cell at most once, even if there were millions of gusts.

  3. Key insight: every leaf shares the same displacement

    Notice that leaves never collide, merge differently, or block one another—every surviving leaf moves as part of one rigid sheet.

    Track two running totals as gusts blow: - row_shift: total "D" gusts (+1 each) minus total "U" gusts (-1 each) so far. - col_shift: total "R" gusts (+1 each) minus total "L" gusts (-1 each) so far.

    If a leaf started at (r, c) and has not fallen off yet, its position after any prefix of gusts is simply:

    current_row = r + row_shift
    current_col = c + col_shift
    

    Because a leaf is lost forever the first time it steps outside the grid, a leaf starting at (r, c) survives the whole sequence if and only if (r + row_shift, c + col_shift) stays inside the grid after every gust—not just at the very end!

  4. Turn the extreme shifts into one safe starting rectangle

    For a starting row r to stay within 0 .. num_rows - 1 at every moment, two things must hold: 1. Even at the farthest upward excursion (min_row_shift, which is <= 0), it never goes above row 0: r + min_row_shift >= 0 -> r >= -min_row_shift 2. Even at the farthest downward excursion (max_row_shift, which is >= 0), it never goes past row num_rows - 1: r + max_row_shift <= num_rows - 1 -> r <= num_rows - 1 - max_row_shift

    The exact same algebra applies to columns using min_col_shift and max_col_shift. That means the leaves that survive to the end are all and only the leaves that started inside one sub-rectangle of the original grid:

    Original grid (0 .. num_rows - 1, 0 .. num_cols - 1):
    +---------------------------------------+
    |  lost to upward gusts (-min_row_shift)|
    |       +-----------------------+       |
    | lost  |   SAFE STARTING BOX   | lost  |
    | to L  | rows: first .. last   | to R  |
    | gusts | cols: first .. last   | gusts |
    |       +-----------------------+       |
    |  lost to downward gusts (max_row_shift)|
    +---------------------------------------+
    
  5. Track the running shift and its extremes

    We initialize row_shift, col_shift, and all four min_* / max_* extremes to 0. Starting the extremes at 0 represents the initial state before any wind blows, so min_row_shift is always <= 0 and max_row_shift is always >= 0 (and if winds is empty, all four stay 0).

    DIRECTION_DELTAS: Dict[str, Tuple[int, int]] = {
        "U": (-1, 0),
        "D": (1, 0),
        "L": (0, -1),
        "R": (0, 1),
    }
    
    # Phase 1 inside leaves_remaining(grid, winds):
    row_shift = 0
    col_shift = 0
    min_row_shift = 0
    max_row_shift = 0
    min_col_shift = 0
    max_col_shift = 0
    
    for gust in winds:
        delta_row, delta_col = DIRECTION_DELTAS[gust]
        row_shift += delta_row
        col_shift += delta_col
        min_row_shift = min(min_row_shift, row_shift)
        max_row_shift = max(max_row_shift, row_shift)
        min_col_shift = min(min_col_shift, col_shift)
        max_col_shift = max(max_col_shift, col_shift)
    
  6. Sum the surviving starting rectangle

    Once we have the four extremes, we compute the inclusive bounds first_safe_row .. last_safe_row and first_safe_col .. last_safe_col.

    What if the wind blew so far in one direction (or back and forth) that every single leaf fell off? Then first_safe_row > last_safe_row or first_safe_col > last_safe_col, and we immediately return 0. Otherwise, because min_*_shift <= 0 and max_*_shift >= 0, every index in the window is guaranteed to lie inside 0 .. num_rows - 1 and 0 .. num_cols - 1, so we sum those cells directly:

        # Phase 2: Convert extreme shifts into the surviving rectangle of starting coordinates.
        first_safe_row = -min_row_shift
        last_safe_row = num_rows - 1 - max_row_shift
        first_safe_col = -min_col_shift
        last_safe_col = num_cols - 1 - max_col_shift
    
        # Check whether the safe window still has at least one row and one column.
        remaining_leaves = 0
        if first_safe_row <= last_safe_row and first_safe_col <= last_safe_col:
            for r in range(first_safe_row, last_safe_row + 1):
                for c in range(first_safe_col, last_safe_col + 1):
                    remaining_leaves += grid[r][c]
    
  7. Trace Example 1 and Example 2

    First trace Example 1: grid = [[2, 4, 1], [3, 0, 5], [6, 2, 1]] (3 x 3), winds = ["L", "U"]:

    Step    row_shift  col_shift   row min..max   col min..max
    ------  ---------  ---------   ------------   ------------
    start       0          0           0 .. 0         0 .. 0
    "L"         0         -1           0 .. 0        -1 .. 0
    "U"        -1         -1          -1 .. 0        -1 .. 0
    
    Safe rows: -(-1) .. (3 - 1 - 0)  ->  1 .. 2
    Safe cols: -(-1) .. (3 - 1 - 0)  ->  1 .. 2
    Sum of grid[1..2][1..2] = (0 + 5) + (2 + 1) = 8
    

    Now check Example 2: grid = [[3, 2], [1, 4]] (2 x 2), winds = ["D", "U"]:

    Step    row_shift   min_row_shift   max_row_shift
    ------  ---------   -------------   -------------
    start       0             0               0
    "D"         1             0               1
    "U"         0             0               1
    
    Safe rows: -0 .. (2 - 1 - 1)  ->  0 .. 0  (only starting row 0 survives!)
    Safe cols: -0 .. (2 - 1 - 0)  ->  0 .. 1
    Sum of grid[0..0][0..1] = 3 + 2 = 5
    

    Even though row_shift returned to 0, max_row_shift = 1 remembers that starting row 1 fell off on the "D" step.

  8. Complete solution

    Putting both phases together inside leaves_remaining:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # DIRECTION_DELTAS: maps each gust character to (delta_row, delta_col),
    # where row 0 is the top edge and column 0 is the left edge.
    DIRECTION_DELTAS: Dict[str, Tuple[int, int]] = {
        "U": (-1, 0),
        "D": (1, 0),
        "L": (0, -1),
        "R": (0, 1),
    }
    
    
    def leaves_remaining(grid: list[list[int]], winds: list[str]) -> int:
        num_rows = len(grid)
        num_cols = len(grid[0])
    
        # Phase 1: Track the cumulative shift of the whole sheet of leaves and the
        # most extreme shifts ever reached. Initialize at 0 to include the starting state.
        row_shift = 0
        col_shift = 0
        min_row_shift = 0
        max_row_shift = 0
        min_col_shift = 0
        max_col_shift = 0
    
        for gust in winds:
            delta_row, delta_col = DIRECTION_DELTAS[gust]
            row_shift += delta_row
            col_shift += delta_col
            min_row_shift = min(min_row_shift, row_shift)
            max_row_shift = max(max_row_shift, row_shift)
            min_col_shift = min(min_col_shift, col_shift)
            max_col_shift = max(max_col_shift, col_shift)
    
        # Phase 2: Convert extreme shifts into the surviving rectangle of starting coordinates.
        # A starting cell (r, c) never crosses row < 0 iff r + min_row_shift >= 0,
        # and never crosses row >= num_rows iff r + max_row_shift <= num_rows - 1.
        first_safe_row = -min_row_shift
        last_safe_row = num_rows - 1 - max_row_shift
        first_safe_col = -min_col_shift
        last_safe_col = num_cols - 1 - max_col_shift
    
        # If the gusts swept across the entire height or width, the safe window is empty.
        if first_safe_row > last_safe_row or first_safe_col > last_safe_col:
            return 0
    
        # Phase 3: Sum the initial leaves inside the safe starting rectangle (inclusive bounds).
        remaining_leaves = 0
        for r in range(first_safe_row, last_safe_row + 1):
            for c in range(first_safe_col, last_safe_col + 1):
                remaining_leaves += grid[r][c]
    
        return remaining_leaves
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine all the leaves sitting on a transparent plastic sheet laid directly on top of the rectangular field. Each gust slides that entire sheet one square up, down, left, or right, and any leaf whose square slides past the border of the field drops off into a ditch forever. Because the leaves never rearrange relative to one another on the sheet, we do not need to move individual cells at all—we just track how far up, down, left, and right the sheet ever slides from its starting spot. Those four peak excursions trim a margin off the four edges of the original grid, leaving a single inner rectangle of starting cells whose leaves never fell off.

A naive simulation allocates a brand-new R x C grid on every single step and copies every surviving cell, doing O(W * R * C) work even though every cell shifts by the exact same (delta_row, delta_col). Worse, a tempting "add up all the gusts first" shortcut breaks immediately on ["D", "U"]: the final net shift is 0, yet the bottom row fell off on the first step and never comes back. Tracking the running prefix extremes (min and max shift seen at any point in time) captures every edge loss in a single pass over winds.

Walk through grid = [[2, 4, 1], [3, 0, 5], [6, 2, 1]] (3 x 3) with winds = ["L", "U"]: - Start at shift (0, 0), with row extremes 0..0 and column extremes 0..0. - Step "L": shift becomes (0, -1) -> column extremes become -1..0 (starting column 0 was pushed past the left border). - Step "U": shift becomes (-1, -1) -> row extremes become -1..0 (starting row 0 was pushed past the top border). - Safe starting rows are -(-1) .. (3 - 1 - 0) = 1..2 and safe starting columns are -(-1) .. (3 - 1 - 0) = 1..2, giving 0 + 5 + 2 + 1 = 8 remaining leaves.

Complexity

Let W be len(winds), R be len(grid), and C be len(grid[0]). Auxiliary space is the extra temporary memory used beyond the input grid and wind list.

  • Time complexity — O(W + R * C): We scan the W gusts once, doing O(1) arithmetic per gust to update the running shift and its four extremes, and then we visit each cell inside the surviving sub-rectangle at most once (at most R * C additions).
  • Auxiliary space — O(1): We store only a handful of integer counters (row_shift, col_shift, four extremes, four rectangle bounds, and remaining_leaves) and never allocate a copy of the grid.

Edge cases

  • Empty winds ([]): The loop over winds does not run, all four extremes remain 0, and the safe rectangle covers the entire R x C grid, returning the initial sum.
  • Opposite gusts (["U", "D"] or ["L", "R"]): Even though row_shift or col_shift returns to 0, the negative or positive extreme stays non-zero and properly excludes the row or column that blew off mid-sequence.
  • Gusts sweeping the entire field: Whenever max_row_shift - min_row_shift >= R or max_col_shift - min_col_shift >= C (for example three "R" gusts on a 3-column grid), first_safe_row > last_safe_row or first_safe_col > last_safe_col, and the function returns 0.
  • 1 x 1 grid or single-row / single-column grids: Any gust clears a 1 x 1 grid to 0; any "U" or "D" gust clears a 1 x C grid to 0.
  • Maximum total leaf count: At 50 x 50 cells with 10^5 leaves per cell, the maximum answer is 250,000,000, which fits comfortably inside a standard 32-bit signed integer (2,147,483,647) as well as Python's arbitrary-precision int.

Common mistakes

  • Checking only the final net shift: Computing final_row_shift and final_col_shift misses leaves blown off partway through when later gusts reverse direction (such as ["L", "R"]).
  • Shifting a grid in place in the wrong loop order: In a simulation approach, iterating c from 0 to C - 1 while moving leaves right (grid[r][c + 1] = grid[r][c]) cascades the same leaves across the entire row during a single gust.
  • Swapping "U" and "D" signs: Row 0 is the top of the grid, so "U" decreases the row index (-1) and "D" increases it (+1).
  • Off-by-one on inclusive rectangle bounds: Both last_safe_row = num_rows - 1 - max_row_shift and last_safe_col = num_cols - 1 - max_col_shift are inclusive indices, so Python's range requires + 1 at the stop argument.
  • Clamping out-of-bounds leaves onto the border cell: Leaves pushed past the grid boundary disappear permanently rather than piling up along the wall.

Alternative approaches

  • Gust-by-gust simulation: Allocate a fresh R x C zero grid for each gust and copy in-bounds destinations in O(W * R * C) time and O(R * C) auxiliary space. It is slightly slower for large W, but becomes the right approach if obstacles or sticky cells break uniform movement.
  • Precomputed 2D prefix sums for multiple wind queries: If the problem asked Q independent wind-sequence queries on the same initial grid, we could build a 2D prefix-sum table (a (R + 1) x (C + 1) array where entry (r, c) holds the sum of all cells in the top-left r x c block) once in O(R * C) time, then answer any safe rectangle's sum in O(1) time after scanning that query's gusts in O(W) time.

Follow-up questions

  • How would you construct the final grid of leaf counts rather than returning only their sum? Every cell (r, c) inside the safe starting rectangle survives without colliding and ends up shifted by the final (row_shift, col_shift). Allocate one R x C grid of zeros and copy final_grid[r + row_shift][c + col_shift] = grid[r][c] for each (r, c) in the safe rectangle, which still runs in O(W + R * C) time.
  • How does the algorithm change if every gust specifies both a direction and a multi-cell step distance? Multiply (delta_row, delta_col) by steps when updating row_shift and col_shift. Because moving steps cells in one straight line reaches its furthest excursion at the end of that step, the exact same min/max shift formulas still find the surviving rectangle in O(W + R * C) time—even if steps is 10^9!
  • What if each gust shifted only one designated row or column instead of the entire grid? Different rows or columns would no longer move as one rigid sheet, so a single global shift would no longer describe the board. Instead, simulate directly on a mutable copy of grid, shifting only the targeted row in O(C) time or the targeted column in O(R) time per step (scanning from the downwind border backward so cells are not overwritten before being read).

Follow-up questions

Similar questions

More Cresta interview questions

All 10 Cresta questions →