Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

The largest island

Medium · Target 15 minutes · Graphs · Type asked atAmazonGoogleMeta

A grid holds 1 for land and 0 for water. An island is a group of land cells connected through shared sides (up, down, left, right). Return the number of cells in the largest island, or 0 if there is no land.

Examples

InputOutputWhy
grid = [[0,0,1,0,0],[1,1,1,0,0],[0,1,0,0,1],[0,0,0,1,1]]5The island on the left has five cells; the one on the right has three.
grid = [[1,0,1],[0,1,0],[1,0,1]]1Diagonal cells are not connected: five islands of one cell.
grid = [[1,1,1],[1,0,1],[1,1,1]]8A ring of eight cells around a lake.

Constraints

  • 1 ≤ rows, cols ≤ 50
  • Every cell is 0 or 1

Hints

Hint 1

This is the components template with f = "count the cells" and g = "maximum".

Hint 2

Scan the grid; at each land cell not yet visited, flood the whole island, counting cells as you mark them.

Hint 3

Keep the largest count seen.

Where people lose marks

  • Counting diagonal neighbours as connected.
  • Counting a cell each time it is reached rather than once, when it is first marked.
  • Returning the number of islands instead of the size of the largest one.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.