Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Maximum frequencies in each M-length subarray
Next article icon

Maximum length substring with highest frequency in a string

Last Updated : 08 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string. The task is to find the maximum occurred substring with a maximum length. These occurrences can overlap.

Examples: 

Input: str = "abab" Output: ab "a", "b", "ab" are occur 2 times. But, "ab" has maximum length  Input: str = "abcd" Output: a

Approach: The idea is to store the frequency of each substring using a map and print the one with maximum frequency and maximum length. 

Below is the implementation of the above approach: 

C++




// C++ program to find maximum
// occurred substring of a string
#include <bits/stdc++.h>
using namespace std;
 
// function to return maximum
// occurred substring of a string
string MaxFreq(string str)
{
    // size of the string
    int n = str.size();
 
    unordered_map<string, int> m;
 
    for (int i = 0; i < n; i++) {
        string s = "";
        for (int j = i; j < n; j++) {
            s += str[j];
            m[s]++;
        }
    }
 
    // to store maximum frequency
    int maxi = 0;
 
    // to store string which has maximum frequency
    string s;
    for (auto i = m.begin(); i != m.end(); i++) {
        if (i->second > maxi) {
            maxi = i->second;
            s = i->first;
        }
        else if (i->second == maxi) {
            string ss = i->first;
            if (ss.size() > s.size())
                s = ss;
        }
    }
 
    // return substring which has maximum frequency
    return s;
}
 
// Driver program
int main()
{
    string str = "ababecdecd";
 
    // function call
    cout << MaxFreq(str);
 
    return 0;
}
 
 

Java




// Java program to find maximum
// occurred subString of a String
import java.util.*;
class GFG{
 
// Function to return maximum
// occurred subString of a String
static String MaxFreq(String str)
{
  // Size of the String
  int n = str.length();
 
  Map<String,
      Integer> mp = new HashMap<String,
                                Integer>();
 
  for (int i = 0; i < n; i++)
  {
    String s = "";
    for (int j = i; j < n; j++)
    {
      s += str.charAt(j);
      if(mp.containsKey(s))
      {
        mp.put(s, mp.get(s) + 1);
      }
      else
      {
        mp.put(s, 1);
      }
    }
  }
 
  // To store maximum frequency
  int maxi = 0;
 
  // To store String which
  // has maximum frequency
  String s = "";
  for (Map.Entry<String,
                 Integer> i : mp.entrySet())
  {
    if (i.getValue() > maxi)
    {
      maxi = i.getValue();
      s = i.getKey();
    }
    else if (i.getValue() == maxi)
    {
      String ss = i.getKey();
      if (ss.length() > s.length())
        s = ss;
    }
  }
 
  // Return subString which
  // has maximum frequency
  return s;
}
 
// Driver code
public static void main(String[] args)
{
  String str = "ababecdecd";
 
  // Function call
  System.out.print(MaxFreq(str));
}
}
 
// This code is contributed by shikhasingrajput
 
 

Python3




# Python3 program to find maximum
# occurred of a string
 
# function to return maximum occurred
# substring of a string
def MaxFreq(s):
     
    # size of string
    n = len(s)
     
    m = dict()
     
    for i in range(n):
        string = ''
        for j in range(i, n):
            string += s[j]
            if string in m.keys():
                m[string] += 1
            else:
                m[string] = 1
                 
    # to store maximum frequency
    maxi = 0
     
    # To store string which has
    # maximum frequency
    maxi_str = ''
     
    for i in m:
        if m[i] > maxi:
            maxi = m[i]
            maxi_str = i
        elif m[i] == maxi:
            ss = i
            if len(ss) > len(maxi_str):
                maxi_str = ss
                 
    # return substring which has maximum freq
    return maxi_str
     
# Driver code
string = "ababecdecd"
 
print(MaxFreq(string))
         
# This code is contributed by Mohit kumar 29    
 
 

C#




// C# program to find maximum
// occurred substring of a string
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return maximum
// occurred substring of a string
static string MaxFreq(string str)
{
     
    // Size of the string
    int n = str.Length;
     
    Dictionary<string,
               int> m = new Dictionary<string,
                                       int>();
                         
    for(int i = 0; i < n; i++)
    {
        string sp = "";
        for(int j = i; j < n; j++)
        {
            sp += str[j];
            if(m.ContainsKey(sp))
            {
                m[sp]++;
            }
            else
            {
                m[sp] = 1;
            }
        }
    }
 
    // To store maximum frequency
    int maxi = 0;
 
    // To store string which has maximum frequency
    string s = "";
     
    foreach(KeyValuePair<string, int> i in m)
    {
        if (i.Value > maxi)
        {
            maxi = i.Value;
            s = i.Key;
        }
        else if (i.Value == maxi)
        {
            string ss = i.Key;
            if (ss.Length > s.Length)
                s = ss;
        }
    }
 
    // Return substring which has
    // maximum frequency
    return s;
}
 
// Driver Code
public static void Main(string[] args)
{
    string str = "ababecdecd";
 
    // Function call
    Console.Write(MaxFreq(str));
}
}
 
// This code is contributed by rutvik_56
 
 

Javascript




<script>
 
// JavaScript program to find maximum
// occurred subString of a String
 
// Function to return maximum
// occurred subString of a String
function MaxFreq(str)
{
    // Size of the String
  let n = str.length;
  
  let mp = new Map();
  
  for (let i = 0; i < n; i++)
  {
    let s = "";
    for (let j = i; j < n; j++)
    {
      s += str[j];
      if(mp.has(s))
      {
        mp.set(s, mp.get(s) + 1);
      }
      else
      {
        mp.set(s, 1);
      }
    }
     }
  
  // To store maximum frequency
  let maxi = 0;
  
  // To store String which
  // has maximum frequency
  let s = "";
  for (let [key, value] of mp.entries())
  {
    if (value > maxi)
    {
      maxi = value;
      s = key;
    }
    else if (value == maxi)
    {
     let ss = key;
      if (ss.length > s.length)
        s = ss;
    }
  }
  
  // Return subString which
  // has maximum frequency
  return s;
}
 
 
// Driver code
 
let str = "ababecdecd";
 
// Function call
document.write(MaxFreq(str));
 
// This code is contributed by patel2127
 
</script>
 
 
Output
ecd

Time Complexity: O(n2), where n is the length of the given string.
Auxiliary Space: O(n), where n is the length of the given string.



Next Article
Maximum frequencies in each M-length subarray
author
pawan_asipu
Improve
Article Tags :
  • Competitive Programming
  • DSA
  • Hash
  • Strings
  • cpp-unordered_map
Practice Tags :
  • Hash
  • Strings

Similar Reads

  • Substring of length K having maximum frequency in the given string
    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 = 5Output: ababaExplanation:The sub
    14 min read
  • Substring with highest frequency length product
    Given a string which contains lower alphabetic characters, we need to find out such a substring of this string whose product of length and frequency in string is maximum among all possible choices of substrings. Examples: Input : String str = “abddab”Output : 6All unique substring with product of th
    15+ min read
  • Maximum frequencies in each M-length subarray
    Given an array arr[] consisting of N integers and a positive integer M, the task is to find the maximum frequency for each M-length subarray ( 0 < M ? N). Examples: Input: arr[] = {1, 2, 3, 1, 2, 4, 1, 4, 4}, M = 4Output: 2 2 1 2 2 3Explanation:All the M length sub-arrays with the maximum frequen
    8 min read
  • Find heaviest increasing Subsequence with maximum sum in a String
    Given a string s and an array arr[] representing the weights of each character in the string, the task is to find the heaviest increasing subsequence with the maximum sum and return that subsequence. Examples: Input: s = "acbde", arr[] = {2, 4, 3, 5, 1}Output: acdExplanation: The heaviest increasing
    8 min read
  • Frequency of a substring in a string using pthread
    Given an input string and a substring. Find the frequency of occurrences of a substring in the given string using pthreads. Examples: Input: string = "man" substring = "dhimanman"Output: 2Input: string = "banana" substring = "nn"Output: 0Note: It is advised to execute the program in Linux based syst
    6 min read
  • Frequency of a Substring in a String
    Given an input string and a pattern, the task is to find the frequency of occurrences of the string pattern in a given string. Examples: Input: pattern = "man", string = "dhimanman"Output: 2 Input: pattern = "nn", string = "Banana"Output: 0 Input: pattern = "aa", string = "aaaaa"Output : 4 Recommend
    14 min read
  • Count Substrings with Frequencies Less than Maximum Digit
    Given a string S of length N. Then your task is to find the count of substrings such that, the frequency of each digit in that substring must be less than the maximum digit of substring. Examples:Input: S = 122321Output: 13Explanation: Below are some of those substrings: S[1, 2]: 12. Max element = 2
    6 min read
  • Find the longest Substring of a given String S
    Given a string S of length, N. Find the maximum length of any substring of S such that, the bitwise OR of all the characters of the substring is equal to the bitwise OR of the remaining characters of the string. If no such substring exists, print -1. Examples: Input: S = "2347"Output: 3?Explanation:
    10 min read
  • Maximum Frequency by replacing with elements in a given range
    Given a 0-indexed array arr[] of N positive integers and two integers K and X. Find the maximum frequency of any element(not necessary to be present in the array) you can make after performing the below operation at most K times- Choose an index i and replace arr[i] with any integer from the range [
    9 min read
  • Find the first maximum length even word from a string
    Given a string of words separated by spaces. The task is to find the first maximum length even word from the string. Eg: “You are given an array of n numbers” The answer would be “an” and not “of” because “an” comes before “of”.Examples: Input: "this is a test string"Output: stringEven length words
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences