KatInterview

Sliding Window Maxima on a Grid With Source Positions

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingmatrixsliding-windowsimulation

Last 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 row i * stride, column j * stride, for all i, j >= 0.
  • A window is only used if it lies completely inside the grid. If the grid has R rows and C columns, the result has (R - k) // stride + 1 rows and (C - k) // stride + 1 columns.
  • Cells at the bottom or right edge that cannot be covered by a full window are simply ignored.
  • If k exceeds 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:

  • value is the maximum of the window with index (i, j),
  • row and col are 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) <= 100
  • 1 <= len(grid[r]) <= 100, and all rows have the same length
  • -10^9 <= grid[r][c] <= 10^9
  • 1 <= k <= 100
  • 1 <= 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.