Overlapping 2D Block Move with O(1) Extra Memory
Arrays & HashingAuto-graded · 26 test casesLast updated
Tests whether a candidate can copy a rectangular subregion of a 2D grid onto another position in the same grid, in place, without corrupting overlapping data.
You have a 2D grid of integers and two rectangular windows of the same size inside it. Your job is to overwrite the destination window with the values that the source window currently holds, then return the grid.
Both windows live in the same grid and may overlap. You must perform the operation in place: allocating a temporary copy of the block, any of its rows, or a second grid is not allowed. Only O(1) extra memory beyond the input is permitted.
Inputs
| Parameter | Type | Meaning |
|---|---|---|
grid | list[list[int]] | The 2D grid to modify |
src_row | int | Top row of the source window |
src_col | int | Left column of the source window |
dst_row | int | Top row of the destination window |
dst_col | int | Left column of the destination window |
height | int | Number of rows in each window |
width | int | Number of columns in each window |
Rules
- For every
0 <= i < heightand0 <= j < width, the cell(dst_row + i, dst_col + j)must end up holding the value that(src_row + i, src_col + j)held before the operation began, even if the two windows overlap. - Every cell that lies outside the destination window must keep its original value. This includes any source cells that the destination window does not cover.
- Modify
gridin place and return it (the same list object you received). - Slice assignment like
row[a:b] = other[c:d]allocates a temporary list of lengthwidthon the right-hand side and counts as O(width) extra memory — do not use it.
Constraints
1 <= len(grid) <= 500;1 <= len(grid[0]) <= 500; every row has the same length.-10^9 <= grid[r][c] <= 10^91 <= height;1 <= width- Both windows fit entirely inside the grid:
0 <= src_row,src_row + height <= len(grid)0 <= dst_row,dst_row + height <= len(grid)0 <= src_col,src_col + width <= len(grid[0])0 <= dst_col,dst_col + width <= len(grid[0])
- Extra memory must be O(1) beyond the input grid.
Examples
Example 1
Input: move_grid_block([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], 0, 0, 0, 1, 2, 3)
Output: [[1, 1, 2, 3], [5, 5, 6, 7], [9, 10, 11, 12]]
Example 2
Input: move_grid_block([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], 1, 1, 0, 0, 2, 2)
Output: [[6, 7, 3, 4], [10, 11, 7, 8], [9, 10, 11, 12]]
Example 3
Input: move_grid_block([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], 0, 0, 1, 2, 2, 2)
Output: [[1, 2, 3, 4], [5, 6, 1, 2], [9, 10, 5, 6]]
Hints
Hint 1
Think about what goes wrong when the windows overlap. If you copy top-to-bottom and left-to-right, can a destination write ever land on a source cell you haven't read yet? Construct a tiny example where that happens.
Hint 2
Flatten the 2D grid mentally into a single row-major array. Each source cell moves by the same flat offset delta = (dst_row - src_row) * W + (dst_col - src_col). Now you have the classic 1D overlapping-copy problem: when delta > 0 you must copy back-to-front; when delta < 0 you copy front-to-back. The sign of delta is just the lexicographic comparison of (dst_row, dst_col) with (src_row, src_col).
Hint 3
You don't need to compute delta explicitly. If (dst_row, dst_col) comes after (src_row, src_col) in row-major order — meaning dst_row > src_row, or same row and dst_col > src_col — iterate rows bottom-up and columns right-to-left. Otherwise iterate rows top-down and columns left-to-right. Convince yourself that no source cell can be overwritten before it is read under this rule.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core hazard
When the source and destination windows overlap, copying cells in the wrong order can overwrite a source cell before it has been read. The destination then picks up an already-modified value instead of the original one, silently corrupting the result. The entire challenge is choosing an iteration order that avoids this.
Reducing to a 1D problem
Imagine unrolling the grid into a flat, row-major array of length R * C, where cell (r, c) maps to index r * C + c. Every source cell is displaced by the same flat offset:
delta = (dst_row - src_row) * C + (dst_col - src_col)
This is exactly the classic overlapping memory copy (C's memmove):
- When
delta > 0the destination sits after the source in memory. Copying front-to-back would read cellq, then later overwrite it from some earlier source cell. Copying back-to-front is safe. - When
delta < 0the destination sits before the source. Here back-to-front is dangerous; front-to-back is safe. - When
delta == 0every cell is written onto itself, so either order is harmless.
Reading the sign of delta without computing it
The sign of delta equals the lexicographic comparison of (dst_row, dst_col) with (src_row, src_col):
dst_row > src_rowimpliesdelta >= C + (dst_col - src_col) >= C - (C-1) = 1 > 0.dst_row == src_rowmeansdelta = dst_col - src_col, so the sign is justdst_colvssrc_col.- Any other case gives
delta < 0.
Mapping back to 2D
Back-to-front in flat order means iterating rows from bottom to top and, within each row, columns from right to left. Front-to-back means rows top to bottom and columns left to right.
Why correctness holds
In the back-to-front case (delta > 0), consider any source cell at flat index q. Suppose an earlier step in the loop already wrote to some destination cell and that write happened to land on q. That write came from a source cell at flat index p > q (we visited p first because we go in decreasing order). The write landed at p + delta. For that to equal q we would need p + delta = q, so delta = q - p < 0, contradicting delta > 0. Therefore no source cell is ever overwritten before it is read.
The front-to-back argument is the mirror image with reversed inequalities.
Cells outside the destination window are never touched by the loops, so they keep their original values automatically.
Complexity
- Time: O(height × width) — each destination cell is written exactly once.
- Space: O(1) extra — only loop indices and two row references are used; no temporary arrays or slices.
Edge cases
- Same source and destination: every cell is written onto itself; the grid is unchanged.
- Pure horizontal shift within a row band: this is the case that breaks a naive forward loop. Shifting right requires the right-to-left column pass; shifting left requires left-to-right.
- Pure vertical shift: only the row direction matters; column order inside a row is irrelevant because the source and destination rows are distinct objects.
- Non-overlapping windows: the ordering still applies consistently, and correctness is trivially preserved.
- 1×1 block or full-grid block: no special handling needed.
Solution
from typing import List
def move_grid_block(grid: List[List[int]], src_row: int, src_col: int,
dst_row: int, dst_col: int, height: int, width: int) -> List[List[int]]:
# Destination is later in row-major order -> copy back-to-front.
if dst_row > src_row or (dst_row == src_row and dst_col > src_col):
for i in range(height - 1, -1, -1):
s = grid[src_row + i]
d = grid[dst_row + i]
for j in range(width - 1, -1, -1):
d[dst_col + j] = s[src_col + j]
else:
# Destination is earlier or identical -> copy front-to-back.
for i in range(height):
s = grid[src_row + i]
d = grid[dst_row + i]
for j in range(width):
d[dst_col + j] = s[src_col + j]
return grid