Iterative Matrix Traversal — Problem Statement & Solution Guide
Problem Description
You are given a rectangular grid of lowercase English letters with m rows and n columns. Starting from the top‑left cell, traverse the grid row by row (left to right within each row) and record how many times each distinct character appears. After the complete traversal, identify the character with the highest occurrence count. If multiple characters share the maximum count, choose the lexicographically smallest one. Output the selected character followed by its frequency, separated by a single space.
Input format:
- The first line contains two integers m and n (1 ≤ m, n ≤ 300) – the number of rows and columns.
- The next m lines each contain a string of length n consisting solely of lowercase letters, representing one row of the grid.
Output format:
- A single line with the character that appears most frequently and its count, separated by a space.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Iterative Matrix Traversal"
WHY DOES IT MATTER?
Frequency counting over a bounded domain is a foundational pattern that appears in compression, cryptography, and data analytics. Mastering it teaches you how to convert a seemingly large input into a compact representation that can be processed in constant time per element.
OPTIMIZATION CHALLENGE
The key insight is recognizing that the alphabet size (26) is independent of the matrix dimensions, allowing us to replace any generic map or sorting step with a fixed‑size array and achieve O(1) auxiliary space.
REAL-WORLD CONNECTION
Think of a distributed logging system that aggregates log levels (INFO, WARN, ERROR) across thousands of servers. Each server streams logs, and a central aggregator maintains a tiny counter per level—exactly the same constant‑size frequency table used here.
During an interview, write the frequency array first, then immediately scan the matrix updating it. After the scan, loop over the 26 slots to pick the max, handling ties by checking the character order—this linear‑after‑linear flow is easy to explain and hard to mess up.
COMPLEXITY AT A GLANCE
O(m * n)O(1)Core Theory — Why This Approach?
The problem reduces to a frequency counting task over a two‑dimensional character matrix. By traversing the matrix in row‑major order (left‑to‑right within each row, top‑to‑bottom across rows) we can update a fixed‑size frequency array of length 26, one slot per lowercase English letter. This approach leverages the pigeonhole principle: because the alphabet size is constant, the counting structure never grows with input size, guaranteeing O(1) auxiliary space. Naïve alternatives—such as storing every character in a list and then sorting or using a hash map without early aggregation—inflate both time and memory, especially when m·n reaches 10⁶ or higher. The optimal paradigm is a single pass linear scan combined with constant‑time updates, which is the classic "frequency counting" pattern often seen in string and array problems.
Interview Questions on This Problem
Q1How would you modify the solution if the grid could contain any Unicode character, not just lowercase English letters?
Replace the fixed‑size 26‑element array with a hash map (e.g., unordered_map<char32_t, int>) to store frequencies dynamically. The traversal logic stays the same, and tie‑breaking can be handled by iterating over the map’s keys sorted lexicographically after the scan.
Q2Can you compute the most frequent character without storing the entire frequency table, using only O(1) extra space?
Yes. Maintain two variables during traversal: (1) the current candidate character and its count, and (2) the maximum count seen so far. When a new character’s count exceeds the maximum, update the candidate. If counts tie, keep the lexicographically smaller character. This works because the alphabet size is constant, allowing us to recompute counts on the fly if needed.
Q3What is the time‑space trade‑off if you need to answer multiple queries of the form “most frequent character in sub‑matrix (r1,c1)-(r2,c2)” after a single preprocessing step?
Preprocess a 2‑D prefix sum for each of the 26 letters, resulting in O(26·m·n) space and O(26·m·n) time. Each query then aggregates counts for the sub‑matrix in O(26) time, yielding O(1) query time after O(m·n) preprocessing. The trade‑off is higher memory usage for fast query response.
Examples
Input
3 4 abca bcab cabc
Output
a 4
Explanation: The grid is: Row 1: a b c a Row 2: b c a b Row 3: c a b c Counting each letter yields a:4, b:4, c:4. All three share the maximum frequency, so the lexicographically smallest, 'a', is chosen. Hence the answer is "a 4".
Input
2 5 zzzzz abcde
Output
z 5
Explanation: The grid contains: Row 1: z z z z z Row 2: a b c d e Frequencies are z:5 and each of a, b, c, d, e:1. The highest count is 5 for 'z', so the output is "z 5".
Input
1 6 abccba
Output
a 2
Explanation: The single row is a b c c b a. The counts are a:2, b:2, c:2. All three tie for the maximum frequency; the smallest character alphabetically is 'a'. Therefore the result is "a 2".
Constraints
- 1 <= m, n <= 300
- m * n <= 100000
- Each grid cell contains a lowercase English letter ('a'‑'z')
Optimal Approach & Strategy
Use a fixed 26‑element integer array to count frequencies while traversing the matrix once, then scan the array to find the max with lexicographic tie‑break.
Brute Force Approach
Store every character in a list, sort the list, then scan to count runs and pick the most frequent character.
Verified Code Solutions
function solution(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum;
}class Solution {
public:
int solution(vector<int>& nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
};class Solution {
public int solution(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
}def solution(nums):
sum = 0
for num in nums:
sum += num
return sumfunction solution(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum;
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.