Distinct Border Value Sum Across Maximum-Sum Square Frames
Hard · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given an R x C grid of integers matrix and a positive integer frame_size, evaluate every axis-aligned frame_size x frame_size square subgrid within matrix.
def max_frame_distinct_sum(matrix: list[list[int]], frame_size: int) -> int:
For any frame_size x frame_size subgrid anchored at top-left coordinate (r, c) (with 0 <= r <= R - frame_size and 0 <= c <= C - frame_size), its perimeter (or border) consists solely of the cells along its top row, bottom row, leftmost column, and rightmost column. Strict interior cells—those not touching any of the four outer edges of the subgrid—are excluded:
- When
frame_size == 1, the subgrid contains just a single cell, which forms its entire border once. - When
frame_size == 2, all four cells of the2 x 2subgrid lie on its border. - Each cell on the border contributes its value once to that subgrid's border sum (corner cells are not counted twice, while identical numbers at different border coordinates both contribute to the border sum).
Compute the answer in two steps:
- Find the largest border sum achieved across every valid
frame_size x frame_sizesubgrid inmatrix. - Gather all cell values lying on the borders of every subgrid whose border sum equals that global maximum, deduplicate those numbers by value, and return the sum of the unique integers.
Additional rules:
- Uniqueness is evaluated by integer value over the combined borders of all tied maximum-sum subgrids: if a number appears multiple times on one winning border or across several tied winning borders, include it once in the final total.
- Subgrids whose border sum is strictly smaller than the maximum are disregarded completely, even when some of their border coordinates fall inside a winning subgrid's interior.
- Negative numbers keep their sign during both border-sum comparison and unique-value summation.
Examples
Example 1
Input: matrix = [
[2, 4, 1, 6],
[3, 50, 5, 9],
[7, 4, 8, 10]
], frame_size = 3
Output: 88
Two 3 x 3 subgrids fit inside this 3 x 4 grid:
- Anchored at (0, 0) (columns 0..2): its border values are 2, 4, 1, 3, 5, 7, 4, 8, giving a border sum of 34 (50 sits in the center interior cell (1, 1), so it does not count).
- Anchored at (0, 1) (columns 1..3): its border values are 4, 1, 6, 50, 9, 4, 8, 10, giving a border sum of 92 (50 now lies on the left edge, while 5 sits in the interior).
Only the second subgrid attains the maximum border sum 92. Because 4 appears twice on that winning border, the unique border values are {1, 4, 6, 8, 9, 10, 50}, which sum to 88.
Example 2
Input: matrix = [
[4, 2, 5, -3],
[2, 6, 1, 8]
], frame_size = 2
Output: 18
Three 2 x 2 subgrids exist:
- (0, 0) has border cells 4, 2, 2, 6 with sum 14.
- (0, 1) has border cells 2, 5, 6, 1 with sum 14.
- (0, 2) has border cells 5, -3, 1, 8 with sum 11.
The first two subgrids tie for the highest border sum (14), while the third (11) is ignored. Pooling the border values from both winning subgrids yields {1, 2, 4, 5, 6}, whose sum is 18.
Example 3
Input: matrix = [
[-6, -2],
[-9, -2]
], frame_size = 1
Output: -2
With frame_size = 1, each individual cell forms a 1 x 1 subgrid whose border sum equals the cell itself. The highest border sum is -2, reached at (0, 1) and (1, 1). The set of unique winning border values is {-2}, returning -2.
Constraints
1 <= R, C <= 100, whereR = len(matrix)andC = len(matrix[0]), and every row inmatrixhas lengthC.1 <= frame_size <= min(R, C)-10^4 <= matrix[r][c] <= 10^4- The absolute value of the returned sum is at most
50,005,000(fits within a 32-bit signed integer).
Step-by-step walkthrough
Understand what a square frame and its border mean
A frame of size
frame_sizeis anyframe_size x frame_sizesquare subgrid insidematrix. Only its border (its outer rim: first row, last row, first column, and last column) counts — any interior cells strictly inside the square are ignored:frame_size = 1 frame_size = 2 frame_size = 3 frame_size = 4 # # # # # # # # # # # # # . # # . . # # # # # . . # # # # # (# = border cell counted once, . = interior cell ignored)Our task naturally splits into two phases:
- Find all winning frames: Compute the border sum of every
frame_size x frame_sizeframe (counting each border cell once) and keep every frame that achieves the maximum border sum. - Sum distinct winning border values: Collect all numbers sitting on the borders of those winning frames, remove duplicate values, and return the sum of those unique integers (keeping negative signs as-is).
- Find all winning frames: Compute the border sum of every
Check whether walking every border directly is fast enough
Before reaching for complicated grid precomputation, let's check the size of the input (
1 <= R, C <= 100).Let
f = frame_size. A frame's top-left corner(top, left)can sit at(R - f + 1) * (C - f + 1)positions. Each border contains4 * (f - 1)cells whenf >= 2(or1cell whenf == 1). Even atR = C = 100, the product(101 - f)^2 * 4 * (f - 1)reaches its peak atf = 34, where67 * 67 * 132 = 592,548cells are visited across all frames. Two passes of roughly6 * 10^5reads finish in milliseconds in Python, so walking each border directly is fast enough — and lets us focus completely on accuracy.List every border cell once without double-counting corners
The easiest bug in border problems is adding all four full edges of length
size, which counts the four corner cells twice and distorts which frame wins. We avoid that by splitting the rim into two non-overlapping pieces:4 x 4 frame at (top, left) with bottom = top + 3, right = left + 3: T T T T <-- full top row: (top, col) for col in left .. right L . . R <-- middle sides: (row, left) & (row, right) L . . R for row in top + 1 .. bottom - 1 B B B B <-- full bottom row: (bottom, col) for col in left .. rightNotice how all three small sizes behave cleanly:
size == 1:topandbottomare the exact same row, so looping over both would list(top, left)twice. Returning[(top, left)]immediately fixes it.size == 2:range(top + 1, bottom)is empty, so only the 2-cell top row and 2-cell bottom row are returned (all 4 cells, once each).size >= 3: Top and bottom rows include the 4 corners, andrange(top + 1, bottom)adds only the non-corner side cells, skipping the interior completely.
def get_border_cells(top: int, left: int, size: int) -> List[Tuple[int, int]]: """Return every (row, col) on the outline of a size x size frame, each listed once.""" # When size == 1, top and bottom are the same row; return the single cell once. if size == 1: return [(top, left)] bottom = top + size - 1 right = left + size - 1 # cells: unique (row, col) coordinates along the frame's border cells = [] # Add the entire top row and entire bottom row (this includes all 4 corners). for col in range(left, right + 1): cells.append((top, col)) cells.append((bottom, col)) # Add the left and right columns strictly between top and bottom to skip corners. for row in range(top + 1, bottom): cells.append((row, left)) cells.append((row, right)) return cellsPhase 1: score every frame and keep all ties
For a
frame_size x frame_sizesquare to stay inside the grid, its bottom rowtop + frame_size - 1can be at mostnum_rows - 1, sotopruns from0throughnum_rows - frame_size(range(num_rows - frame_size + 1)), and similarlyleftruns overrange(num_cols - frame_size + 1).Two details matter when tracking the maximum:
- Initialize
best_sum = Nonerather than0. If every number inmatrixis negative, every border sum is negative, and starting at0would leavebest_framesempty! - Whenever
border_sum == best_sum, append(top, left)tobest_framesinstead of ignoring ties, because every tied maximum frame contributes its border values in Phase 2.
best_sum = None best_frames = [] for top in range(num_rows - frame_size + 1): for left in range(num_cols - frame_size + 1): border_sum = 0 for row, col in get_border_cells(top, left, frame_size): border_sum += matrix[row][col] if best_sum is None or border_sum > best_sum: best_sum = border_sum best_frames = [(top, left)] elif border_sum == best_sum: best_frames.append((top, left))- Initialize
Phase 2: deduplicate winning border values with a set
Once
best_framesholds every winning(top, left)position, we walkget_border_cells(top, left, frame_size)for only those frames and insert eachmatrix[row][col]into a Pythonset.A
setstores each unique integer value at most once — whether a number repeats twice on the same border or appears on two overlapping winning borders, it stays indistinct_border_valuesonce. Numbers from non-winning frames (or sitting purely in a winning frame's interior) are never visited here.distinct_border_values = set() for top, left in best_frames: for row, col in get_border_cells(top, left, frame_size): distinct_border_values.add(matrix[row][col]) answer = sum(distinct_border_values)Trace Example 1 and Example 2 step by step
Example 1: matrix (3 x 4), frame_size = 3 [ 2, 4, 1, 6 ] [ 3, 50, 5, 9 ] [ 7, 4, 8, 10 ] Frame at (0, 0) (cols 0..2): Frame at (0, 1) (cols 1..3): [ 2, 4, 1 ] [ 4, 1, 6 ] [ 3, (50), 5 ] <-- 50 inside! [ 50, (5), 9 ] <-- 50 on left border! [ 7, 4, 8 ] [ 4, 8, 10 ] border_sum = 34 border_sum = 92 (WINNER) best_frames = [(0, 1)] distinct_border_values = {1, 4, 6, 8, 9, 10, 50} (4 counted once) -> sum = 88 Example 2: matrix = [[4, 2, 5, -3], [2, 6, 1, 8]], frame_size = 2 Frame (0, 0) sums to 4 + 2 + 2 + 6 = 14 (tied best) Frame (0, 1) sums to 2 + 5 + 6 + 1 = 14 (tied best) Frame (0, 2) sums to 5 - 3 + 1 + 8 = 11 (ignored) best_frames = [(0, 0), (0, 1)] distinct_border_values = {1, 2, 4, 5, 6} -> sum = 18Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def get_border_cells(top: int, left: int, size: int) -> List[Tuple[int, int]]: """Return every (row, col) on the outline of a size x size frame, each listed once.""" # When size == 1, top and bottom are the same row; return the single cell once. if size == 1: return [(top, left)] bottom = top + size - 1 right = left + size - 1 # cells: unique (row, col) coordinates along the frame's border cells = [] # Add the entire top row and entire bottom row (this includes all 4 corners). for col in range(left, right + 1): cells.append((top, col)) cells.append((bottom, col)) # Add the left and right columns strictly between top and bottom to skip corners. for row in range(top + 1, bottom): cells.append((row, left)) cells.append((row, right)) return cells def max_frame_distinct_sum(matrix: list[list[int]], frame_size: int) -> int: num_rows = len(matrix) num_cols = len(matrix[0]) # Phase 1: score every valid frame and keep all frames tied for the maximum sum. # Start best_sum at None (not 0) because every border sum in the grid can be negative. best_sum = None # best_frames: list of (top, left) corners tied for best_sum, e.g. [(0, 0), (0, 1)] best_frames = [] # The last valid top-left corner is (num_rows - frame_size, num_cols - frame_size). for top in range(num_rows - frame_size + 1): for left in range(num_cols - frame_size + 1): border_sum = 0 for row, col in get_border_cells(top, left, frame_size): border_sum += matrix[row][col] if best_sum is None or border_sum > best_sum: best_sum = border_sum best_frames = [(top, left)] elif border_sum == best_sum: best_frames.append((top, left)) # Phase 2: pool border values from all winning frames and sum each distinct value once. # distinct_border_values: set of unique integers across all winning borders, e.g. {1, 5} distinct_border_values = set() for top, left in best_frames: for row, col in get_border_cells(top, left, frame_size): distinct_border_values.add(matrix[row][col]) return sum(distinct_border_values)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine sliding a hollow wooden picture frame of size frame_size x frame_size across every valid position on a grid of numbers: you can only see the numbers directly underneath the four wooden edges of the frame, while any numbers inside the central hole are hidden. First, we check every valid spot to find the highest border sum and bookmark every position tied for first place; second, we toss every number visible under those winning frames' borders into a duplicate-removing bag (set) and sum what is inside the bag.
Two tempting shortcuts fail here: summing the entire frame_size x frame_size square includes hidden interior cells (which can both crown the wrong frame and leak interior values into the answer), while summing all four full edges of length frame_size counts the four corners twice (distorting border sums whenever corners hold large positive or negative numbers).
In Example 1 ([[2, 4, 1, 6], [3, 50, 5, 9], [7, 4, 8, 10]] with frame_size = 3), there are two 3 x 3 frames:
- Frame (0, 0) has border cells [2, 4, 1, 3, 5, 7, 4, 8] with sum 34 (50 sits in the center hole, so it is ignored).
- Frame (0, 1) has border cells [4, 1, 6, 50, 9, 4, 8, 10] with sum 92 (50 now sits on its left edge, while 5 is in the hole).
Only (0, 1) achieves the maximum 92; deduplicating the repeated 4 leaves {1, 4, 6, 8, 9, 10, 50}, which sums to 88.
Complexity
Let f = frame_size, F = (R - f + 1) * (C - f + 1) be the number of frames, and B be the number of border cells per frame (1 when f = 1, and 4 * (f - 1) when f >= 2).
- Time:
O(F * B). Phase 1 walks theBborder cells of each of theFframes once, and Phase 2 walks only the winning frames (at mostFframes, withO(1)average hash-set insertion per cell). UnderR, C <= 100,F * Bis at most592,548(atR = C = 100, f = 34), so both passes run in a few milliseconds. - Space:
O(R * C).best_framesstores at mostF <= R * C(top, left)pairs,distinct_border_valuesstores at mostR * Cunique numbers from the grid, andget_border_cellsallocates a temporary list ofB <= 2 * (R + C)coordinates per frame.
Edge cases
frame_size == 1: Every individual cell is its own1 x 1frame;get_border_cellsreturns that single cell once (avoiding double-countingtopandbottom), and the answer equals the maximum value in the matrix.frame_size == 2: Every2 x 2square has zero interior cells, so all 4 of its cells belong to the border.- All-negative matrices: Starting
best_sum = Noneensures negative border sums (such as-8) still becomebest_sum, and negative values indistinct_border_valuesare summed with their minus signs intact. - Multiple tied maximum frames: Every frame reaching
best_sumis kept inbest_frames, and overlapping or repeated values across them are counted once via theset. - Repeated value on a single border: A
2 x 2frame[[2, 2], [2, 2]]has border sum8in Phase 1, while Phase 2 deduplicates{2}to return2. - Extreme value inside a winning frame's interior: Even if a cell (such as
-50) sits on the border of a weaker frame and inside the interior of the winning frame, Phase 2 only visits border cells of winning frames, so-50is properly excluded.
Common mistakes
- Double-counting the four corners: Looping all four edges over their full length
frame_sizeadds(top, left),(top, right),(bottom, left), and(bottom, right)twice each. In[[5, 0, 0, 0], [0, 0, 0, 7], [0, 0, 0, 0]]withframe_size = 3, double-counting5inflates the left frame's score from5to10, wrongly beating the right frame's7. - Forgetting
size == 1in border enumeration: Withoutif size == 1: return [(top, left)], adding both(top, col)and(bottom, col)lists the single cell twice becausetop == bottom. - Initializing
best_sum = 0: When every frame has a negative border sum, no frame beats0, leavingbest_framesempty and wrongly returning0. - Keeping only the first maximum frame: Updating only on
border_sum > best_sumdrops tied frames that may hold additional distinct border values. - Deduplicating during Phase 1: Border sums in Phase 1 add every border cell (so four
2s score8, not2); deduplication by value happens only in Phase 2 across the winning borders. - Off-by-one on valid frame positions: The upper bound in
range(num_rows - frame_size + 1)requires+ 1so the last valid frame touching rownum_rows - 1is included.
Alternative approaches
- 2D prefix sums for
O(1)border scoring in Phase 1: A 2D prefix sum is a precomputed tableP[r][c]storing the sum of the rectangle from(0, 0)to(r - 1, c - 1), which lets us look up the sum of any axis-aligned rectangle inO(1)time using four additions/subtractions. A frame's border sum equals its fullf x fsquare sum minus its inner(f - 2) x (f - 2)square sum (whenf >= 3), reducing Phase 1 fromO(F * B)toO(R * C)time.
Follow-up questions
- How would you optimize the runtime if the grid dimensions grew to 2000 x 2000? At
R = C = 2000andframe_size = 668, walking every border takes ~4.7 * 10^9cell reads, which will time out. Phase 1 becomesO(R * C)using a 2D prefix sum table (outer_square_sum - inner_square_sum). For Phase 2, instead of walking each winning border cell by cell, use a difference array — an array where marking a range[start, end]adds+1atstartand-1atend + 1so a single left-to-right running sum reveals which cells have count> 0. Marking each winning frame's 2 horizontal segments in per-row difference arrays and 2 vertical segments in per-column difference arrays takesO(1)per winning frame, givingO(R * C)total time and space. - What would change if uniqueness were tracked by cell coordinates (row, col) rather than by integer value? In Phase 2, we would store
(row, col)tuples in avisited_cellsset instead of storingmatrix[row][col]in a value set, then summatrix[r][c]over(r, c)invisited_cells. On Example 2 ([[4, 2, 5, -3], [2, 6, 1, 8]],frame_size = 2), the two winning2 x 2frames cover the six coordinates(0..1, 0..2), so coordinate-based uniqueness would include both2s at(0, 1)and(1, 0)for a total of4 + 2 + 5 + 2 + 6 + 1 = 20instead of18. - How could you compute the result over all frame sizes from 1 up to min(R, C) simultaneously? Precompute one 2D prefix sum table in
O(R * C), then loop overffrom1tomin(R, C)and all(top, left)positions, computing each border sum inO(1)and recording winning(top, left, f)triples inO(R * C * min(R, C))time. In Phase 2, apply the per-row and per-column difference-array range markers for every winning(top, left, f)triple inO(1)per winner, then sweep the grid once inO(R * C)to collect distinct values from all marked cells.
Follow-up questions
- How would you optimize the runtime if the grid dimensions grew to 2000 x 2000?
- What would change if uniqueness were tracked by cell coordinates (row, col) rather than by integer value?
- How could you compute the result over all frame sizes from 1 up to min(R, C) simultaneously?
Similar questions
- Matrix Row and Rotation Commands
- Bash Script for Reproducible Python Virtual Environments
- Point Obstacles and Clear Span Queries
- Account Ledger and Top-Activity Leaderboard
- Circular Peak-and-Valley Array Check
- Elapsed Minutes Since Previous Departure
More Capital One interview questions
- Account Ledger and Top-Activity Leaderboard Medium
- Virtual Payment Cards: Trade-Offs, Validation Rules, and Filter Debugging Medium
- Virtual Payment Cards: Rule Validation, State Tracking, and Edge Cases Medium Pro
- Count Fixed-Length Subarrays Matching Neighbor Comparison Signs Medium Pro
- Ad Engagement and ISO-Week PivotTable Analysis Medium Pro
- Point Obstacles and Clear Span Queries Medium Pro
- Leading a Technical Product from Concept to Launch Medium Pro
- High-Impact Win, Production Failure, and Enabling Others Medium Pro
- TV Series Contract Renewal and Divestiture Economics Medium Pro
- Forward-Fill Log Dates for Peak Viewing Slot Medium Pro