1172. Most Common Bigram
A messaging app wants to show the most typical two-letter chunk of a message. You are given a lowercase string s. Look at every substring of length 2, including overlapping ones (so "aaa" holds "aa" twice), and return the bigram that occurs most often.
If several bigrams share the highest count, return the lexicographically smallest of them. The string has at least two characters, so an answer always exists, and the result is always a string of exactly two letters.
A single pass with a 26 by 26 table of counts runs in linear time and constant extra space.
Example 1
- Input:
- s = "abababc"
- Output:
- "ab"
- Explanation:
The bigram
abappears 3 times,batwice andbconce, soabwins.
Example 2
- Input:
- s = "banana"
- Output:
- "an"
- Explanation:
anandnaboth appear twice, andanis smaller alphabetically.
Example 3
- Input:
- s = "aaaa"
- Output:
- "aa"
- Explanation:
The overlapping bigram
aaappears 3 times.
Constraints
2 ≤ s.length ≤ 104
s contains only lowercase letters
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)