Katkat

Count Islands and Return the Largest Island Size

OracleSoftware Engineer · Onsite

Last updated

Count four-connected islands and find the largest island using DFS or BFS, with correct visited-state handling and all-water behavior.

Given a two-dimensional land/water grid, return both the number of islands and the size of the largest island. An island is a maximal group of land cells connected horizontally or vertically.

Implement island_stats(grid: int[][]) -> int[] and return [island_count, largest_size].

Constraints & Assumptions

  • The grid is rectangular, with 1 through 500 rows and columns.
  • Every entry is 0 for water or 1 for land. Diagonal contact does not connect islands.
  • If there is no land, return [0, 0].
  • Each land cell contributes once to exactly one island's size.
  • You may use DFS or BFS. Account for a large single island when choosing recursive versus iterative traversal.
  • The combined two-integer output and four-neighbor definition make the reported island-count and maximum-size follow-up one deterministic practice task.

Examples

grid = [[1,1,0],[0,1,0],[1,0,1]]
result = [3,3]
grid = [[0,0],[0,0]]
result = [0,0]

Alongside the implementation, compare DFS and BFS for this grid: describe their traversal order, give the time and auxiliary-space bounds for each, and explain the recursion-stack risk of recursive DFS on a large island. Distinguish the visited-state storage from the explicit stack or queue, and explain how the same traversal obtains both the island count and the maximum component size.

Hints

Hint 1

Count when starting a new traversal: An unvisited land cell starts one island. Track how many land cells that traversal reaches, then compare that component size with the current maximum.