Sliding Window Maxima on a Grid With Source Positions
Arrays & HashingAuto-graded · 24 test casesLast updated
Slide a square window over an integer grid with a given step, and report each window's maximum with its grid coordinates, resolving ties by the smallest row, then the smallest column.
Grid Window Maxima With Locations
You are given a rectangular grid of integers. A square window of side k moves across the grid, jumping stride cells at a time both horizontally and vertically. For every window position, you must find the largest value inside it and also say where in the grid that value sits.
Window placement
- There is no padding. The window with index
(i, j)has its top-left corner at rowi * stride, columnj * stride, for alli, j >= 0. - A window is only used if it lies completely inside the grid. If the grid has
Rrows andCcolumns, the result has(R - k) // stride + 1rows and(C - k) // stride + 1columns. - Cells at the bottom or right edge that cannot be covered by a full window are simply ignored.
- If
kexceeds the number of rows or the number of columns, no window fits, and you must return an empty list[](not a list containing empty lists).
Output format
Return a 3-level nested list. The entry at result[i][j] is a list [value, row, col], where:
valueis the maximum of the window with index(i, j),rowandcolare the 0-indexed coordinates of that maximum in the original grid (not relative to the window).
Ties
If the maximum value appears several times in a window, report the occurrence with the smallest row index; if several of those share that row, report the one with the smallest column index.
Constraints
1 <= len(grid) <= 1001 <= len(grid[r]) <= 100, and all rows have the same length-10^9 <= grid[r][c] <= 10^91 <= k <= 1001 <= stride <= 100
Examples
Example 1
Input: window_max_with_position([[1, 3, 2, 0], [4, 6, 5, 1], [7, 2, 9, 8], [3, 4, 1, 6]], 2, 2)
Output: [[[6, 1, 1], [5, 1, 2]], [[7, 2, 0], [9, 2, 2]]]
Example 2
Input: window_max_with_position([[5, 1, 5], [2, 5, 0], [1, 1, 3]], 2, 1)
Output: [[[5, 0, 0], [5, 0, 2]], [[5, 1, 1], [5, 1, 1]]]
Example 3
Input: window_max_with_position([[1, 2], [3, 4]], 3, 1)
Output: []
Hints
Hint 1
First decide how many windows fit along each axis. If k exceeds either dimension, return [] immediately, before using any formula that could go negative.
Hint 2
For a window with top-left corner (r0, c0), scan rows r0..r0+k-1 and columns c0..c0+k-1, remembering the best value and its position. Do not initialise the best to 0, because values can be negative.
Hint 3
Scan in row-major order and replace the stored best only when a value is strictly greater. The first occurrence in row-major order is then exactly the smallest row, then smallest column.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulate the process directly. First, if k > R or k > C, return []. Otherwise there are (R - k) // stride + 1 window rows and (C - k) // stride + 1 window columns.
For each window with top-left corner (r0, c0) = (i * stride, j * stride):
- Go through the window's rows from top to bottom.
- For each row, take the slice
row[c0:c0+k]and compute its maximumm. - If
mis strictly greater than the best value so far (or nothing has been recorded yet), storem, the current row, and the column of the first occurrence ofminside that slice (row.index(m, c0, c0 + k)). - After the last row, append
[best, best_row, best_col]to the output.
Why it is correct
- Coverage: the largest valid
iis(R - k) // stride, so the last window ends at rowr0 + k - 1 <= R - 1; the next one would not fit. The same holds for columns. - Maximum: the window maximum is the largest of its per-row maxima, and every row of the window is examined.
- Tie-break: let
Mbe the window maximum andr*the first row containing it. Earlier rows have smaller maxima, so they cannot block recording atr*. Later rows have maxima at mostM, and since the comparison is strict they never overwrite the stored position. Inside rowr*,indexreturns the first (smallest) column in the window range. So the reported cell is the lexicographically smallest(row, col)holdingM. - Negatives: using
Noneas the initial state avoids a wrong default such as0. - Empty case: checking
kagainst both dimensions first avoids producing shapes like[[]].
Complexity
Let P be the number of windows.
- Time:
O(P * k^2); each window readsk^2cells, and theindexcall adds at mostO(k)per row. - Space:
O(P)for the output, plusO(k)for the temporary row slice.
Reference solution
from typing import List
def window_max_with_position(grid: List[List[int]], k: int, stride: int) -> List[List[List[int]]]:
R, C = len(grid), len(grid[0])
if k > R or k > C:
return []
out = []
for i in range((R - k) // stride + 1):
r0 = i * stride
line = []
for j in range((C - k) // stride + 1):
c0 = j * stride
best = None
br = bc = 0
for r in range(r0, r0 + k):
row = grid[r]
m = max(row[c0:c0 + k])
if best is None or m > best:
best = m
br = r
bc = row.index(m, c0, c0 + k)
line.append([best, br, bc])
out.append(line)
return out