You are given an m x n matrix grid consisting of characters and a string pattern.
A horizontal substring is a contiguous sequence of characters read from left to right. If the end of a row is reached before the substring is complete, it wraps to the first column of the next row and continues as needed. You do not wrap from the bottom row back to the top.
A vertical substring is a contiguous sequence of characters read from top to bottom. If the bottom of a column is reached before the substring is complete, it wraps to the first row of the next column and continues as needed. You do not wrap from the last column back to the first.
Count the number of cells in the matrix that satisfy the following condition: The cell must be part of at least one horizontal substring and at least one vertical substring, where both substrings are equal to the given pattern.
Count Cells in Overlapping Horizontal and Vertical Substrings — Solution
The key insight is to find cells that participate in both horizontal and vertical pattern matches. Best approach uses two-pass scanning with hash sets for O(m·n·k) time and efficient set intersection. Time: O(m·n·k), Space: O(m·n)
Common Approaches
✓
Brute Force - Check All Positions
⏱️ Time: O(m·n·k²)
Space: O(m·n)
Check every possible starting position for horizontal and vertical substrings. For each cell, verify if it belongs to valid pattern matches in both directions.
Optimized - Two-Pass with Sets
⏱️ Time: O(m·n·k)
Space: O(m·n)
First pass collects all cells that are part of horizontal pattern matches. Second pass collects all cells that are part of vertical pattern matches. Then find intersection efficiently using set operations.
Brute Force - Check All Positions — Algorithm Steps
Find all horizontal pattern matches with their cell positions
Find all vertical pattern matches with their cell positions
Count cells that appear in both horizontal and vertical matches
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Scan Horizontal
Find all horizontal pattern matches
2
Scan Vertical
Find all vertical pattern matches
3
Count Overlap
Count cells in both sets
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000
int solution(char grid[][MAX_SIZE], int m, int n, char* pattern) {
int k = strlen(pattern);
if (k == 0) return 0;
char horizontalCells[MAX_SIZE*MAX_SIZE][20];
char verticalCells[MAX_SIZE*MAX_SIZE][20];
int hCount = 0, vCount = 0;
// Find horizontal matches
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
char substring[MAX_SIZE];
char positions[MAX_SIZE][20];
int posCount = 0;
int row = i, col = j;
int idx = 0;
for (int pos = 0; pos < k; pos++) {
if (row >= m) break;
substring[idx++] = grid[row][col];
sprintf(positions[posCount++], "%d,%d", row, col);
col++;
if (col == n) {
col = 0;
row++;
}
}
substring[idx] = '\0';
if (strlen(substring) == k && strcmp(substring, pattern) == 0) {
for (int p = 0; p < posCount; p++) {
strcpy(horizontalCells[hCount++], positions[p]);
}
}
}
}
// Find vertical matches
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
char substring[MAX_SIZE];
char positions[MAX_SIZE][20];
int posCount = 0;
int row = i, col = j;
int idx = 0;
for (int pos = 0; pos < k; pos++) {
if (col >= n) break;
substring[idx++] = grid[row][col];
sprintf(positions[posCount++], "%d,%d", row, col);
row++;
if (row == m) {
row = 0;
col++;
}
}
substring[idx] = '\0';
if (strlen(substring) == k && strcmp(substring, pattern) == 0) {
for (int p = 0; p < posCount; p++) {
strcpy(verticalCells[vCount++], positions[p]);
}
}
}
}
// Count intersection - remove duplicates first
int count = 0;
char counted[MAX_SIZE*MAX_SIZE][20];
int countedSize = 0;
for (int i = 0; i < hCount; i++) {
for (int j = 0; j < vCount; j++) {
if (strcmp(horizontalCells[i], verticalCells[j]) == 0) {
// Check if already counted
int alreadyCounted = 0;
for (int k = 0; k < countedSize; k++) {
if (strcmp(counted[k], horizontalCells[i]) == 0) {
alreadyCounted = 1;
break;
}
}
if (!alreadyCounted) {
strcpy(counted[countedSize++], horizontalCells[i]);
count++;
}
break;
}
}
}
return count;
}
int main() {
char grid[MAX_SIZE][MAX_SIZE];
char pattern[MAX_SIZE];
char line[10000];
int m = 0, n = 0;
// Read grid line
fgets(line, sizeof(line), stdin);
// Parse grid - extract characters between quotes
int i = 0, j = 0;
int inQuote = 0;
char currentChar = 0;
for (int pos = 0; line[pos] != '\0' && line[pos] != '\n'; pos++) {
if (line[pos] == '"') {
if (inQuote) {
// End of character, store it
if (currentChar != 0) {
grid[i][j] = currentChar;
j++;
currentChar = 0;
}
inQuote = 0;
} else {
inQuote = 1;
}
} else if (inQuote && line[pos] >= 'a' && line[pos] <= 'z') {
currentChar = line[pos];
} else if (line[pos] == ']' && line[pos+1] == ',' && line[pos+2] == '[') {
// End of row
if (j > 0) {
if (n == 0) n = j; // Set n from first row
i++;
j = 0;
}
}
}
// Handle last row
if (j > 0) {
if (n == 0) n = j;
i++;
}
m = i;
// Read pattern line
fgets(pattern, sizeof(pattern), stdin);
pattern[strcspn(pattern, "\n")] = 0;
int result = solution(grid, m, n, pattern);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(m·n·k²)
For each of m·n cells, check up to k positions in both directions where k is pattern length
n
2n
✓ Linear Growth
Space Complexity
O(m·n)
Storage for marking cells that are part of horizontal and vertical matches
n
2n
⚡ Linearithmic Space
12.8K Views
MediumFrequency
~35 minAvg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.