Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created October 30, 2020 04:52
Show Gist options
  • Save Shaddyjr/78e6179825daac2b7bf4e66e4bb2ccc8 to your computer and use it in GitHub Desktop.
Save Shaddyjr/78e6179825daac2b7bf4e66e4bb2ccc8 to your computer and use it in GitHub Desktop.
# source: https://www.hackerrank.com/challenges/3d-surface-area/problem
# video: https://youtu.be/tIG0GF2EqjE
def surfaceArea(A):
n_rows = len(A)
n_cols = len(A[0])
total = (n_rows * n_cols) * 2 # top and bottom
for row_i in range(n_rows): # O(n)
for col_i in range(n_cols): # O(m)
val = A[row_i][col_i]
# handle row
if row_i - 1 < 0:
prev_row_val = 0
else:
prev_row_val = A[row_i - 1][col_i]
total += abs(val - prev_row_val)
# handle col
if col_i - 1 < 0:
prev_col_val = 0
else:
prev_col_val = A[row_i][col_i - 1]
total += abs(val - prev_col_val)
# add last col element again
if col_i == n_cols - 1:
total += val
# add last row element again
if row_i == n_rows - 1:
total += sum(A[row_i])
return total # Total Complexity = O(n * m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment