713587. Count number of free cell

Medium

Count number of free cell

Slug: count-number-of-free-cell--170646

Difficulty: Medium

Id: 713587

Topic Tags: Hash, Matrix, Data Structures

Company Tags: Intuit

Summary

The problem is about counting the number of "free cells" in a given matrix. A free cell is defined as an empty cell with no obstacles (represented by non-zero values) adjacent to it.

Detailed Explanation

To solve this problem, we can use a hash-based approach. We create a frequency map to store the count of free cells for each row and column. Then, we iterate through the matrix and update the corresponding counts in the frequency map. Finally, we sum up the counts from the frequency map to get the total number of free cells.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty frequency map freq with keys for each row and column index.
  2. Iterate through the matrix:
    • For each cell (i, j) in the matrix:
      • Check if the cell is "free" (i.e., its value is 0).
      • If it's free, increment the count for row i and column j in the frequency map.
  3. Sum up the counts from the frequency map to get the total number of free cells.

Time complexity: O(m * n), where m is the number of rows and n is the number of columns in the matrix.

Space complexity: O(m + n) for the frequency map.

Optimized Solutions

Java

View on GeeksforGeeks
public int countFreeCells(int[][] matrix) {
    Map<Integer, Integer> rowCounts = new HashMap<>();
    Map<Integer, Integer> colCounts = new HashMap<>();

    int freeCells = 0;
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            if (matrix[i][j] == 0) {
                rowCounts.put(i, rowCounts.getOrDefault(i, 0) + 1);
                colCounts.put(j, colCounts.getOrDefault(j, 0) + 1);
            }
        }
    }

    for (int i = 0; i < matrix.length; i++) {
        freeCells += rowCounts.getOrDefault(i, 0);
    }
    for (int j = 0; j < matrix[0].length; j++) {
        freeCells += colCounts.getOrDefault(j, 0);
    }

    return freeCells;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.