1172. Most Common Bigram

Easy1.5 points estimatedCountingHash TableString

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 ab appears 3 times, ba twice and bc once, so ab wins.

Example 2

Input:
s = "banana"
Output:
"an"
Explanation:

an and na both appear twice, and an is smaller alphabetically.

Example 3

Input:
s = "aaaa"
Output:
"aa"
Explanation:

The overlapping bigram aa appears 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)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…