Skip to content
DATA STRUCTURE
DATA STRUCTURE

Learn everything about Data structures.

  • Algorithms
  • DSA
  • Array
  • Stack
  • Queue
  • Matrix
  • Programs
DATA STRUCTURE

Learn everything about Data structures.

HackerRank 2D Array DS solution in Python

YASH PAL, May 14, 2025May 21, 2025

Today we are going to solve the HackerRank 2D array DS problem using python programming language. Given a 6×6 2D array, arr, an hourglass is a subset of values with indices falling in the following pattern:

a b c
d
e f g
There are 16 hourglasses in a 6×6 array. The hourglass sum is the sum of the values in an hourglass. Calculate the hourglass sum for every hourglass in arr, then print the maximum hourglass sum.

Hackerrank 2D Array DS problem solution in python
2D Array DS

Problem solution in Python

ar = []
for i in range(6):
    ar.append(list(map(int, input().split())))

def get_hg(x, y):
    hg = []
    xend = x+3
    for i in range(y, y+3):
        if i == y + 1:
            hg.append([0, ar[i][x+1],0])
        else:
            hg.append(ar[i][x:xend])

    return hg

hg = []
for x in range(3 + 1):
    for y in range(3 + 1):
        hg.append(get_hg(x, y))

hgsums = []
for h in hg:
    s = 0
    for j in h:
        s += sum(j)
    hgsums.append(s)

print(max(hgsums))

HackerRank 2D Array DS solution in Python 2.

# Enter your code here. Read input from STDIN. Print output to STDOUT
DIM = 6

matrix = []

def hourglass(r, c):
    return matrix[r][c] + sum(matrix[r - 1][c - 1: c + 2]) + sum(matrix[r + 1][c - 1: c + 2])

for i in range(DIM):
    matrix.append(map(int, raw_input().split()))

hourglass_vals = []
for r in range(1, 5):
    for c in range(1, 5):
        hourglass_vals.append(hourglass(r, c))
        
print max(hourglass_vals)

Other solutions

  • HackerRank Dynamic Array solution in Python

Also read

  • Array in Data Structure
  • Python Libraries for Machine Learning
array DS problems arraysprograms

Post navigation

Previous post
Next post
  • HackerRank Dynamic Array Solution in Python
  • HackerRank 2D Array DS solution in Python
  • HackeRank Array – DS solution in Python
  • Streaming Demystified: How Much Data Does Your Favorite Show Really Use?
  • Parenthesis Matching program in C programming
  • HackerRank Dynamic Array Solution in Python
  • HackerRank 2D Array DS solution in Python
  • HackeRank Array – DS solution in Python
  • Streaming Demystified: How Much Data Does Your Favorite Show Really Use?
  • Parenthesis Matching program in C programming
  • About US
  • Contact US
  • Data Structures and algorithms tutorials
  • Digital Communication Tutorials
  • DMCA
  • HackerRank All Algorithms problems solutions
  • HackerRank C problems solutions
  • HackerRank C++ problems solutions
  • HackerRank Java solutions
  • HackerRank Python solutions
  • Human Values Tutorials
  • Internet of Things Tutorials
  • Privacy Policy
©2025 DATA STRUCTURE | WordPress Theme by SuperbThemes