💡 The algorithm correctly ignores smaller sums after sliding.
reconstruct
Finish scanning all rows and columns, return max_sum
All valid hourglass positions have been processed. The maximum hourglass sum found is 13, which is returned as the final answer.
💡 Returning max_sum completes the algorithm and provides the solution.
Line:return max_sum
💡 The algorithm efficiently found the maximum hourglass sum by sliding and comparing sums.
def max_hourglass_sum_sliding(matrix):
n = len(matrix) # STEP 1
m = len(matrix[0]) # STEP 1
max_sum = float('-inf') # STEP 1
for i in range(n - 2): # STEP 1
# Compute initial hourglass sum for first position in row i # STEP 2-3
current_sum = (matrix[i][0] + matrix[i][1] + matrix[i][2] +
matrix[i+1][1] +
matrix[i+2][0] + matrix[i+2][1] + matrix[i+2][2]) # STEP 2-3
if current_sum > max_sum: # STEP 4
max_sum = current_sum # STEP 4
for j in range(1, m - 2): # STEP 5-15
# Slide hourglass right by updating sum # STEP 5-6
current_sum -= (matrix[i][j-1] + matrix[i+1][j] + matrix[i+2][j-1]) # STEP 5
current_sum += (matrix[i][j+2] + matrix[i+1][j+1] + matrix[i+2][j+2]) # STEP 6
if current_sum > max_sum: # STEP 7, 9, 11, 13, 15
max_sum = current_sum # STEP 7, 9, 11, 13, 15
return max_sum # STEP 16
# Example usage:
matrix = [
[1,2,3,0,0],
[0,0,0,0,0],
[2,1,4,0,0],
[0,0,0,0,0],
[1,1,0,1,0]
]
print(max_hourglass_sum_sliding(matrix)) # Output: 13
📊
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
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
Step 2: Note that the if-condition has not yet been applied
The total before subtracting the center element is 30.
Final Answer:
Option C -> Option C
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
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.
Step 2: After swap, mat[1][2] becomes 8
Thus, mat[1][2] = 8 after transpose.
Final Answer:
Option A -> Option A
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
Step 1: Identify loops and operations
Outer loops iterate over all m*n cells. For each cell, 8 neighbors are checked in constant time.
Step 2: Calculate total operations
Total operations = m*n*8 = O(m*n), since 8 is constant.
Final Answer:
Option D -> Option D
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
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.
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.
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
Step 1: Understand matrix shape constraints
In-place transpose by swapping only works for square matrices because indices map symmetrically.
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.
Final Answer:
Option C -> Option C
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 unknownstrongwhile earning +1 Grip toward your certificate.