KatInterview

Highest Frequency Letter with Alphabetical Tie-Breaking

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringsstringsarraysfrequency-counting

Last updated

Tests efficient character frequency counting and consistent tie-breaking using fixed-size auxiliary space.

Problem Statement

You are given a string s made up entirely of lowercase English letters. Your task is to identify which letter occurs the greatest number of times in the string. When multiple letters share the highest occurrence count, return the one that appears earliest in the alphabet.

Your implementation must handle strings with up to ten million characters efficiently.

Function Signature

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

Input & Output Format

  • Input: A non-empty string s containing only lowercase English letters ('a' to 'z').
  • Output: A single character (string of length 1) representing the letter with the highest frequency. If multiple letters tie for the highest count, return the lexicographically smallest one.

Constraints

  • 1 <= len(s) <= 10^7
  • s consists exclusively of lowercase English letters ('a' through 'z')
  • Your solution should run in O(n) time where n is the length of s
  • Aim for O(1) auxiliary space (beyond the input itself)

Edge Cases to Consider

  • Strings where one letter dominates completely
  • Strings where all letters appear with equal frequency
  • Strings where every character is unique
  • Very long inputs approaching the maximum constraint
  • Single-character strings

Examples

Example 1

Input: highest_frequency_letter('abacaba')

Output: 'a'

Example 2

Input: highest_frequency_letter('dcbaabcd')

Output: 'a'

Hints

Hint 1

The English alphabet has exactly 26 letters—consider using a fixed-size structure rather than a dynamic hash map.

Hint 2

Walk through the frequency array in alphabetical order and only update your answer when you find a strictly greater count.

Hint 3

A single pass to count and a second pass over 26 slots to find the maximum is O(n + 26) = O(n) total.