Making a large island

Asked atMeta
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an n x n binary matrix grid, it is allowed to change at most one 0 to 1. A group of connected 1s forms an island, where two 1s are connected if they share one of their sides.

Return the size of the largest island in the grid after applying this operation.

Input: grid = [[1,0],[0,1]] Output: 3 Explanation: We change any one 0 to 1 and connect two 1s, then we get an island with maximum area = 3.

Input: grid = [[1,1],[1,1]] **Output: **4 Explanation: The largest island already exists with size 4.

Input: grid = [[1,1],[1,0]]

  • 1 <= n <= 500
  • 0 <= grid[i][j] <= 1

cpp

class Solution {
public:
    int largestIsland(vector<vector<int>>& grid) {
        
    }
};

java

class Solution {
    public int largestIsland(int[][] grid) {
      
    }
}

python

class Solution:
    def largestIsland(self, grid):

javascript

class Solution {
   largestIsland(grid) {
       
    }
}

csharp

public class Solution
{
    public int LargestIsland(int[][] grid)
    {
      
    }
}

go

func largestIsland(grid [][]int) int {
	
}
Solve on LeetCode →
Stuck? Show a way to structure it+
  1. 01Restate the objective and identify the key invariant
  2. 02Develop the component labeling and one flip approach step by step
  3. 03Walk through a small adversarial example
  4. 04Cover boundary conditions before coding
  5. 05State time and space Big-O and explain the trade-off

Reference answer

Then expect these follow-ups

  • How would the approach change for streaming input?

    Tests: constraint adaptation

  • Which boundary case is most likely to break an implementation?

    Tests: implementation extension

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question