Created
October 30, 2020 04:52
-
-
Save Shaddyjr/78e6179825daac2b7bf4e66e4bb2ccc8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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