Track Items Surviving Sequential Shifts on a Grid
Arrays & HashingAuto-graded · 23 test casesLast updated
Determine which grid cells remain in bounds after a sequence of directional shifts, testing displacement tracking and boundary analysis.
You are given a rectangular grid where each cell contains a count of items. A sequence of directional shifts is then applied to the entire grid. Each shift moves all items exactly one cell in a specified direction simultaneously. Items that move outside the grid boundaries are permanently removed and cannot return in subsequent shifts.
Your task is to calculate the total number of items remaining on the grid after all shifts have been applied.
Function Signature
def count_surviving_items(grid: List[List[int]], directions: List[str]) -> int:
Parameters
grid: A 2D list wheregrid[r][c]represents the count of items initially in rowr, columnc. Row 0 is the topmost row, and column 0 is the leftmost column.directions: A list of shift directions, where each element is one of"U"(up),"D"(down),"L"(left), or"R"(right).
Behavior
- Shifts are processed sequentially in the order they appear in
directions. - During each shift, all items move simultaneously:
"U"moves items from rowrto rowr - 1,"D"to rowr + 1,"L"from columncto columnc - 1, and"R"to columnc + 1. - All items in a cell move together as a single unit.
- Any item that moves to a position outside the grid boundaries is permanently discarded.
- Return the total count of items remaining on the grid after all shifts. If
directionsis empty, return the sum of all items in the initial grid.
Constraints
1 <= len(grid) <= 501 <= len(grid[0]) <= 50- All rows have identical length
0 <= grid[r][c] <= 10^50 <= len(directions) <= 200- Each element in
directionsis one of"U","D","L","R"
Examples
Example 1
Input: count_surviving_items([[1, 2, 0], [0, 3, 4], [5, 0, 6]], ['R', 'D'])
Output: 6
Example 2
Input: count_surviving_items([[1, 1], [1, 1]], ['L', 'R'])
Output: 2
Example 3
Input: count_surviving_items([[0, 5, 0]], [])
Output: 5
Hints
Hint 1
Consider that all items move by the same displacement vector at each step—no item moves independently.
Hint 2
Track the cumulative displacement path, not just the final position. An item survives only if it stays in bounds at every intermediate step.
Hint 3
For each starting cell, check whether adding the minimum and maximum row offsets keeps it in bounds, and do the same for columns independently.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that every item on the grid moves by exactly the same displacement vector during each shift. Items never move independently, and they never interact with each other. This transforms the problem from simulating individual movements to analyzing displacement trajectories.
For each starting cell (r, c), we need to determine whether the items in that cell survive all shifts. An item survives if and only if it remains within grid boundaries after every single shift, not just at the end. Once an item exits the grid, it is permanently lost.
After k shifts, every item has moved by a cumulative offset (row_offset_k, col_offset_k). An item starting at (r, c) will be at position (r + row_offset_k, c + col_offset_k) after shift k. For the item to survive the entire sequence, this position must be valid at every step k.
Rather than checking every intermediate position, we can track the extreme displacement values reached during the entire sequence:
min_row,max_row: smallest and largest row offsets encounteredmin_col,max_col: smallest and largest column offsets encountered
A cell (r, c) survives if and only if:
0 <= r + min_row and r + max_row < rows and 0 <= c + min_col and c + max_col < cols
The row and column conditions are independent, so we can check each axis separately. The answer is the sum of grid[r][c] over all cells that satisfy these conditions.
Why This Works
- Uniform motion: Every item moves identically on each shift, so their trajectories differ only by starting position.
- Permanent removal: Items that exit cannot return, so we must verify every intermediate position stays in bounds.
- Extremes suffice: If a trajectory stays in bounds at its extreme displacements, it stays in bounds throughout. For row
r, the conditionsr + min_row >= 0andr + max_row < rowsguarantee all intermediate positionsr + offsetare valid sincemin_row <= offset <= max_row. - No interactions: Items simply add together when they land in the same cell; there are no collisions that destroy items.
Complexity
- Time: O(D + R × C) where D is the length of
directions, R is the number of rows, and C is the number of columns. We scan the directions once to compute extremes, then scan the grid once to sum survivors. - Space: O(1) extra space beyond the input. We only maintain a few integer variables for tracking offsets and extremes.
Full Solution
from typing import List
def count_surviving_items(grid: List[List[int]], directions: List[str]) -> int:
rows = len(grid)
cols = len(grid[0])
# Track cumulative displacement and its extremes
row_offset = col_offset = 0
min_row = max_row = min_col = max_col = 0
for direction in directions:
if direction == "U":
row_offset -= 1
elif direction == "D":
row_offset += 1
elif direction == "L":
col_offset -= 1
else: # "R"
col_offset += 1
min_row = min(min_row, row_offset)
max_row = max(max_row, row_offset)
min_col = min(min_col, col_offset)
max_col = max(max_col, col_offset)
# Sum items from cells that stay in bounds throughout all shifts
total = 0
for r in range(rows):
if r + min_row < 0 or r + max_row >= rows:
continue
for c in range(cols):
if c + min_col >= 0 and c + max_col < cols:
total += grid[r][c]
return total