854. Making A Large Island
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the size of the largest island we can form in a grid by changing at most one 0 to a 1. An island is a 4-directionally connected group of 1s. Changing a 0 to a 1 can potentially merge multiple adjacent, but previously separate, islands into a single, larger one.
Solution
Making A Large Island in Python
import collections
class Solution:
def largestIsland(self, grid: list[list[int]]) -> int:
n = len(grid)
dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def bfs_paint(r, c, island_id):
"""Paints an island with island_id and returns its size using BFS."""
if not (0 <= r < n and 0 <= c < n and grid[r][c] == 1):
return 0
q = collections.deque([(r, c)])
grid[r][c] = island_id
size = 0
while q:
row, col = q.popleft()
size += 1
for dr, dc in dirs:
nr, nc = row + dr, col + dc
if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 1:
grid[nr][nc] = island_id
q.append((nr, nc))
return size
island_id = 2 # Start island IDs from 2
island_sizes = {} # {island_id: size}
max_area = 0
# Pass 1: Find, label, and size all islands
for r in range(n):
for c in range(n):
if grid[r][c] == 1:
size = bfs_paint(r, c, island_id)
island_sizes[island_id] = size
max_area = max(max_area, size)
island_id += 1
# Pass 2: Check every 0 to see the potential merged island size
for r in range(n):
for c in range(n):
if grid[r][c] == 0:
neighbor_islands = set()
for dr, dc in dirs:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] > 1:
neighbor_islands.add(grid[nr][nc])
potential_size = 1
for i_id in neighbor_islands:
potential_size += island_sizes[i_id]
max_area = max(max_area, potential_size)
# If max_area is 0, it means the grid was all 0s.
# The loops for 0s will set max_area to 1.
# If the grid was all 1s, max_area is n*n from pass 1.
# If n=1 and grid=[[0]], max_area becomes 1. So returning max_area is fine.
# But if the entire grid is 0, no islands are found in pass 1, so island_sizes is empty.
# max_area will remain 0 from pass 1. Then pass 2 will set it to 1 for the first 0.
# So max_area will be 1.
# If the grid is all 1's, max_area will be n*n.
# The only way max_area is 0 is if n=0, but n>=1.
# So we can just return max_area, but if it is 0, the grid must have been all 0s, and the ans is 1.
return max_area if max_area > 0 else 1
Making A Large Island in Java
class Solution {
public int largestIsland(int[][] grid) {
int n = grid.length;
int islandId = 2; // Start island IDs from 2
Map<Integer, Integer> islandSizes = new HashMap<>();
int maxArea = 0;
// Pass 1: Find all islands, label them, and record their sizes.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
int size = paintAndGetSize(grid, i, j, islandId);
islandSizes.put(islandId, size);
maxArea = Math.max(maxArea, size);
islandId++;
}
}
}
// Pass 2: Iterate through all 0s and calculate potential new island size.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
Set<Integer> neighborIslands = new HashSet<>();
int potentialSize = 1; // Start with 1 for the 0 we flip
int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int[] dir : dirs) {
int ni = i + dir[0];
int nj = j + dir[1];
if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] > 1) {
neighborIslands.add(grid[ni][nj]);
}
}
for (int id : neighborIslands) {
potentialSize += islandSizes.get(id);
}
maxArea = Math.max(maxArea, potentialSize);
}
}
}
// If the grid was all 0s, maxArea is 0 from Pass 1.
// Pass 2 makes it 1. If grid is all 1s, maxArea is n*n from Pass 1.
// So the calculated maxArea is correct.
// The only edge case is an empty grid (n=0), but constraints say n>=1.
// If grid is all 0s, maxArea will be 1, so if we return maxArea, it's correct.
// If the grid has no 1s, maxArea will be 0 after Pass 1. Pass 2 will find a 0 and calculate size 1.
// The `maxArea == 0 ? 1 : maxArea` logic is a safeguard for an all-0 grid, but the algorithm naturally finds 1.
// A simpler return is just maxArea, unless n*n is 0 and grid has no 1s.
// If grid is all 1s, maxArea = n*n. If all 0s, maxArea=1. So if n>0, maxArea > 0.
return maxArea == 0 ? 1 : maxArea;
}
private int paintAndGetSize(int[][] grid, int r, int c, int islandId) {
int n = grid.length;
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{r, c});
grid[r][c] = islandId;
int size = 0;
int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
while (!q.isEmpty()) {
int[] curr = q.poll();
size++;
for (int[] dir : dirs) {
int nr = curr[0] + dir[0];
int nc = curr[1] + dir[1];
if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 1) {
grid[nr][nc] = islandId;
q.offer(new int[]{nr, nc});
}
}
}
return size;
}
}
Making A Large Island in C++
class Solution {
public:
int largestIsland(vector<vector<int>>& grid) {
int n = grid.size();
int islandId = 2; // Start island IDs from 2 to avoid collision with 0 and 1
unordered_map<int, int> islandSizes;
int maxArea = 0;
// Pass 1: Find all islands, label them with a unique ID, and record their sizes.
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
int size = paintAndGetSize(grid, i, j, islandId);
islandSizes[islandId] = size;
maxArea = max(maxArea, size); // Update maxArea with the size of the current island
islandId++;
}
}
}
// Pass 2: Iterate through all 0s and calculate potential new island size by merging neighbors.
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) {
unordered_set<int> neighborIslands;
int potentialSize = 1; // Start with 1 for the 0 we flip
int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (auto& dir : dirs) {
int ni = i + dir[0];
int nj = j + dir[1];
if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] > 1) {
neighborIslands.insert(grid[ni][nj]);
}
}
for (int id : neighborIslands) {
potentialSize += islandSizes[id];
}
maxArea = max(maxArea, potentialSize);
}
}
}
// If maxArea is 0 after all passes, it means the grid was all 0s.
// In that case, Pass 2 would have made maxArea = 1.
// If the grid was all 1s, maxArea would be n*n from Pass 1.
// So, if n > 0 and the grid is all 0s, maxArea is 1. But if n=0, it's 0. Since n>=1, this is fine.
// A simpler way to think about it: if the grid is ALL zeros, maxArea starts at 0, and the first 0 checked in pass 2 will set it to 1. Correct.
// If the grid is ALL ones, maxArea becomes n*n in pass 1, and pass 2 is skipped. Correct.
// Thus, the value in maxArea is correct even without special checks at the end.
return maxArea == 0 ? 1 : maxArea;
}
private:
int paintAndGetSize(vector<vector<int>>& grid, int r, int c, int islandId) {
int n = grid.size();
queue<pair<int, int>> q;
q.push({r, c});
grid[r][c] = islandId;
int size = 0;
int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
while (!q.empty()) {
pair<int, int> curr = q.front();
q.pop();
size++;
for (auto& dir : dirs) {
int nr = curr.first + dir[0];
int nc = curr.second + dir[1];
if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 1) {
grid[nr][nc] = islandId;
q.push({nr, nc});
}
}
}
return size;
}
};
Making A Large Island in TypeScript
function largestIsland(grid: number[][]): number {
const n = grid.length;
let islandId = 2; // Start island IDs from 2
const islandSizes = new Map<number, number>();
let maxArea = 0;
// Helper function to paint an island and return its size using BFS
const paintAndGetSize = (r: number, c: number, id: number): number => {
const q: [number, number][] = [[r, c]];
grid[r][c] = id;
let size = 0;
const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];
while (q.length > 0) {
const [currR, currC] = q.shift()!;
size++;
for (const [dr, dc] of dirs) {
const nr = currR + dr;
const nc = currC + dc;
if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] === 1) {
grid[nr][nc] = id;
q.push([nr, nc]);
}
}
}
return size;
};
// Pass 1: Find all islands, label them, and record their sizes.
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
const size = paintAndGetSize(i, j, islandId);
islandSizes.set(islandId, size);
maxArea = Math.max(maxArea, size);
islandId++;
}
}
}
// Pass 2: Iterate through all 0s and calculate potential new island size.
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 0) {
const neighborIslands = new Set<number>();
let potentialSize = 1; // Start with 1 for the 0 we flip
const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];
for (const [dr, dc] of dirs) {
const ni = i + dr;
const nj = j + dc;
if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] > 1) {
neighborIslands.add(grid[ni][nj]);
}
}
for (const id of neighborIslands) {
potentialSize += islandSizes.get(id) || 0;
}
maxArea = Math.max(maxArea, potentialSize);
}
}
}
// If maxArea is 0, grid was all 0s. Return 1 as we can flip one 0.
// Since n>=1, grid has at least one cell.
return maxArea === 0 ? 1 : maxArea;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.