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)or0 <= c < len(grid[0])drops off the board permanently; reversing direction on a later step never recovers discarded leaves. - After executing the entire
windssequence, return the sum of leaves remaining across all cells on the board. Whenwindsis 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. Column0(2 + 3 + 6 = 11leaves) exits past the left border, producing[[4, 1, 0], [0, 5, 0], [2, 1, 0]]. - Step
"U"shifts every cell one row north. Row0(4 + 1 + 0 = 5leaves) exits past the top border, leaving[[0, 5, 0], [2, 1, 0], [0, 0, 0]]with5 + 2 + 1 = 8leaves.
Example 2
Input: grid = [[3, 2], [1, 4]], winds = ["D", "U"]
Output: 5
- Step
"D"pushes the bottom row (1 + 4 = 5leaves) 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 = 5leaves 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) <= 50and1 <= 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
windsis"U","D","L", or"R".
Step-by-step walkthrough
Understand the grid and the wind rules
We start with a rectangular
num_rows x num_colsgrid of leaf counts and a list of wind gusts ("U","D","L","R"). Row0is the top row and column0is 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.
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_colsgrid 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
gridin place while scanning left to right during an"R"gust, leaves moved from column0to column1get picked up again on the next iteration and pushed all the way off the right edge in a single gust!With at most
200gusts on a50 x 50grid (500,000cell 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.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 (+1each) minus total"U"gusts (-1each) so far. -col_shift: total"R"gusts (+1each) minus total"L"gusts (-1each) 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_shiftBecause 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!Turn the extreme shifts into one safe starting rectangle
For a starting row
rto stay within0 .. num_rows - 1at every moment, two things must hold: 1. Even at the farthest upward excursion (min_row_shift, which is<= 0), it never goes above row0:r + min_row_shift >= 0->r >= -min_row_shift2. Even at the farthest downward excursion (max_row_shift, which is>= 0), it never goes past rownum_rows - 1:r + max_row_shift <= num_rows - 1->r <= num_rows - 1 - max_row_shiftThe exact same algebra applies to columns using
min_col_shiftandmax_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)| +---------------------------------------+Track the running shift and its extremes
We initialize
row_shift,col_shift, and all fourmin_*/max_*extremes to0. Starting the extremes at0represents the initial state before any wind blows, somin_row_shiftis always<= 0andmax_row_shiftis always>= 0(and ifwindsis empty, all four stay0).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)Sum the surviving starting rectangle
Once we have the four extremes, we compute the inclusive bounds
first_safe_row .. last_safe_rowandfirst_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_roworfirst_safe_col > last_safe_col, and we immediately return0. Otherwise, becausemin_*_shift <= 0andmax_*_shift >= 0, every index in the window is guaranteed to lie inside0 .. num_rows - 1and0 .. 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]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) = 8Now 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 = 5Even though
row_shiftreturned to0,max_row_shift = 1remembers that starting row1fell off on the"D"step.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 theWgusts once, doingO(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 mostR * Cadditions). - Auxiliary space —
O(1): We store only a handful of integer counters (row_shift,col_shift, four extremes, four rectangle bounds, andremaining_leaves) and never allocate a copy of the grid.
Edge cases
- Empty
winds([]): The loop overwindsdoes not run, all four extremes remain0, and the safe rectangle covers the entireR x Cgrid, returning the initial sum. - Opposite gusts (
["U", "D"]or["L", "R"]): Even thoughrow_shiftorcol_shiftreturns to0, 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 >= Rormax_col_shift - min_col_shift >= C(for example three"R"gusts on a 3-column grid),first_safe_row > last_safe_roworfirst_safe_col > last_safe_col, and the function returns0. 1 x 1grid or single-row / single-column grids: Any gust clears a1 x 1grid to0; any"U"or"D"gust clears a1 x Cgrid to0.- Maximum total leaf count: At
50 x 50cells with10^5leaves per cell, the maximum answer is250,000,000, which fits comfortably inside a standard 32-bit signed integer (2,147,483,647) as well as Python's arbitrary-precisionint.
Common mistakes
- Checking only the final net shift: Computing
final_row_shiftandfinal_col_shiftmisses 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
cfrom0toC - 1while 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: Row0is 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_shiftandlast_safe_col = num_cols - 1 - max_col_shiftare inclusive indices, so Python'srangerequires+ 1at 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 Czero grid for each gust and copy in-bounds destinations inO(W * R * C)time andO(R * C)auxiliary space. It is slightly slower for largeW, 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
Qindependent wind-sequence queries on the same initialgrid, 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-leftr x cblock) once inO(R * C)time, then answer any safe rectangle's sum inO(1)time after scanning that query's gusts inO(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 oneR x Cgrid of zeros and copyfinal_grid[r + row_shift][c + col_shift] = grid[r][c]for each(r, c)in the safe rectangle, which still runs inO(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)bystepswhen updatingrow_shiftandcol_shift. Because movingstepscells in one straight line reaches its furthest excursion at the end of that step, the exact samemin/maxshift formulas still find the surviving rectangle inO(W + R * C)time—even ifstepsis10^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 inO(C)time or the targeted column inO(R)time per step (scanning from the downwind border backward so cells are not overwritten before being read).
Follow-up questions
- How would you construct the final grid of leaf counts rather than returning only their sum?
- How does the algorithm change if every gust specifies both a direction and a multi-cell step distance?
- What if each gust shifted only one designated row or column instead of the entire grid?
Similar questions
- Longest Suffix-to-Prefix String Overlap
- Implement a Conversational Flight Search and Booking Agent with Tool Calling
- In-Memory Feature Flag Rule Evaluator
- Benchmarking and Release-Gating Platform for Tool-Using AI Agents
- Greedy and Beam-Search Token Sequence Decoding
- Dynamic Task Router with Least-Loaded Tie Rotation
More Cresta interview questions
- Dynamic Task Router with Least-Loaded Tie Rotation Medium
- Implement a Conversational Flight Search and Booking Agent with Tool Calling Medium
- In-Memory Feature Flag Rule Evaluator Medium Pro
- Benchmarking and Release-Gating Platform for Tool-Using AI Agents Medium Pro
- Longest Suffix-to-Prefix String Overlap Medium Pro
- Asynchronous Video Walkthrough of a Past AI System Medium Pro
- Locate Files Across a Directory Hierarchy and Return Absolute Paths Medium Pro
- Greedy and Beam-Search Token Sequence Decoding Medium Pro
- Taking a Validated Prototype to Production Easy Pro