KatInterview

Track Items Surviving Sequential Shifts on a Grid

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingsimulation2d-arrayprefix-sum

Last 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 where grid[r][c] represents the count of items initially in row r, column c. 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 row r to row r - 1, "D" to row r + 1, "L" from column c to column c - 1, and "R" to column c + 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 directions is empty, return the sum of all items in the initial grid.

Constraints

  • 1 <= len(grid) <= 50
  • 1 <= len(grid[0]) <= 50
  • All rows have identical length
  • 0 <= grid[r][c] <= 10^5
  • 0 <= len(directions) <= 200
  • Each element in directions is 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.