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 the 2 x 2 subgrid 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:

  1. Find the largest border sum achieved across every valid frame_size x frame_size subgrid in matrix.
  2. 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, where R = len(matrix) and C = len(matrix[0]), and every row in matrix has length C.
  • 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

  1. Understand what a square frame and its border mean

    A frame of size frame_size is any frame_size x frame_size square subgrid inside matrix. 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:

    1. Find all winning frames: Compute the border sum of every frame_size x frame_size frame (counting each border cell once) and keep every frame that achieves the maximum border sum.
    2. 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).
  2. 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 contains 4 * (f - 1) cells when f >= 2 (or 1 cell when f == 1). Even at R = C = 100, the product (101 - f)^2 * 4 * (f - 1) reaches its peak at f = 34, where 67 * 67 * 132 = 592,548 cells are visited across all frames. Two passes of roughly 6 * 10^5 reads finish in milliseconds in Python, so walking each border directly is fast enough — and lets us focus completely on accuracy.

  3. 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 .. right
    

    Notice how all three small sizes behave cleanly:

    • size == 1: top and bottom are 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, and range(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 cells
    
  4. Phase 1: score every frame and keep all ties

    For a frame_size x frame_size square to stay inside the grid, its bottom row top + frame_size - 1 can be at most num_rows - 1, so top runs from 0 through num_rows - frame_size (range(num_rows - frame_size + 1)), and similarly left runs over range(num_cols - frame_size + 1).

    Two details matter when tracking the maximum:

    • Initialize best_sum = None rather than 0. If every number in matrix is negative, every border sum is negative, and starting at 0 would leave best_frames empty!
    • Whenever border_sum == best_sum, append (top, left) to best_frames instead 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))
    
  5. Phase 2: deduplicate winning border values with a set

    Once best_frames holds every winning (top, left) position, we walk get_border_cells(top, left, frame_size) for only those frames and insert each matrix[row][col] into a Python set.

    A set stores 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 in distinct_border_values once. 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)
    
  6. 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 = 18
    
  7. Complete 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 the B border cells of each of the F frames once, and Phase 2 walks only the winning frames (at most F frames, with O(1) average hash-set insertion per cell). Under R, C <= 100, F * B is at most 592,548 (at R = C = 100, f = 34), so both passes run in a few milliseconds.
  • Space: O(R * C). best_frames stores at most F <= R * C (top, left) pairs, distinct_border_values stores at most R * C unique numbers from the grid, and get_border_cells allocates a temporary list of B <= 2 * (R + C) coordinates per frame.

Edge cases

  • frame_size == 1: Every individual cell is its own 1 x 1 frame; get_border_cells returns that single cell once (avoiding double-counting top and bottom), and the answer equals the maximum value in the matrix.
  • frame_size == 2: Every 2 x 2 square has zero interior cells, so all 4 of its cells belong to the border.
  • All-negative matrices: Starting best_sum = None ensures negative border sums (such as -8) still become best_sum, and negative values in distinct_border_values are summed with their minus signs intact.
  • Multiple tied maximum frames: Every frame reaching best_sum is kept in best_frames, and overlapping or repeated values across them are counted once via the set.
  • Repeated value on a single border: A 2 x 2 frame [[2, 2], [2, 2]] has border sum 8 in Phase 1, while Phase 2 deduplicates {2} to return 2.
  • 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 -50 is properly excluded.

Common mistakes

  • Double-counting the four corners: Looping all four edges over their full length frame_size adds (top, left), (top, right), (bottom, left), and (bottom, right) twice each. In [[5, 0, 0, 0], [0, 0, 0, 7], [0, 0, 0, 0]] with frame_size = 3, double-counting 5 inflates the left frame's score from 5 to 10, wrongly beating the right frame's 7.
  • Forgetting size == 1 in border enumeration: Without if size == 1: return [(top, left)], adding both (top, col) and (bottom, col) lists the single cell twice because top == bottom.
  • Initializing best_sum = 0: When every frame has a negative border sum, no frame beats 0, leaving best_frames empty and wrongly returning 0.
  • Keeping only the first maximum frame: Updating only on border_sum > best_sum drops 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 score 8, not 2); 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 + 1 so the last valid frame touching row num_rows - 1 is included.

Alternative approaches

  • 2D prefix sums for O(1) border scoring in Phase 1: A 2D prefix sum is a precomputed table P[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 in O(1) time using four additions/subtractions. A frame's border sum equals its full f x f square sum minus its inner (f - 2) x (f - 2) square sum (when f >= 3), reducing Phase 1 from O(F * B) to O(R * C) time.

Follow-up questions

  • How would you optimize the runtime if the grid dimensions grew to 2000 x 2000? At R = C = 2000 and frame_size = 668, walking every border takes ~4.7 * 10^9 cell reads, which will time out. Phase 1 becomes O(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 +1 at start and -1 at end + 1 so 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 takes O(1) per winning frame, giving O(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 a visited_cells set instead of storing matrix[row][col] in a value set, then sum matrix[r][c] over (r, c) in visited_cells. On Example 2 ([[4, 2, 5, -3], [2, 6, 1, 8]], frame_size = 2), the two winning 2 x 2 frames cover the six coordinates (0..1, 0..2), so coordinate-based uniqueness would include both 2s at (0, 1) and (1, 0) for a total of 4 + 2 + 5 + 2 + 6 + 1 = 20 instead of 18.
  • 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 over f from 1 to min(R, C) and all (top, left) positions, computing each border sum in O(1) and recording winning (top, left, f) triples in O(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 in O(1) per winner, then sweep the grid once in O(R * C) to collect distinct values from all marked cells.

Follow-up questions

Similar questions

More Capital One interview questions

All 268 Capital One questions →