Most Frequent Substring of Length K

This program finds most frequent substring of length K.

Problem Statement

Write a Java program to find most frequent substring of length 2 in "abcabcabc".

Source Code

1 import java.util.HashMap;
2 public class MostFrequentSubstringK {
3 public static void main(String[] args) {
4 System.out.println("Eduinq Most Frequent Substring K");
5 String str="abcabcabc"; int k=2;
6 HashMap<String,Integer> map=new HashMap<>();
7 for(int i=0;i<=str.length()-k;i++){
8 String sub=str.substring(i,i+k);
9 map.put(sub,map.getOrDefault(sub,0)+1);
10 }
11 String maxSub=""; int maxFreq=0;
12 for(String key:map.keySet()){
13 if(map.get(key)>maxFreq){ maxFreq=map.get(key); maxSub=key; }
14 }
15 System.out.println("Most frequent substring: "+maxSub+" occurs "+maxFreq+" times");
16 }
17 }

Program Output

Eduinq Most Frequent Substring K
Most frequent substring: ab occurs 3 times

Explanation

A loop slides across the string extracting every substring of length k and stores their frequencies in a HashMap, then a second loop finds the substring with the highest frequency, demonstrating fixed-length substring frequency analysis.

Quick Links to Explore