PPractick

DSA interview question

Making a Large Island

Hard · Data structures · Topics: graph, dfs, dsu, matrix

The problem

A land-reclamation project can fill at most one water cell (turn a 0 into 1) on an n × n map. What's the largest island (4-directionally connected land) that can result? Trying every flip and re-running a flood fill is O(n⁴). Instead:

  1. Label every existing island once with an ID and record its size.
  2. For each water cell, the island formed by filling it has size 1 plus the sizes of the distinct islands around it, since the same island may touch it on several sides.
  3. Also consider making no flip at all.

Example: [[1,0], [0,1]] → 3.

Function signature

int largestIsland(vector<vector<int>> grid);  // n x n of 0/1

Test cases

InputOutputExplanation
[[1,0],[0,1]]3Filling either 0 joins both islands
[[1,1],[1,0]]4
[[1,1],[1,1]]4Nothing to fill
[[1,0,1],[0,0,0],[1,0,1]]3An edge-centre cell joins two corners
[[0,0],[0,0]]1Only the filled cell

(Confirm: at most one cell is changed; connectivity is 4-directional.)

How interviewers phrase it

Clarifying questions to ask

  1. At most one flip, so zero flips is allowed? (Yes: an all-land grid is valid.)
  2. 4-directional? (Yes.)
  3. How large? (n up to 500, so an O(n²) method is needed.)

Follow-ups to expect

  1. "Why label islands first?"
  2. "Why track distinct IDs?"
  3. "What if the grid has no water?"
  4. "DSU alternative?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in