Home › Company-wise questions › PayPal › Number of Islands ← PayPal bank
PayPal · Question 68 · Graphs
Number of Islands Graphs Java code ⏱ O(mn) 💾 O(mn)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Count the number of islands (connected groups of '1's) in a 2D grid.
Approach Use DFS or BFS to mark visited islands.
Time O(mn)Space O(mn)
How it works 1 Each fresh '1' starts a flood. 2 DFS sinks the whole island to '0'. Sample input / output Input:
grid = 4x5 with 3 islands
Output:
3 Constraints 1 <= m, n <= 300.
Solution — read it, then walk it Flowchart Pseudocode
Time O(mn)Space O(mn)Loops 2Branches 2Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat yes ↻ repeat ↻ repeat yes no START import java.util.* DEFINE class Main DEFINE static int numIslands(char[][] grid) DEFINE count = 0 for (int i = 0; i < grid.length; i++) for (int j = 0; j < grid[0].length; j++) if (grid[i][j] == '1') dfs(grid, i, j) count++ RETURN count DEFINE static void dfs(char[][] grid, int i, int j) if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length |… RETURN grid[i][j] = '0' dfs(grid, i + 1, j) dfs(grid, i - 1, j) dfs(grid, i, j + 1) dfs(grid, i, j - 1) DEFINE static void main(String[] args) DEFINE [][] grid = {{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}} System.out.println(numIslands(grid)) END start / end statement condition loop returns definition← Q67 · House Robber Q69 · Kth Largest Element in an Array → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →