Grokking Meta Coding Interview
Ask Author
Back to course home

0% completed

Vote For New Content
edisonfreire14
Simple approach O(m x n) time O(1) space

edisonfreire14

Aug 13, 2025

Key intuition:

If there is a island block (a 1 in the matrix) the perimeter of that singular block is 4 - the number of other island blocks it is connected to.

So if you go to every island block and check the 4 directions from it count out of the sides are connected then subtract that from 4 we know the perimeter of that block.

So if you do that for every island block and sum it up it will give you the perimeter for the island in the matrix. This in theory would work to find perimeter of multiple islands, if they had lakes too.

def findIslandPerimeter(self, matrix): # TODO: Write your code here rows = len(matrix) cols = len(matrix[0]) deltas = [(1,0),(-1,0),(0,1),(0,-1)] def check_around(i,j): connected = 0 for i_delta, j_delta in deltas: new_i = i + i_delta new_j = j + j_delta if 0<=new_i<rows and 0<=new_j<cols: if matrix[new_i][new_j] == 1: connected += 1 return 4 - connected perimeter = 0 for i in range(rows): for j in range(cols): if matrix[i][j]==1: perimeter += check_around(i,j) return perimeter

0

0

Comments
Comments

On this page