← Visualizers
Graphs · Component Labeling LeetCode 827

Making A Large Island / visualized

You can change at most one 0 to 1. The naive trap is re-flooding for every zero in O((mn)²). The optimal O(mn) way: Pass 1 labels each component with a unique ID and maps its area. Pass 2 tests flipping each 0 by summing distinct adjacent IDs via a Set.

Execution

idle
INVARIANT Two-Pass Component ID Invariant: Naive re-flooding is O((mn)²). Optimal is O(mn): Pass 1 tags each island with an ID (starting at 2) & saves its area in a Map. Pass 2 tests flipping each 0 by summing unique adjacent IDs via Set!
Press Run to begin.
0 / 0
Speed

Java · Pass 1 Pre-label & Pass 2 Lookup

scanning cell bridge candidate optimal bridge / full water / untouched
INTERVIEW SCRIPT

How to Explain Making A Large Island to an Interviewer

1. Discard the O((mn)²) Trap

"Do not re-flood for every zero. Flipping each zero and running DFS traverses overlapping islands repeatedly, resulting in an unacceptable $O((m \cdot n)^2)$ time."

2. Pass 1: Labeling Components

"In Pass 1, we run DFS on untouched 1s, tagging all cells in that island with a unique ID ($\ge 2$ to avoid colliding with 0 and 1). We record sizeMap[islandId] = size in $O(m \cdot n)$ time."

3. Pass 2: Deduplicating with Set

"In Pass 2, for each 0, we inspect its 4 neighbors. We insert neighbor IDs into a Set<Integer> to avoid double-counting if two sides touch the same island! Potential area = $1 + \sum_{\text{id} \in \text{seen}} \text{sizeMap}[\text{id}]$."

4. Edge Cases: All 1s & All 0s

"If the grid has no zeros, return $m \cdot n$. If the grid has no ones, flipping any zero produces 1. Total time and space are both optimal $O(m \cdot n)$."

O(m·n) time · O(m·n) space  ·  Pass 1 labels each component and memoizes its size in a hash table. Pass 2 tests every zero by inspecting its 4 orthogonal neighbours in O(1) time using a HashSet to avoid double-counting.