VOOZH about

URL: https://www.geeksforgeeks.org/dsa/substring-of-length-k-having-maximum-frequency-in-the-given-string/

⇱ Substring of length K having maximum frequency in the given string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Substring of length K having maximum frequency in the given string

Last Updated : 15 Jul, 2025

Given a string str, the task is to find the substring of length K which occurs the maximum number of times. If more than one string occurs maximum number of times, then print the lexicographically smallest substring.

Examples:

Input: str = "bbbbbaaaaabbabababa", K = 5
Output: ababa
Explanation:
The substrings of length 5 from the above strings are {bbbbb, bbbba, bbbaa, bbaaa, baaaa, aaaaa, aaaab, aaabb, aabba, abbab, bbaba, babab, ababa, babab, ababa}.
Among all of them, substrings {ababa, babab} occurs the maximum number of times(= 2).
The lexicographically smallest string from {ababa, babab} is ababa.
Therefore, "ababa" is the required answer.

Input:  str = "heisagoodboy", K = 5
Output: agood
Explanation:
The substrings of length 5 from the above string are {heisa, eisag, isago, sagoo, agood, goodb, oodbo, odboy}.
All of them occur only once. But the lexicographically smallest string among them is "agood".
Therefore, "agood" is the required answer.

Naive Approach: The simplest approach to solve the problem is to generate all the substrings of size K from the given string and store the frequency of each substring in a Map. Then, traverse the Map and find the lexicographically smallest substring which occurs maximum number of times and print it. 


Output
ababa

Time Complexity: O(N*( K + log K))
Auxiliary Space: O(N * K)

Efficient Approach: To optimize the above approach, the idea is to use Sliding Window technique. Consider a window of size 
K to generate all substrings of length K and count the frequency of a substring generated in a Map. Traverse the map and find the substring that occurs maximum number of times and print it. If several of them exist, then print the lexicographically smallest substring.

Below is the implementation of the above approach.


Output
ababa

Time Complexity: O((N - K)*log(N - K))
Auxiliary Space: O(N - K)

Comment