Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1568: Minimum Number of Days to Disconnect Island

In this guide, we solve Leetcode #1568 Minimum Number of Days to Disconnect 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.

Leetcode

Problem Statement

You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, Array, Matrix, Strongly Connected Component

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 = [[0,1,1,0],[0,1,1,0],[0,0,0,0]] Output: 2 Explanation: We need at least 2 days to get a disconnected grid. Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.

Python Solution

class Solution: def minDays(self, grid: List[List[int]]) -> int: if self.count(grid) != 1: return 0 m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] == 1: grid[i][j] = 0 if self.count(grid) != 1: return 1 grid[i][j] = 1 return 2 def count(self, grid): def dfs(i, j): grid[i][j] = 2 for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and grid[x][y] == 1: dfs(x, y) m, n = len(grid), len(grid[0]) cnt = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: dfs(i, j) cnt += 1 for i in range(m): for j in range(n): if grid[i][j] == 2: grid[i][j] = 1 return cnt

Complexity

The time complexity is O(V+E). The space complexity is O(V).

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.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy