Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

Introduction to Island Pattern

Core idea

How it works

Recognize it when

The template

Variants in this chapter

Watch out for

How this compares with nearby patterns

Key Takeaways

You are given a grid of land and water. Count how many separate islands it holds, where an island is a group of land cells joined up, down, left or right.

1 1 0 0
1 0 0 1        there are 3 islands
0 0 1 0

The grid is a graph in disguise. Every cell is a node, and every cell is joined to the neighbour above it, below it, to its left and to its right. Nobody hands you an adjacency list, because you can work out the neighbours from the coordinates.

That means the whole problem is the graph traversal you already know, run in a loop:

  1. Walk every cell in the grid.
  2. When you find land you have not seen, you have found a new island, so add one to the count.
  3. From that cell, visit everything joined to it and mark it all as seen.
  4. Carry on walking. Anything already marked belongs to an island you have counted.

The traversal is what stops you counting the same island four times.

Core idea

The Island pattern applies a graph traversal to a grid, where a cell's neighbours are its four sides.

Each traversal claims one whole island. The outer loop finds new starting points, and the inner traversal consumes everything reachable from one of them.

How it works

The inner traversal can be recursive or use a queue. The steps are the same:

  1. Check that the cell is inside the grid. If not, stop.
  2. Check that the cell is land and not yet visited. If not, stop.
  3. Mark it visited.
  4. Repeat for the cell above, below, left and right.
Three separate islands, since land joins only up, down, left and right.
Three separate islands, since land joins only up, down, left and right.

Every cell is visited at most once, so the time is O(R * C) for R rows and C columns. The space is the same in the worst case. A single island can fill the grid, and the traversal has to hold it.

Marking is what makes this correct. Most solutions overwrite the land cell with water instead of keeping a separate visited grid, which saves memory. Ask the interviewer whether the input may be modified before doing that.

Recognize it when

Use the Island pattern when the question shows these signs.

  • The input is a two dimensional grid of cells.
  • Cells are joined to their neighbours by position rather than by a given list of edges.
  • The question asks about regions, areas, groups, or shapes inside the grid.
  • The wording includes island, region, flood, or surrounded.
  • You need to know how many separate connected areas the grid contains.

It is not this pattern when:

  • The connections come as a list of pairs. That is a normal graph.
  • The grid is a maze and you need the shortest route. Use Breadth First Search and count the rounds, which is the graph pattern rather than this one.
  • Each cell's answer is built from cells already computed, with no exploration. That is Dynamic Programming.

The template

function countIslands(grid):
    count = 0

    for row from 0 to rows - 1:
        for col from 0 to cols - 1:
            if grid[row][col] is land:
                count = count + 1
                sink(grid, row, col)           # claim this whole island

    return count


function sink(grid, row, col):
    if row or col is outside the grid:  return
    if grid[row][col] is not land:      return

    grid[row][col] = water                     # mark before recursing

    sink(grid, row + 1, col)
    sink(grid, row - 1, col)
    sink(grid, row, col + 1)
    sink(grid, row, col - 1)

Two guards do the real work. The bounds check keeps you inside the grid, and the land check stops you revisiting. Both must come before anything else, and the marking must happen before the four calls or the recursion will loop.

Variants in this chapter

VariantWhat changesProblems in this chapter
Count the regionsadd one for each traversal you startNumber of Islands
Measure a regionthe traversal returns a size instead of nothingBiggest Island
Repaint a regionthe traversal writes a new value as it goesFlood Fill
Exclude regions touching the edgetraverse from the border first, and remove those regionsNumber of Closed Islands
Compare or transform regionsthe traversal records a shape or a perimeterProblem Challenge 1, Problem Challenge 2, Problem Challenge 3

The border trick in row four is worth learning on its own. When a question asks for regions that do not touch the edge, it is almost always easier to remove the ones that do.

Watch out for

  • Checking bounds after reading the cell. Reading grid[row][col] before testing the coordinates raises an error at the edges. The order of the two guards is not a matter of taste.
  • Marking after the recursive calls. Mark the cell before you explore its neighbours, or two cells will keep calling each other.
  • Counting diagonals as neighbours. Most questions mean four directions. Some mean eight. Read the question and say which one you assumed.
  • Overwriting the input without asking. Sinking islands destroys the grid. That is usually fine, and it is still worth saying out loud.
  • Deep recursion on a large grid. A grid that is all land recurses once per cell, which can overflow the stack. A queue avoids that.

How this compares with nearby patterns

If the question asks forUse
regions or areas in a gridIsland (Matrix Traversal)
connections given as a list of pairsGraphs
the shortest route through a mazeBreadth First Search, counting rounds
grouping without needing any routeUnion Find

This pattern is not really separate from Graphs. It is the same traversal with the adjacency list replaced by four coordinate offsets. If you can write one, you can write the other.

Key Takeaways

  • A grid is a graph where each cell's neighbours are the four cells beside it.
  • The outer loop finds new islands and the inner traversal claims them.
  • Guard the bounds first, then the cell value, then mark before recursing.
  • Time and space are both O(R * C) in the worst case.
  • Removing the regions that touch the border is the usual route to "closed" or "surrounded" questions.

Let's apply it to the first problem, Number of Islands.

Z

zaid

· 3 years ago

title

Show 1 reply
A

Arul Prakash

· 4 years ago

hi

On This Page

Core idea

How it works

Recognize it when

The template

Variants in this chapter

Watch out for

How this compares with nearby patterns

Key Takeaways