← Questions

Making a large island

0
MetaCodingLast asked Dec 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Dec 2025. It tests graphs, dfs and grids.

You get an n x n binary grid where 1 is land and 0 is water. An island is a group of land cells connected up, down, left or right. You may change at most one 0 into a 1. Return the size of the largest island you can end up with.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • largest_island(grid: list[list[int]]) -> int.

Example

[[1, 0],
 [0, 1]]         ->  3     # flip either 0 to join both islands

[[1, 1],
 [1, 0]]         ->  4

[[1, 1],
 [1, 1]]         ->  4     # nothing to flip

[[0, 0],
 [0, 0]]         ->  1

[[1, 1, 0],
 [0, 0, 1],
 [1, 0, 1]]      ->  5     # flip (1, 1) or (0, 2) to join the top island and the right one

Constraints

  • 1 <= n <= 500, so anything near O(n^4) is too slow.

Clarifying questions

  • Is the flip optional ("at most one")?
  • Is connectivity 4-directional only?
  • What is the answer for an all-water grid, and for an all-land grid?
  • May I modify the grid?

What a strong answer covers

  • The brute force, flipping each water cell and re-measuring with BFS, is O(n^4) and too slow.
  • Label each island once with an id (DFS, BFS or union-find) and record its size.
  • For each water cell, look at its up to four neighbours, collect the distinct island ids, and add their sizes plus one. Using a set avoids counting the same island twice when it touches the cell on two sides.
  • The answer is the best such value, or the largest island if there is no water.
  • O(n^2) time and space.
  • Tests: all water, all land, one water cell surrounded by one island, a cell that touches the same island twice, a cell joining four islands.

Follow-ups

  • You may flip up to k cells. How does the problem change?
  • Cells are added one at a time; report the largest island after each addition (union-find).
  • Islands also connect diagonally.

Where it's asked

  • Meta · AI-enabled coding · Last asked Dec 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

graphs · dfs · grids

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding