Bird
Raised Fist0
Interview PrepmatricesmediumAmazonGoogle

Maximum Sum of an Hourglass

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize variables and start first row

Set matrix dimensions and initialize max_sum to negative infinity. Prepare to process the first row where hourglass can fit (i=0).

💡 Initialization sets the stage for scanning the matrix and ensures max_sum can be updated correctly.
Line:n = len(matrix) m = len(matrix[0]) max_sum = float('-inf') for i in range(n - 2):
💡 We only consider rows where a full hourglass can fit, i.e., up to n-3.
📊
Maximum Sum of an Hourglass - Watch the Algorithm Execute, Step by Step
Watching each sum calculation and pointer movement helps you understand how the sliding window technique optimizes the search for the maximum hourglass sum without recomputing sums from scratch.
Step 1/16
·Active fill★Answer cell
setup
i
0
1
2
3
4
Result: "-∞"
fill_row
j
0
1
2
3
4
Result: "-∞"
fill_row
j
0
1
2
3
4
Result: "-∞"
compare
j
0
1
2
3
4
Result: 13
shrink
i
0
j
1
2
3
4
Result: 13
expand
i
0
j
1
2
3
4
Result: 13
compare
i
0
j
1
2
3
4
Result: 13
fill_row
j
0
i
1
2
3
4
Result: 13
compare
j
0
i
1
2
3
4
Result: 13
shrink
0
j
1
2
3
4
Result: 13
compare
0
j
1
2
3
4
Result: 13
fill_row
j
0
1
i
2
3
4
Result: 13
compare
j
0
1
i
2
3
4
Result: 13
shrink
0
j
1
i
2
3
4
Result: 13
compare
0
j
1
i
2
3
4
Result: 13

Key Takeaways

✓ Sliding window technique efficiently updates hourglass sums by adding and removing only the changed elements.

This insight is hard to see from code alone because the sum update lines are compact; visualization shows exactly which elements are removed and added.

✓ The algorithm only computes full sums once per row and then slides horizontally, saving computation time.

Watching the initial sum calculation separate from sliding clarifies the dependency and order of operations.

✓ max_sum updates only when a strictly larger sum is found, ensuring the maximum is tracked correctly.

Seeing the comparisons step-by-step helps understand why some sums do not update max_sum.

Practice

(1/5)
1. Consider the following Python function that computes the sum of the diagonals of a square matrix:
def diagonalSum(mat):
    total = 0
    n = len(mat)
    for i in range(n):
        total += mat[i][i] + mat[i][n - 1 - i]
    if n % 2 == 1:
        total -= mat[n//2][n//2]
    return total

matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(diagonalSum(matrix))
What is the value of total after the loop completes but before the if-condition is applied?
easy
A. 15
B. 25
C. 30
D. 45

Solution

  1. Step 1: Trace the loop iterations

    For i=0: total = 0 + mat[0][0] + mat[0][2] = 0 + 1 + 3 = 4 For i=1: total = 4 + mat[1][1] + mat[1][1] = 4 + 5 + 5 = 14 For i=2: total = 14 + mat[2][2] + mat[2][0] = 14 + 9 + 7 = 30
  2. Step 2: Note that the if-condition has not yet been applied

    The total before subtracting the center element is 30.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sum of diagonals before center correction is 30 [OK]
Hint: Sum both diagonals first, then adjust center if needed [OK]
Common Mistakes:
  • Forgetting to subtract center element once
  • Double counting center element
  • Off-by-one in indices
2. Consider the following code that transposes a square matrix in-place:
def transpose(matrix):
    n = len(matrix)
    if n == 1:
        return
    for i in range(n):
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose(mat)
print(mat)
What is the value of mat[1][2] after the function call?
easy
A. 8
B. 6
C. 4
D. 5

Solution

  1. Step 1: Trace swaps affecting mat[1][2]

    Initially, mat[1][2] = 6. The swap occurs when i=1, j=2 swapping mat[1][2] and mat[2][1]. mat[2][1] is 8.
  2. Step 2: After swap, mat[1][2] becomes 8

    Thus, mat[1][2] = 8 after transpose.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Swapping upper triangle elements swaps mat[1][2] with mat[2][1] correctly [OK]
Hint: Trace swaps only in upper triangle [OK]
Common Mistakes:
  • Confusing indices i and j during swap
  • Off-by-one errors in loops
  • Assuming mat[1][2] remains unchanged
3. What is the time complexity of the optimal in-place Game of Life solution that encodes states using 4 integer values, given an m x n board?
medium
A. O(m + n) since only rows and columns are scanned
B. O(m * n * 8 * 2) due to checking neighbors twice
C. O(m * n * m * n) because each cell checks all other cells as neighbors
D. O(m * n) because each cell and its neighbors are processed in constant time

Solution

  1. Step 1: Identify loops and operations

    Outer loops iterate over all m*n cells. For each cell, 8 neighbors are checked in constant time.
  2. Step 2: Calculate total operations

    Total operations = m*n*8 = O(m*n), since 8 is constant.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Neighbor checks are constant per cell -> linear in board size [OK]
Hint: Neighbor checks are constant per cell, so linear overall [OK]
Common Mistakes:
  • Mistaking neighbor checks as nested loops over entire board
  • Counting neighbor checks twice incorrectly
  • Confusing linear scan with quadratic complexity
4. Identify the bug in the following in-place Game of Life code snippet that causes incorrect neighbor counts and final states.
medium
A. Line checking neighbors lacks boundary condition checks causing index errors
B. Final loop does not convert encoded states back to original states
C. Neighbor counting incorrectly includes dead cells as live
D. Encoding uses wrong integers for state transitions

Solution

  1. Step 1: Examine neighbor counting loop

    The code checks board[x][y] without verifying if x,y are within valid indices, risking index errors or invalid counts.
  2. Step 2: Confirm other parts are correct

    Final decoding loop correctly converts 2->0 and 3->1; encoding uses correct integers; neighbor counting excludes dead cells properly.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing boundary check causes incorrect neighbor counts or runtime errors [OK]
Hint: Always check boundaries before accessing neighbors [OK]
Common Mistakes:
  • Forgetting boundary checks in neighbor loops
  • Not finalizing encoded states after first pass
  • Misusing encoding integers
5. Suppose you need to transpose a non-square matrix (m x n) in-place, but the matrix is stored as a flat array in row-major order. Which approach correctly handles this scenario?
hard
A. Transpose in-place by swapping elements only in the upper triangle of the matrix.
B. Use the same in-place swapping approach as for square matrices, swapping elements symmetrically across the diagonal.
C. Create a new matrix of size n x m and copy elements accordingly, since in-place transpose is not possible for non-square matrices.
D. Use a recursive approach to swap elements in cycles to achieve in-place transpose.

Solution

  1. Step 1: Understand matrix shape constraints

    In-place transpose by swapping only works for square matrices because indices map symmetrically.
  2. Step 2: For non-square matrices, in-place transpose is not possible

    Because the shape changes from m x n to n x m, a new matrix must be created to hold the transposed data.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Non-square matrix transpose requires extra space due to dimension change [OK]
Hint: In-place transpose only works for square matrices [OK]
Common Mistakes:
  • Trying to swap elements in-place for non-square matrices
  • Assuming upper triangle swaps apply to rectangular matrices
  • Ignoring dimension changes after transpose
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard