Problem solution · Java

Count Cells in Overlapping Horizontal and Vertical Substrings

Count Cells in Overlapping Horizontal and Vertical Substrings: a Java solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
79 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Count Cells in Overlapping Horizontal and Vertical Substrings, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 79 lines of Java from the credited upstream file 3529.java.
  • The implementation visibly relies on sequence storage.
  • 10 loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCount Cells in Overlapping Horizontal and Vertical Substrings · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int countCells(char[][] grid, String pattern) {    final int m = grid.length;    final int n = grid[0].length;    int ans = 0;    StringBuilder flattenedGridRow = new StringBuilder();    StringBuilder flattenedGridCol = new StringBuilder();     // Flatten the grid for horizontal matching.    for (int i = 0; i < m; ++i)      for (int j = 0; j < n; ++j)        flattenedGridRow.append(grid[i][j]);     // Flatten the grid for vertical matching.    for (int j = 0; j < n; ++j)      for (int i = 0; i < m; ++i)        flattenedGridCol.append(grid[i][j]);     // Find matching positions.    boolean[][] horizontalMatches =        markMatchedCells(flattenedGridRow.toString(), pattern, m, n, true);    boolean[][] verticalMatches =        markMatchedCells(flattenedGridCol.toString(), pattern, m, n, false);     // Count overlapping match positions.    for (int i = 0; i < m; ++i)      for (int j = 0; j < n; ++j)        if (horizontalMatches[i][j] && verticalMatches[i][j])          ++ans;     return ans;  }   private static final long BASE = 13;  private static final long HASH = 1_000_000_007;   private boolean[][] markMatchedCells(final String flattenedGrid, final String pattern, int m,                                       int n, boolean isHorizontal) {    boolean[][] matchMatrix = new boolean[m][n];    int[] matchPrefix = new int[flattenedGrid.length() + 1];    long[] pows = new long[pattern.length()]; // pows[i] := BASE^i % HASH    pows[0] = 1;    long patternHash = 0;    long runningHash = 0;     for (int i = 1; i < pattern.length(); ++i)      pows[i] = (pows[i - 1] * BASE) % HASH;     for (final char c : pattern.toCharArray())      patternHash = (patternHash * BASE + (c - 'a')) % HASH;     for (int i = 0; i < flattenedGrid.length(); ++i) {      runningHash = (runningHash * BASE + (flattenedGrid.charAt(i) - 'a')) % HASH;      if (i >= pattern.length() - 1) {        if (runningHash == patternHash) { // Match found.          ++matchPrefix[i - pattern.length() + 1];          --matchPrefix[i + 1];        }        // Remove the contribution of the oldest letter.        final long oldestLetterHash =            (pows[pattern.length() - 1] * (flattenedGrid.charAt(i - pattern.length() + 1) - 'a')) %            HASH;        runningHash = (runningHash - oldestLetterHash + HASH) % HASH;      }    }     for (int k = 0; k < flattenedGrid.length(); ++k) {      matchPrefix[k] += (k > 0) ? matchPrefix[k - 1] : 0;      if (matchPrefix[k] > 0) {        final int i = isHorizontal ? k / n : k % m;        final int j = isHorizontal ? k % n : k / m;        matchMatrix[i][j] = true;      }    }     return matchMatrix;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗