[LeetCode] – Number of Islands Solution

    by nikoo28

    In this problem, we are given a 2D grid consisting of ‘1’s (land) and ‘0’s (water). Our task is to count the number of islands. An island consists of a group of connected ‘1’s surrounded by water (‘0’s). The connection can be in four directions—up, down, left, or right.

    The most important aspect of this problem is to ensure that we count each piece of land only once. To do this, we need an efficient way to traverse the grid and mark visited lands.

    Input:
    grid = [
    ['1', '1', '0', '0', '0'],
    ['1', '1', '0', '0', '0'],
    ['0', '0', '1', '0', '0'],
    ['0', '0', '0', '1', '1']
    ]
    Output: 3
    Explanation:
    - The first two rows form one island.
    - The single '1' in the third row is another island.
    - The last two '1's in the fourth row form the third island.
    figure showing 3 number of islands
    Fig: A visual for number of islands

    A naive approach would be to iterate over every cell in the grid and try to count islands while keeping track of visited cells using an auxiliary data structure. This method would involve unnecessary re-traversals, making it inefficient.

    Steps:

    1. Initialize a variable count to store the number of islands.
    2. Create a separate visited matrix to track visited cells.
    3. Iterate through every cell in the grid:
      • If a cell contains ‘1’ and hasn’t been visited, perform a traversal (BFS or DFS) to mark all connected land as visited.
      • Increment the island count.
    4. Return count as the number of islands.

    Instead of maintaining an extra visited array, we can modify the grid itself by marking visited land cells as ‘0’ (water). This reduces space complexity while ensuring we don’t count the same island multiple times.

    Steps:

    1. Initialize count = 0 to track the number of islands.
    2. Iterate through the grid:
      • If a cell is ‘1’, trigger a Depth-First Search (DFS) to mark all connected land as visited.
      • Increment count after each DFS traversal.
    3. The DFS function should:
      • Check if the cell is out of bounds or already water (‘0’). If so, return.
      • Mark the current cell as ‘0’ to avoid re-visiting.
      • Recursively visit its neighbors (up, down, left, right).
    4. Once the entire grid is traversed, return count.
    Fig: A bigger example showing visited cells
    int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
          return 0;
        }
    
        int 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;
    }
    
    private void dfs(char[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length
            || j < 0 || j >= grid[0].length
            || grid[i][j] == '0') {
          return;
        }
    
        grid[i][j] = '0'; // Mark the cell as visited
    
        // Explore all four directions
        dfs(grid, i + 1, j);
        dfs(grid, i - 1, j);
        dfs(grid, i, j + 1);
        dfs(grid, i, j - 1);
    }
    Code language: Java (java)
    • Time Complexity: O(n * m), where n is the number of rows and m is the number of columns. Each cell is visited once and its adjacent cells are checked at most once.
    • Space Complexity: O(n * m) in the worst case due to recursion stack depth (if the grid is entirely land). However, this is more space-efficient than using an auxiliary visited array.
    YouTube player
    0 comments
    0 FacebookTwitterLinkedinWhatsappEmail
  • ArraysStrings

    [Leetcode] – Word Break Solution

    by nikoo28
    4 minutes read

    In the given problem statement, we have a string s and a dictionary wordDict containing a list of words. We need to determine if s can be segmented into a space-separated sequence of dictionary words. The tricky part of this problem is ensuring that every segment of the string matches words from the dictionary. A brute-force approach could generate all possible segmentations, but that would be highly inefficient. Input: s = “studyalgorithms”wordDict = [“study”, “algorithms”]Output: trueExplanation: Since “studyalgorithms” can be split into “study” and “algorithms”, both of which are in …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Arrays

    [Leetcode] – Insert Interval Solution

    by nikoo28
    4 minutes read

    In this problem, we are given a list of non-overlapping intervals sorted by their start times, along with a new interval. The goal is to insert the new interval into the list while ensuring the intervals remain non-overlapping and sorted. If necessary, overlapping intervals should be merged. The tricky part of this problem lies in handling overlapping intervals efficiently while maintaining the sorted order. We also need to consider edge cases, such as when the new interval does not overlap with any existing intervals or when it encompasses multiple intervals. …

    0 FacebookTwitterLinkedinWhatsappEmail
  • System DesignTheory

    Message Queue in System Design

    by nikoo28
    3 minutes read

    Continuing with our System Design series we’ll be discussing message queue, an essential component in building scalable, decoupled systems. Message queues help systems handle communication between different parts asynchronously, ensuring smooth data flow even during heavy traffic. What is a Message Queue? A message queue is a system that allows different parts of a system to communicate with each other in an asynchronous manner. It acts as a buffer between a producer (the part that sends messages) and a consumer (the part that processes messages), allowing the producer to continue …

    0 FacebookTwitterLinkedinWhatsappEmail
  • System DesignTheory

    Proxy in System Design

    by nikoo28
    5 minutes read

    Let’s continue the journey in System Design. In this post, we’ll explore the concept of forward and reverse proxy, which play a crucial role in optimizing and securing web traffic. Proxies act as intermediaries, improving efficiency, security, and management of requests between clients and servers. What is a Proxy? A proxy is essentially an intermediary that sits between a client and a server, forwarding requests and responses between the two. It can be used for various purposes such as load balancing, security, caching, and more. Real-World Example: Imagine a bookstore …

    0 FacebookTwitterLinkedinWhatsappEmail
  • System DesignTheory

    Indexing in System Design

    by nikoo28
    3 minutes read

    Let us continue our System Design series! In this post, we’ll dive into the concept of indexing in databases. Indexing is a technique that allows for faster data retrieval by organizing and optimizing the way data is stored. What is Indexing? Indexing is like creating a shortcut for finding the right data quickly. Instead of scanning the entire database, the index helps you jump directly to the location of the data you need, improving the performance of your queries. Real-World Example: Let’s go back to our bookstore analogy. Imagine you …

    0 FacebookTwitterLinkedinWhatsappEmail
  • System DesignTheory

    Databases in System Design

    by nikoo28
    5 minutes read

    Welcome again to System Design series! In this post, we will explore the concept of databases, which are fundamental to storing, organizing, and managing data in any application. Databases are the backbone of any data-driven system, providing the infrastructure needed to handle, retrieve, and manipulate data efficiently. What is a Database? A database allows users to easily access, manage, and update a structured collection of data. It serves as a digital ledger, storing information in an organized way, allowing quick retrieval and manipulation of data. Real-World Example: In our bookstore …

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More