coding
PayPal
Amazon
Microsoft

PayPal Coding Question: Count Islands in 2D Grid with DFS

Topics:
Depth-First Search
Breadth-First Search
Matrix / Connected Components
Roles:
Machine Learning Engineer
Software Engineer
Data Engineer
Experience:
Entry Level
Mid Level
Senior

Question Description

Overview

You are asked to implement num_islands(grid) to count distinct islands in a rectangular 2D grid composed of '1' (land) and '0' (water). An island is a group of adjacent '1' cells connected horizontally or vertically. The input is an m × n matrix (list of lists) and you should return the integer count of connected land components.

What you'll be asked to do

First, write a correct implementation (commonly using DFS or BFS to mark visited land). Typical flows: scan the matrix, when you find an unvisited '1' increment the island count and flood-fill that component (recursive DFS, iterative stack, or BFS queue) to avoid double counting. After the implementation stage, explain the time and space complexity in terms of m (rows) and n (columns).

Interview flow & expectations

  • Clarify input mutability (can you modify grid in-place?) and constraints (m, n size).
  • Propose DFS and BFS options and trade-offs (recursion depth vs iterative stack/queue).
  • Implement a clean solution (mark visited or overwrite cells).
  • Provide time/space analysis and mention edge cases (all water, all land, thin long grids).

Skills signaled

You should demonstrate matrix traversal, graph connected-components thinking, mastery of DFS/BFS variants, iterative vs recursive trade-offs, and clear time/space complexity reasoning.

Common Follow-up Questions

  • How would you modify your solution if diagonal adjacency counts (8-directional connectivity)?
  • Can you implement the solution using Union-Find (disjoint set) and compare its time/space trade-offs to DFS/BFS?
  • How would you return the size (area) of the largest island and the coordinates of its cells while keeping O(m·n) time?
  • If the grid is huge and stored on disk (out-of-core), how would you adapt your algorithm to minimize memory and I/O?
  • How does your approach change if you cannot modify the input grid and must use only O(1) extra space?

Related Questions

1Max Area of Island — compute largest connected '1' region in a grid
2Number of Enclaves — count land cells not connected to the grid border
3Surrounded Regions (capture regions) — flip surrounded 'O's to 'X's using BFS/DFS

Explore More Questions

Practice This Question with AI

Get real-time hints, detailed requirements, and insightful analysis of the question.

PayPal: Count Islands in 2D Grid (DFS/BFS) and Complexity | Voker