Advertisement

Number of Islands - LeetCode 200 Solution

Number of Islands - Complete Solution Guide

Number of Islands is LeetCode problem 200, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given an m x n 2D binary grid grid which represents a map of '1' s (land) and '0' s (water), return the number of islands . An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1 Example 2: Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"]

Detailed Explanation

The problem asks us to find the number of 'islands' in a 2D grid where '1' represents land and '0' represents water. An island is defined as a group of connected '1's (land) horizontally or vertically. The entire grid is surrounded by water, meaning any land touching the edges of the grid is part of an island.

Solution Approach

The provided solutions use a Breadth-First Search (BFS) approach. The algorithm iterates through each cell of the grid. If a cell contains a '1' (land), it means we've found a new island. We increment the island count, then initiate a BFS to explore all connected land cells. During the BFS, each visited '1' is marked as '0' to prevent it from being visited again. The BFS continues until all connected land cells of the current island have been visited and marked.

Step-by-Step Algorithm

  1. Step 1: Iterate through each cell of the grid using nested loops.
  2. Step 2: If a cell contains '1' (land), increment the island count.
  3. Step 3: Mark the current cell as '0' (sink the land).
  4. Step 4: Create a queue (using collections.deque in Python, LinkedList in Java, queue in C++) and add the coordinates of the current cell to the queue.
  5. Step 5: While the queue is not empty, do the following:
  6. Step 6: Dequeue a cell (row, col) from the queue.
  7. Step 7: Explore the four neighboring cells (up, down, left, right).
  8. Step 8: For each neighbor, check if it's within the grid boundaries and if it contains '1' (land).
  9. Step 9: If a neighbor is land, mark it as '0' and enqueue its coordinates.
  10. Step 10: After the BFS is complete for the current island, the outer loops continue iterating through the grid.
  11. Step 11: Return the total island count.

Key Insights

  • Insight 1: The core idea is to traverse the grid and, upon encountering a '1', increment the island count and then 'sink' the entire island by marking all connected '1's as '0'. This avoids recounting the same island multiple times.
  • Insight 2: Depth-First Search (DFS) or Breadth-First Search (BFS) are effective algorithms for traversing and marking connected components in a graph or a grid. The provided solutions use BFS.
  • Insight 3: Modifying the input grid in place (changing '1' to '0') is a common optimization to avoid using extra space for tracking visited cells. However, this approach mutates the input, which might not be desirable in all situations.

Complexity Analysis

Time Complexity: O(M*N)

Space Complexity: O(M*N)

Topics

This problem involves: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix.

Companies

Asked at: Akuna Capital, Anduril, Axon, BILL Holdings, Barclays, BitGo, BlackRock, Booking.com, ByteDance, Capital One, Cisco, Citadel, Cloudflare, Comcast, Coupang, CrowdStrike, Disney, Docusign, DoorDash, Dropbox, EarnIn, Expedia, Flipkart, Goldman Sachs, Grammarly, HPE, HashedIn, Hotstar, Huawei, Infosys, Intel, Intuit, Karat, LinkedIn, Lucid, Moloco, Morgan Stanley, Nutanix, Nvidia, OKX, Oracle, Palantir Technologies, PayPal, PhonePe, Pinterest, Qualcomm, Reddit, Rivian, SAP, Salesforce, Samsung, ServiceNow, Siemens, Snap, Snowflake, SoFi, Tesla, Tinkoff, Turing, UiPath, Urban Company, Visa, Walmart Labs, Waymo, Whatnot, Wix, X, Yandex, Zenefits, Zepto, Zeta, Zillow, Zoho, Zomato, eBay, thoughtspot.