Distinct Value Sum Across Peak-Score Square Ring Windows
Arrays & HashingAuto-graded · 25 test casesLast updated
Tests 2D prefix sums, border enumeration, multi-way tie tracking, and cross-frame value deduplication on square ring-shaped windows of a matrix.
Problem
You have a grid of integers with R rows and C columns, and a window side length w.
A window is any w × w block of cells aligned to the grid axes. Its top-left corner can be placed at any cell (r, c) satisfying r + w ≤ R and c + w ≤ C.
The ring of a window is the subset of its cells that lie on its outermost layer: the top row, the bottom row, the leftmost column, or the rightmost column of that block. Cells strictly inside the outermost layer are not part of the ring. Every cell on the ring is counted exactly once when computing the ring sum.
Your task:
- Compute the ring sum of every valid window and find the peak ring sum — the largest ring sum achieved by any window.
- Collect the values of all ring cells belonging to any window that achieves the peak ring sum.
- Return the sum of the distinct values in that collection.
Values from windows whose ring sum falls short of the peak do not contribute, even if those same cells happen to sit on the ring of a peak window.
Rules
- When
w = 1, the ring is the single cell (it is simultaneously its own top row, bottom row, left column, and right column). - When
w = 2, every cell in the window is on its ring; there are no interior cells. - Distinctness is by value: if the number
5appears on the rings of three different peak windows, it is added to the result only once. Likewise, if the same cell belongs to multiple peak windows' rings, its value is still counted once. - Negative integers are included as-is when they appear as ring values of peak windows.
Constraints
1 ≤ R, C ≤ 100- Every row has exactly
Celements. 1 ≤ w ≤ min(R, C)-10^4 ≤ grid[i][j] ≤ 10^4- The absolute value of the answer fits in a 32-bit signed integer (≤ 50,005,000).
Examples
Example 1
Input: peak_ring_distinct_sum([[1, 2, 3, 4], [5, 100, 7, 8], [9, 10, 11, 12]], 3)
Output: 150
Example 2
Input: peak_ring_distinct_sum([[1, 1, 1], [1, 5, 1], [1, 1, 1]], 2)
Output: 6
Example 3
Input: peak_ring_distinct_sum([[3, 7], [7, -2]], 1)
Output: 7
Hints
Hint 1
Compute the sum of any rectangular region in O(1) by building a 2D prefix-sum table first. Then express the ring sum as the full w×w square sum minus the (w−2)×(w−2) interior square sum — watch out for the cases where that interior is empty.
Hint 2
Track the peak ring sum and the top-left corners of all windows that achieve it in a single pass. Start your best-so-far variable at None rather than 0 so that all-negative grids are handled correctly.
Hint 3
Once you know the peak windows, mark every ring cell of each one in a boolean grid (top row, bottom row, left column, right column). Then sweep the grid: collect matrix values at marked cells into a set, and return the sum of that set.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution breaks into two clean phases connected by a 2D prefix-sum table.
Phase 0 — Build the prefix-sum table
P[i][j] holds the sum of all grid cells in rows 0..i-1 and columns 0..j-1. With this table, the sum of any rectangular region can be retrieved in O(1) using the standard inclusion-exclusion formula:
rect_sum(r1, c1, r2, c2) = P[r2][c2] - P[r1][c2] - P[r2][c1] + P[r1][c1]
Phase 1 — Find the peak ring sum
For each valid top-left corner (r, c), the ring sum is:
ring_sum = full_square_sum − interior_square_sum
The full square covers rows [r, r+w) and columns [c, c+w). The interior (the cells not on the ring) covers rows [r+1, r+w-1) and columns [c+1, c+w-1). When w ≤ 2, the interior is empty so nothing is subtracted — this handles w = 1 (single cell) and w = 2 (all cells on the ring) correctly.
A single pass over all valid corners tracks the running peak value and accumulates every corner that matches it. Initialising best = None rather than 0 ensures all-negative grids are handled correctly.
Phase 2 — Collect distinct ring values
For each peak corner, the four sides of its ring (top row, bottom row, left column, right column) are marked in a boolean grid. Marking rather than immediately collecting values means a cell shared by two overlapping peak windows is processed once. Then a single scan of the boolean grid adds each marked cell's value into a Python set, which automatically deduplicates by value. Returning sum(vals) gives the final answer.
Why it is correct
- The ring-as-square-minus-interior identity counts every border cell exactly once because border and interior cells partition the full window.
- Tracking corners rather than recomputing borders during phase 2 keeps the two concerns separate and makes the tie-handling logic easy to audit.
- Using a
setfor the final collection satisfies the "distinct by value" requirement regardless of how many peak windows share a value or how many cells hold that value.
Complexity
Let K = number of peak windows.
- Prefix table: O(R·C)
- Enumerating windows: O(R·C), O(1) per window
- Marking ring cells: O(K·w); worst case every window is a peak window (constant grid), giving O(R·C·w) ≈ 10^6 operations at the given limits
- Final scan: O(R·C)
Overall: O(R·C + K·w) time, O(R·C) space.
Edge cases
| Situation | Behaviour |
|---|---|
w = 1 | Every cell is its own window; peak windows are cells with the maximum value; answer equals that value |
w = 2 | No interior subtraction; all four cells of each window are on its ring |
| All-negative grid | best = None start ensures the true maximum is found |
| Many tied peak windows | Marking deduplicates cells; set deduplicates values |
| A cell on one peak ring but inside another peak window | It is still included because the problem asks for the union of rings |
Reference solution
from typing import List
def peak_ring_distinct_sum(grid: List[List[int]], w: int) -> int:
R, C = len(grid), len(grid[0])
# Build 2D prefix-sum table P where P[i][j] = sum of grid[0..i-1][0..j-1]
P = [[0] * (C + 1) for _ in range(R + 1)]
for i in range(R):
row = grid[i]
acc = 0
for j in range(C):
acc += row[j]
P[i + 1][j + 1] = P[i][j + 1] + acc
def rect_sum(r1, c1, r2, c2):
# Sum of grid cells in rows [r1, r2) and columns [c1, c2)
return P[r2][c2] - P[r1][c2] - P[r2][c1] + P[r1][c1]
# Phase 1: find the peak ring sum and record all windows that achieve it
best = None
peak_corners = []
for r in range(R - w + 1):
for c in range(C - w + 1):
s = rect_sum(r, c, r + w, c + w)
if w > 2:
# Subtract the interior square to get the ring sum only
s -= rect_sum(r + 1, c + 1, r + w - 1, c + w - 1)
if best is None or s > best:
best = s
peak_corners = [(r, c)]
elif s == best:
peak_corners.append((r, c))
# Phase 2: mark every ring cell belonging to any peak window
mark = [[False] * C for _ in range(R)]
for r, c in peak_corners:
# Top and bottom rows of the ring
for j in range(c, c + w):
mark[r][j] = True
mark[r + w - 1][j] = True
# Left and right columns of the ring
for i in range(r, r + w):
mark[i][c] = True
mark[i][c + w - 1] = True
# Collect distinct values at marked cells and return their sum
vals = set()
for i in range(R):
for j in range(C):
if mark[i][j]:
vals.add(grid[i][j])
return sum(vals)