DEV Community

Philip Thomas
Philip Thomas

Posted on

Demystifying Algorithms: The Hourglass Sum Problem

What is the Hourglass Sum Problem?

The hourglass sum problem involves finding the maximum "hourglass" sum in a 2D matrix. An hourglass is a specific shape in the matrix, consisting of values in the following pattern:

a b c
  d
e f g
Enter fullscreen mode Exit fullscreen mode

The goal is to calculate the sum of all elements in every possible hourglass and return the maximum sum.

This problem is often used to test proficiency in array manipulation, nested loops, and problem-solving skills in coding interviews.


The Technical View

  • Time Complexity: (O(n^2)).
    • The algorithm iterates over all rows and columns that can form a valid hourglass, performing constant-time calculations for each.
  • Space Complexity: (O(1)).
    • The algorithm operates directly on the input matrix without requiring extra space.

How It Works

To solve the hourglass sum problem:

  1. Iterate through all valid hourglass "top-left" positions in the matrix.
  2. For each position, calculate the sum of the hourglass formed by the elements at:
    • Top: Three elements in the current row.
    • Middle: Single element from the next row.
    • Bottom: Three elements from the row after that.
  3. Keep track of the maximum hourglass sum encountered during these iterations.

A Fifth-Grader's Summary

Imagine you’re looking at a grid of numbers and drawing hourglass shapes over it. For each shape, you add up the numbers inside and write down the sum. At the end, you pick the largest number you wrote down—that’s the answer!


Real-World Example

The hourglass sum problem is a simplified version of real-world challenges in image processing and grid-based data analysis. For example:

  • Detecting patterns in digital images.
  • Analyzing heatmaps to find regions with the highest intensity.
  • Solving matrix-based puzzles in games.

Examples with Code, Detailed Iterations, and Optimized Patterns


1. Maximum Hourglass Sum

Problem: Find the maximum hourglass sum in a 6x6 2D matrix.

Code:

public static int HourglassSum(int[][] arr)
{
    int maxSum = int.MinValue;

    for (int i = 0; i <= 3; i++) // Rows
    {
        for (int j = 0; j <= 3; j++) // Columns
        {
            // Calculate hourglass sum
            int top = arr[i][j] + arr[i][j + 1] + arr[i][j + 2];
            int middle = arr[i + 1][j + 1];
            int bottom = arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
            int hourglassSum = top + middle + bottom;

            // Update maxSum
            maxSum = Math.Max(maxSum, hourglassSum);
        }
    }

    return maxSum;
}
Enter fullscreen mode Exit fullscreen mode

What Happens in Each Iteration:

  1. The outer loop (i) iterates over rows where hourglasses can fit (0 to 3 in a 6x6 matrix).
  2. The inner loop (j) iterates over columns where hourglasses can fit (0 to 3).
  3. At each valid top-left corner ((i, j)), calculate the hourglass sum:
    • Top: Sum of elements at ([i][j]), ([i][j+1]), and ([i][j+2]).
    • Middle: Element at ([i+1][j+1]).
    • Bottom: Sum of elements at ([i+2][j]), ([i+2][j+1]), and ([i+2][j+2]).
  4. Compare the current hourglass sum with maxSum and update if larger.

2. Matrix Example

Problem: Test the algorithm on the following matrix:

1  1  1  0  0  0
0  1  0  0  0  0
1  1  1  0  0  0
0  0  2  4  4  0
0  0  0  2  0  0
0  0  1  2  4  0
Enter fullscreen mode Exit fullscreen mode

Code:

int[][] arr = new int[][]
{
    new int[] {1, 1, 1, 0, 0, 0},
    new int[] {0, 1, 0, 0, 0, 0},
    new int[] {1, 1, 1, 0, 0, 0},
    new int[] {0, 0, 2, 4, 4, 0},
    new int[] {0, 0, 0, 2, 0, 0},
    new int[] {0, 0, 1, 2, 4, 0},
};

Console.WriteLine(HourglassSum(arr));
Enter fullscreen mode Exit fullscreen mode

What Happens in Each Iteration:

  1. The algorithm calculates hourglass sums for all 16 possible hourglasses in the matrix.
  2. Some sample calculations:
    • Hourglass starting at ([0][0]): (1+1+1+1+1+1+1 = 7).
    • Hourglass starting at ([3][2]): (2+4+4+2+1+2+4 = 19).

Final Result: 19.


3. Handling Edge Cases

Problem: Handle matrices where:

  • All elements are negative.
  • The matrix is non-square (but large enough to form hourglasses).

Code:

int[][] arr = new int[][]
{
    new int[] {-1, -1, -1, -1, -1, -1},
    new int[] {-1, -1, -1, -1, -1, -1},
    new int[] {-1, -1, -1, -1, -1, -1},
    new int[] {-1, -1, -1, -1, -1, -1},
    new int[] {-1, -1, -1, -1, -1, -1},
    new int[] {-1, -1, -1, -1, -1, -1},
};

Console.WriteLine(HourglassSum(arr));
Enter fullscreen mode Exit fullscreen mode

What Happens:

  • The algorithm calculates hourglass sums, all of which will be negative.
  • maxSum starts at int.MinValue and updates to the largest (least negative) hourglass sum.

Final Result: Largest negative hourglass sum.


Conclusion

The hourglass sum problem is a classic exercise in matrix traversal and array manipulation. By breaking the problem into smaller steps and iterating systematically, you can efficiently compute the maximum sum for any valid matrix.

Mastering this problem equips you with the skills to tackle more advanced array problems and enhances your ability to think algorithmically!

Top comments (0)