Number of Islands
Updated
Problem statement
You are given a grid grid with m rows and n columns. Each cell holds the character '1' for land or '0' for water.
Two land cells are connected when they share a side: one is directly above, below, left or right of the other. Cells that touch only at a corner are not connected. Every cell outside the grid is water.
An island is all the land cells you can reach from one land cell by stepping between connected land cells. Every land cell belongs to exactly one island.
Return the number of islands in grid.
Function
numIslands(grid: char[][]) → intExamples
Example 1
grid = [["1","1","0","0"],["1","0","0","1"],["0","0","1","1"],["1","0","0","0"]]return = 3Here (r, c) means row r and column c, counting from 0. There are 3 islands. The first is (0, 0), (0, 1) and (1, 0). The second is (1, 3), (2, 2) and (2, 3). The third is the single cell (3, 0). It is not joined to the first island because (2, 0) is water.
Example 2
grid = [["1","0","1"],["0","1","0"],["1","0","1"]]return = 5The five land cells touch each other only at corners. Corner contact does not connect cells, so each land cell is its own island and the answer is 5.
Example 3
grid = [["1","1","1"],["1","0","1"],["1","1","1"]]return = 1The eight land cells form a ring around the water cell in the middle. Each of them shares a side with the next one around the ring, so they are one island. The water inside does not split it, and the answer is 1.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is'0'or'1'.
More Intuit interview questions
- LRU CacheONSITE INTERVIEW · Seen Sep 2026
- VIP and Regular Service SchedulerPHONE SCREEN · Seen Nov 2026
- Employee Promotion OpportunitiesOA · Seen Oct 2026
- Next Pascal Row CoefficientOA · Seen Oct 2026
- Parse Router LogsOA · Seen Oct 2026
- Longest Repeated Letter Block with Adjacent SwapsOA · Seen Oct 2026
- Maximum Square-Free DivisorOA · Seen Oct 2026
- Two Tribes from Taller-Person CountsOA · Seen Oct 2026
- Shortest Path from an Encoded GraphOA · Seen Sep 2026
- Oldest and Youngest EmployeesOA · Seen Sep 2026
Similar questions at other companies
- Number of IslandsExpedia · ONSITE INTERVIEWExpedia interview questions
- Count Islands in a Binary GridApple · PHONE SCREENApple interview questions
- Count the IslandsAdobe · PHONE SCREENAdobe interview questions
- Number of Islands with Diagonal ConnectivityGoogle · ONSITE INTERVIEWGoogle interview questions
- Island Count and Maximum AreaOracle · ONSITE INTERVIEWOracle interview questions
- Maximum Number of Fish in a GridGlobalization Partners · ONSITE INTERVIEW
- Max Area of IslandGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Max Area of IslandRoku · ONSITE INTERVIEWRoku interview questions
- Max Area of IslandBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Maximum Area of IslandSambaNova Systems · ONSITE INTERVIEWSambaNova Systems interview questions