Skip to main content

Most Frequent Substring

easy
Software engineer

A text analysis program needs to identify the most frequently occurring substring of a specific length within a given lowercase string.

Given a string str and an integer n, return the substring of length n that appears the most times in str. If more than one substring has the highest frequency, return the lexicographically smallest one. Return an empty string if no such valid substring is found.

A substring is defined as a sequence of contiguous characters in str. Overlapping substrings are counted separately; for example, in "aaaa" with n = 2, the substring "aa" appears three times.

Example 1

Input

str = "inengineering", n = 2

Output

"in"

Explanation

Substrings of length 2 are: 'in', 'ne', 'en', 'ng', 'gi', 'in', 'ne', 'ee', 'er', 'ri', 'in', 'ng'. 
The substring 'in' appears 3 times. 
'ne', 'en', and 'ng' appear 2 times each. 
Since 'in' has the highest frequency (3), it is the answer.

Example 2

Input

str = "zabzab", n = 2

Output

"ab"

Explanation

Both 'ab' and 'za' appear twice. 'ab' is lexicographically smaller than 'za'.

Example 3

Input

str = "aaaaa", n = 1

Output

"a"

Constraints

  • 1 <= str.length <= 10⁵
  • 1 <= n <= str.length
  • str consists only of lowercase English letters

Screening

CountingHash TableSliding WindowSortingString
Language
Code editor loads in the browser.

Output

Input

"inengineering"
2

Expected

"in"

Your output

Run to see your output.