Sum of Distinct Values on Maximum-Sum Square Borders in a Matrix
Company: Capital One
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Online Assessment
Overview: A matrix problem that considers every k by k square in a grid, sums the values on each square's border, and asks for the sum of the distinct values appearing on all borders that reach the maximum border sum. It tests border enumeration without double counting corners, tie handling across squares, and value de-duplication.
Read the full Capital One Machine Learning Engineer interview experience this question came from
Constraints
- 1 <= m, n <= 100, where m = len(matrix) and n = len(matrix[0]); every row has length n
- 1 <= matrix[i][j] <= 10^4
- 1 <= k <= min(m, n)
Examples
Input: ([[1, 1, 1, 1], [1, 9, 9, 1], [1, 1, 1, 1]], 3)
Expected Output: 10
Explanation: Source Example 1: the two 3 x 3 squares tie at border sum 16, each with one 9 inside its border; the union of border values {1, 9} sums to 10.
Input: ([[3, 8], [8, 1]], 1)
Expected Output: 8
Explanation: Source Example 2: with k = 1 two cells holding 8 tie for the maximum, and the value 8 counts once.
Hints
- Each border cell counts once: for k = 1 and k = 2 every cell of the square is on the border, and a corner belongs to both a border row and a border column but is still counted only once.
- Several squares can share the maximum border sum, so you need the maximum before you know which borders to collect values from.
- Distinctness is by value, not by position: two cells holding the same number contribute that number once.