Island Perimeter (LeetCode 463): Count Edges, Not Cells

Island Perimeter is a classic warm-up grid question. You get a 2D grid of 0s (water) and 1s (land). There's exactly one island and no lakes inside it. Return the island's perimeter.

The key observation

Each land cell contributes 4 edges. Every time two land cells touch, they share an edge, and that shared edge removes 2 from the total (one side from each cell). So:

perimeter = 4 × land_cells − 2 × shared_edges

To avoid double counting, only look up and left (or down and right) from each land cell.

Python solution

⎗
✓
def islandPerimeter(grid):
    rows, cols = len(grid), len(grid[0])
    land = shared = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 1:
                land += 1
                if r > 0 and grid[r - 1][c] == 1:
                    shared += 1
                if c > 0 and grid[r][c - 1] == 1:
                    shared += 1
    return 4 * land - 2 * shared

Time is O(rows × cols) and extra space is O(1).

Alternative: DFS

You can also run a DFS from any land cell and add 1 every time you step out of bounds or into water. It works, but it's more code and uses recursion stack space, so mention it as an option and go with the counting approach.

How to talk through it in an interview

  1. Restate the constraints: one island, no internal lakes, grid up to 100 × 100.
  2. Start with the "4 per cell" idea, then explain why shared edges need subtracting.
  3. Point out that checking only two neighbors avoids double counting.
  4. Walk a tiny example: two horizontal cells give 4 × 2 − 2 × 1 = 6.

Follow-ups to expect

  • Multiple islands: the same formula still gives the total perimeter of all islands.
  • Lakes allowed: the counting formula still works, because a lake's border is still water next to land.
  • Max perimeter island: label islands with DFS or union-find, then count per label.

Practice tip

Grid questions reward saying your counting rule out loud before coding. If you want feedback on how clearly you explain it during practice, an AI tool for job interviews can help you rehearse. Disclosure: I work on Linkjob AI.

Edit

Pub: 03 Nov 2026 18:03 UTC

Views: 8