Katkat

Find the Most Frequent Character with a Tie-Breaker

SquarepointSoftware Engineer · HR Screen

Last updated

Tests string traversal, frequency counting, and deterministic tie-breaking under large input constraints.

Problem Statement

Given a string s consisting of lowercase English letters, find the character that appears most frequently. If there is a tie between multiple characters with the same maximum frequency, return the character that comes first in alphabetical order (lexicographically smallest).

Your solution should be efficient enough to process strings containing millions of characters.

Function Signature

def most_frequent_char(s: str) -> str:
    pass

Input & Output Format

  • Input: A non-empty string s containing only lowercase English letters ('a' through 'z').
  • Output: A single lowercase English character representing the most frequent character with tie-breaking applied.

Constraints

  • 1 <= len(s) <= 10^7
  • s contains only lowercase English letters ('a' - 'z').
  • Target time complexity: O(n) where n = len(s).
  • Target space complexity: O(1) auxiliary space beyond the input string.

Examples

Example 1

Input: s = "abacaba"
Output: "a"
Explanation: 'a' appears 4 times, 'b' appears 2 times, and 'c' appears 1 time. The highest frequency is 4, belonging to 'a'.

Example 2

Input: s = "dcbaabcd"
Output: "a"
Explanation:
Frequencies:
- 'a': 2
- 'b': 2
- 'c': 2
- 'd': 2
All characters tie with a frequency of 2. Alphabetically, 'a'  `"z"`).
- String where all characters are distinct (tie among all present characters; return the alphabetically smallest).
- Very large strings (`~10^7` characters) where avoiding unnecessary object allocations is critical.

Hints

Hint 1

Since the alphabet is fixed to 26 lowercase English letters, a fixed-size array of length 26 can track counts in constant auxiliary space.

Hint 2

Iterate through the string once to populate counts, then iterate through the 26 possible characters to determine the maximum.

Hint 3

Checking characters in ascending order from 'a' to 'z' ensures you naturally pick the lexicographically smallest character without additional sorting.

Follow-up questions

  • How would you handle this if the input string cannot fit in memory and must be processed as a stream of chunks or lines?
  • If the character set was extended to arbitrary Unicode characters, how would your space and time complexity change?
  • How would you parallelize this computation across multiple CPU cores for a 100 GB log file?