Leetcode #827: Making A Large Island
In this guide, we solve Leetcode #827 Making A Large Island in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Depth-First Search, Breadth-First Search, Union Find, Array, Matrix
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Python Solution
class Solution:
def largestIsland(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int):
p[i][j] = root
cnt[root] += 1
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n and grid[x][y] and p[x][y] == 0:
dfs(x, y)
n = len(grid)
cnt = Counter()
p = [[0] * n for _ in range(n)]
dirs = (-1, 0, 1, 0, -1)
root = 0
for i, row in enumerate(grid):
for j, x in enumerate(row):
if x and p[i][j] == 0:
root += 1
dfs(i, j)
ans = max(cnt.values() or [0])
for i, row in enumerate(grid):
for j, x in enumerate(row):
if x == 0:
s = set()
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n:
s.add(p[x][y])
ans = max(ans, sum(cnt[root] for root in s) + 1)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.