Photo by NeONBRAND on Unsplash

Yet Another HackerRank Problem — 2D Array Hourglass in Javascript

Clark Johnson
2 min readMay 11, 2020

--

As a developer, it’s important to keep the skills sharp with algorithm practice. The details for the problem detailed in this post can be found at https://www.hackerrank.com/challenges/2d-array/problem.

The problem begins with a 6 x 6 array, like this one:

1  1  1  0  0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0

We’ll be looking for subsets of this array that follow this pattern of 7 numbers:

a b c
d
e f g

This hourglass pattern occurs 16 times within the array.

The goal is to find the sum of the numbers in each of the hourglass patterns and return the maximum sum.

For example, in the 2D array above, the first pattern is

1 1 1
1
1 1 1

and the sum is 7.

For the solution, let’s begin with the function declaration.

function hourglassSum(arr) {

}

The hourglassSum function expects an array of arrays.

Since the minimum value of any position is -9, the minimum value of the sum is -63.

function hourglassSum(arr) {
let max = -63
}

We’ll use a nested loop to evaluate the sums of all the hourglass patterns (4 on each row) for all the possible rows (4 rows).

After each sum is computed, it will be compared to the current maximum sum and will replace that sum if it is greater.

Finally, after all iterations are complete, the maximum sum will be returned.

Here’s the completed function:

function hourglassSum(arr) {
let max = -63
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
let sum = 0
sum = (arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2])
max = max < sum ? sum : max
}
}
return max
}

While this problem is rated as easy, it’s still healthy to stretch the mind. Let me know if you find any unnecessary code or a more efficient path to the solution.

Happy coding!

--

--

Clark Johnson

Full stack software engineer seeking projects using React, Ruby on Rails, Javascript, when I’m not at a baseball game