Island Perimeter solution explained

To find an island's perimeter on a grid of land and water, count land cells and count pairs of land cells that share a side. Each land cell brings four edges and each shared side hides two of them, so the perimeter is 4 × land - 2 × shared. One pass over the grid gives O(R × C) time and O(1) extra space, and if you already know one land cell, a walk over just that island costs time proportional to the island's size.

By Published 7 min read

The problem, in plain terms

A map is drawn as a grid of square cells, where 1 is land and 0 is water, and everything outside the grid is water too. Land cells connect only through their sides, not their corners. The usual version promises a single island. Return the total length of its border, where each cell side has length 1 and counts when land is on one side and water or the map edge is on the other.

0 1 1 0      7 land cells
1 1 0 0      6 shared sides between land cells
0 1 1 1      perimeter = 4 x 7 - 2 x 6 = 16

1 1 1        8 land cells around one water cell (a lake)
1 0 1        8 shared sides
1 1 1        formula gives 4 x 8 - 2 x 8 = 16
             outer coastline alone is 12; the lake shore adds 4
Two grids, made up for this page

Clarify three things: whether there can be more than one island (and whether you want the total or one island's perimeter), whether lakes can exist, and whether the lake shoreline should be counted. Most phrasings say one island with no lakes, in which case every approach on this page agrees.

Why it appears in interviews

It sits next to the island-counting grid problems but rewards a different instinct. Many candidates reach for depth-first search out of habit, when a counting argument solves it in a few lines with no visited set. Interviewers like seeing whether you can find the formula, explain why it is right, and then say when a traversal would still be the better choice.

A direct first approach: check four sides of every land cell

For each land cell, look at its four neighbors. Each neighbor that is water, or that falls outside the grid, adds one to the perimeter. This is already O(R × C) and easy to defend, so it is a perfectly good first answer. Its only weakness is that it inspects each shared side twice, once from each cell, and needs four bounds checks per land cell.

The tidier approach: 4 × land minus 2 × shared

Think of every land cell as contributing four sides. When two land cells sit side by side, the side between them is not coastline, and it was counted once by each of them, so subtract 2 for every such pair. To count each pair exactly once, check only the neighbor above and the neighbor to the left of each land cell. The function below scans the whole grid, so it returns the total coastline of every island, lake shores included.

def island_perimeter(grid):
    land = shared = 0
    for r, row in enumerate(grid):
        for c, cell in enumerate(row):
            if cell == 1:
                land += 1
                if r > 0 and grid[r - 1][c] == 1:   # neighbor above
                    shared += 1
                if c > 0 and row[c - 1] == 1:       # neighbor to the left
                    shared += 1
    return 4 * land - 2 * shared
Python: whole-grid count. Sums every land-to-water edge, for all islands and lakes.

When the grid is huge and mostly water but you are handed one cell of the island, scanning every cell wastes time. A traversal from that cell visits only the island. For each cell popped, every side that faces water or the map edge adds one, and every unvisited land neighbor is pushed. This version returns the perimeter of that one island only, again including the shore of any lake inside it.

// Walks only the island that contains (sr, sc); cost grows with the island,
// not with the whole grid.
function perimeterFrom(grid, sr, sc) {
  const rows = grid.length, cols = grid[0].length;
  const seen = new Set([sr * cols + sc]);
  const stack = [[sr, sc]];
  let edges = 0;
  while (stack.length > 0) {
    const [r, c] = stack.pop();
    for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
      if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || grid[nr][nc] === 0) {
        edges++;                       // this side faces water or the map edge
      } else if (!seen.has(nr * cols + nc)) {
        seen.add(nr * cols + nc);
        stack.push([nr, nc]);
      }
    }
  }
  return edges;
}
JavaScript: perimeter of the single island containing (sr, sc), found by iterative DFS.

Encoding a cell as r × cols + c gives a single number to store in the set, which is cheaper than building a string key for every cell.

When lakes should not count

If the question defines perimeter as the outer coastline only, neither function above is enough on its own, because both count the shore of enclosed water. One clean fix is to imagine a ring of water around the grid, flood the outside water from that ring, and then count only land sides that face outside water or the edge. On the second example grid that gives 12 instead of 16. Raising this before the interviewer does shows you thought about what the formula really measures.

Complexity summary

R rows, C columns, A = land cells in the island
ApproachWhat it returnsTimeExtra space
Four sides per land cellAll land-to-water edges in the gridO(R × C)O(1)
4 × land - 2 × sharedAll land-to-water edges in the gridO(R × C)O(1)
DFS from a known land cellEdges of that one islandO(A)O(A)
Flood outside water, then countOuter coastline onlyO(R × C)O(R × C)
R rows, C columns, A = land cells in the island. Scroll sideways on a small screen.

Edge cases to test

  • A single land cell, which has perimeter 4.
  • A grid with no land, which should return 0 from the counting version.
  • Land touching every border, so the map edge counts as coastline.
  • A one-row or one-column grid.
  • A ring of land around a lake, to confirm which definition you are computing.
  • Two separate islands, if the question allows them.

Pitfalls

  • Counting shared sides from all four directions and still subtracting 2 for each, which removes every pair twice. Look only up and left, or subtract 1 per neighbor counted.
  • Forgetting that the map edge is coastline, by only counting sides that face a 0 cell.
  • Reaching for DFS and a visited set when a single scan is simpler, then spending the interview on bookkeeping.
  • Assuming the whole-grid formula gives one island's perimeter when there are several islands.
  • Treating corner contact as a shared side.

How to explain it out loud

Fictional example

Getting to the formula
Candidate
Each land cell has four sides. A side is coastline unless another land cell is on the other side of it.
Candidate
So I'll count land cells and count adjacent land pairs. Each pair hides two sides, one from each cell, so the answer is four times land minus two times pairs. I only look up and left so I count each pair once.
Candidate
It's one pass with constant extra space. If the grid were huge and you gave me a cell on the island, I'd walk just the island instead. And if there could be a lake, this counts its shore, so I'd want to check whether that's intended.

Visiting one connected region of a grid is the core of Flood Fill, which repaints the region instead of measuring its border. Minimum Path Sum is another grid problem that a single row-by-row pass solves, this time with dynamic programming.

Where Natively fits in your prep

Counting problems are won by the explanation, so rehearse the sentence about each pair hiding two sides until it comes out cleanly. On a Mac or Windows computer, Natively can read a grid problem from a screenshot during practice, propose the lake and multi-island questions to ask, and help you debug either version. Reviewing the transcript afterward shows whether your explanation matched your code. See the AI interview assistant.

Questions people ask

How do you solve Island Perimeter?

Count land cells and count pairs of land cells that share a side, checking only up and left so each pair is counted once. The perimeter is four times the land count minus two times the shared count.

What is the time complexity of Island Perimeter?

O(R × C) for one pass over the grid with O(1) extra space. A DFS from a known land cell costs time proportional to the island's size instead.

Do you need DFS for Island Perimeter?

No. A counting pass is enough when the grid holds one island. DFS helps when you are given one cell of a single island in a large grid, or when several islands must be measured separately.

Does the formula count lakes?

Yes. Both the formula and the per-side check count the shore of water enclosed by the island. If only the outer coastline should count, flood the outside water first and count sides facing it.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP