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
  • Practice Combinatorics
  • MCQs on Combinatorics
  • Basics of Combinatorics
  • Permutation and Combination
  • Permutation Vs Combination
  • Binomial Coefficient
  • Calculate nPr
  • Calculate nCr
  • Pigeonhole Principle
  • Principle of Inclusion-Exclusion
  • Catalan Number
  • Lexicographic Rank
  • Next permutation
  • Previous Permutation
Open In App
Next Article:
Longest Substring Without Repeating Characters
Next article icon

Largest substring with same Characters

Last Updated : 25 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s of size N. The task is to find the largest substring which consists of the same characters
Examples: 
 

Input : s = “abcdddddeff” 
Output : 5 
Substring is “ddddd”
Input : s = aabceebeee 
Output : 3 
 

 

Approach : 
Traverse through the string from left to right. Take two variables ans and temp. If the current element is the same as the previous element then increment temp. If the current element is not equal to the previous element then make temp as 1 and update ans.
Below is the implementation of the above approach : 
 

C++




// CPP program to find largest sub
// string with same characters
#include <bits/stdc++.h>
using namespace std;
 
// Function to find largest sub
// string with same characters
int Substring(string s)
{
 
    int ans = 1, temp = 1;
 
    // Traverse the string
    for (int i = 1; i < s.size(); i++) {
        // If character is same as
        // previous increment temp value
        if (s[i] == s[i - 1]) {
            ++temp;
        }
        else {
            ans = max(ans, temp);
            temp = 1;
        }
    }
    ans = max(ans, temp);
 
    // Return the required answer
    return ans;
}
 
// Driver code
int main()
{
    string s = "abcdddddeff";
 
    // Function call
    cout << Substring(s);
 
    return 0;
}
 
 

Java




// Java program to find largest sub
// string with same characters
import java.util.*;
 
class GFG
{
 
// Function to find largest sub
// string with same characters
static int Substring(String s)
{
    int ans = 1, temp = 1;
 
    // Traverse the string
    for (int i = 1; i < s.length(); i++)
    {
        // If character is same as
        // previous increment temp value
        if (s.charAt(i) == s.charAt(i - 1))
        {
            ++temp;
        }
        else
        {
            ans = Math.max(ans, temp);
            temp = 1;
        }
    }
    ans = Math.max(ans, temp);
 
    // Return the required answer
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String s = "abcdddddeff";
 
    // Function call
    System.out.println(Substring(s));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program to find largest sub
# with same characters
 
# Function to find largest sub
# with same characters
def Substring(s):
 
    ans, temp = 1, 1
 
    # Traverse the string
    for i in range(1, len(s)):
         
        # If character is same as
        # previous increment temp value
        if (s[i] == s[i - 1]):
            temp += 1
        else:
            ans = max(ans, temp)
            temp = 1
 
    ans = max(ans, temp)
 
    # Return the required answer
    return ans
 
# Driver code
s = "abcdddddeff"
 
# Function call
print(Substring(s))
 
# This code is contributed by Mohit Kumar
 
 

C#




// C# program to find largest sub
// string with same characters
using System;
class GFG
{
 
// Function to find largest sub
// string with same characters
static int Substring(String s)
{
    int ans = 1, temp = 1;
 
    // Traverse the string
    for (int i = 1; i < s.Length; i++)
    {
        // If character is same as
        // previous increment temp value
        if (s[i] == s[i - 1])
        {
            ++temp;
        }
        else
        {
            ans = Math.Max(ans, temp);
            temp = 1;
        }
    }
    ans = Math.Max(ans, temp);
 
    // Return the required answer
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    String s = "abcdddddeff";
 
    // Function call
    Console.WriteLine(Substring(s));
}
}
 
// This code is contributed by Rajput-Ji
 
 

PHP




<?php
// PHP program to find largest sub
// string with same characters
 
// Function to find largest sub
// string with same characters
function Substring($s)
{
    $ans = 1;
    $temp = 1;
     
    // Traverse the string
    for ($i = 1; $i < strlen($s); $i++)
    {
         
        // If character is same as
        // previous increment temp value
        if ($s[$i] == $s[$i - 1])
        {
            ++$temp;
        }
        else
        {
            $ans = max($ans, $temp);
            $temp = 1;
        }
    }
     
    $ans = max($ans, $temp);
 
    // Return the required answer
    return $ans;
}
 
// Driver code
$s = "abcdddddeff";
 
// Function call
echo Substring($s);
     
// This code is contributed by Naman_Garg
?>
 
 

Javascript




<script>
 
// Javascript program to find largest sub
// string with same characters
 
// Function to find largest sub
// string with same characters
function Substring(s)
{
 
    var ans = 1, temp = 1;
 
    // Traverse the string
    for (var i = 1; i < s.length; i++) {
        // If character is same as
        // previous increment temp value
        if (s[i] == s[i - 1]) {
            ++temp;
        }
        else {
            ans = Math.max(ans, temp);
            temp = 1;
        }
    }
    ans = Math.max(ans, temp);
 
    // Return the required answer
    return ans;
}
 
// Driver code
var s = "abcdddddeff";
// Function call
document.write( Substring(s));
 
</script>
 
 

Output: 
 

5

Time Complexity: O(N)

Auxiliary Space: O(1)
 



Next Article
Longest Substring Without Repeating Characters

S

ShivamKumarsingh1
Improve
Article Tags :
  • Analysis of Algorithms
  • Combinatorial
  • DSA
  • Greedy
  • Strings
  • substring
Practice Tags :
  • Combinatorial
  • Greedy
  • Strings

Similar Reads

  • Longest Substring Without Repeating Characters
    Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples: Input: s = "geeksforgeeks"Output: 7 Explanation: The longest substrings without repeating characters are "eksforg” and "ksforge", with lengths of 7. Input: s = "aaa"Output:
    12 min read
  • Longest substring with k unique characters
    Given a string you need to print longest possible substring that has exactly k unique characters. If there is more than one substring of longest possible length, then print any one of them. Note:- Source(Google Interview Question). Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max subs
    13 min read
  • Count substrings with same first and last characters
    Given a string s consisting of lowercase characters, the task is to find the count of all substrings that start and end with the same character. Examples : Input : s = "abcab"Output : 7Explanation: The substrings are "a", "abca", "b", "bcab", "c", "a", "b".Input : s = "aba"Output : 4Explanation: The
    7 min read
  • Print Longest substring without repeating characters
    Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples: Input: s = “geeksforgeeks”Output: 7 Explanation: The longest substrings without repeating characters are “eksforg” and “ksforge”, with lengths of 7. Input: s = “aaa”Output:
    14 min read
  • Length of the longest substring with consecutive characters
    Given string str of lowercase alphabets, the task is to find the length of the longest substring of characters in alphabetical order i.e. string "dfabck" will return 3. Note that the alphabetical order here is considered circular i.e. a, b, c, d, e, ..., x, y, z, a, b, c, .... Examples: Input: str =
    7 min read
  • Find length of longest substring with at most K normal characters
    Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters. Examples: Input : P =
    12 min read
  • Split string to get maximum common characters
    Given a string S of length, N. Split them into two strings such that the number of common characters between the two strings is maximized and return the maximum number of common characters. Examples: Input: N = 6, S = abccbaOutput: 3Explanation: Splitting two strings as "abc" and "cba" has at most 3
    6 min read
  • Group words with same set of characters
    Given a list of words with lower cases. Implement a function to find all Words that have the same unique character set. Example: Input: words[] = { "may", "student", "students", "dog", "studentssess", "god", "cat", "act", "tab", "bat", "flow", "wolf", "lambs", "amy", "yam", "balms", "looped", "poodl
    8 min read
  • String with maximum number of unique characters
    Given an array of strings, the task is to print the string with the maximum number of unique characters. Note: Strings consists of lowercase characters.If multiple strings exists, then print any one of them.Examples: Input: arr[] = ["abc", "geeksforgeeks", "gfg", "code"]Output: "geeksforgeeks" Expla
    5 min read
  • Longest substring such that no three consecutive characters are same
    Given string str, the task is to find the length of the longest substring of str such that no three consecutive characters in the substring are same.Examples: Input: str = "baaabbabbb" Output: 7 "aabbabb" is the required substring.Input: str = "babba" Output: 5 Given string itself is the longest sub
    6 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