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 String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Find minimum number of Substrings with unique characters
Next article icon

Count the minimum number of groups formed in a string

Last Updated : 18 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string ‘S’ which comprises two or more uppercase English letters. The task is to count the minimum number of groups required to completely cover the string by replacing consecutive characters with the same single character.

Examples:  

Input : S = "TTWWW"
Output : 2
Explanation :
There are 2 groups formed. One by covering the 2 consecutive T and the other by 3 consecutive W.
Input : S = "FFMMMF"
Output : 3
Explanation :
Minimum number of groups formed is 3 that is two F's, three M's and one F .
Note: Three F's were not included in one group because they are not consecutive in the string s.
Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: 
To solve the problem mentioned above the main idea is to compare the adjacent characters in the string ‘S’ one by one. If for instance, the characters are different that is the consecutive letters of the string are not the same then, the counter for the total group formed is incremented by 1 and so on until we reach the length if the string.

Below is the implementation of the above-mentioned approach:  

C++




// C++ implementation to Count the
// minimum number of groups formed in a string
// by replacing consecutive characters
// with same single character
#include<bits/stdc++.h>
 
using namespace std;
 
// Function to count the minimum number
// of groups formed in the given string s
void group_formed(string S){
 
    // Initializing count as one since
    // the string is not NULL
    int count = 1;
 
    for (int i = 0; i < S.size() - 1; i++){
 
        // Comparing adjacent characters
        if ( S[i] != S[i+1])
            count += 1;
          }
 
    cout << (count);
  }
 
// Driver Code
int main(){
    string S = "TTWWW";
 
    group_formed(S);
  }
 
// This code is contributed by mohit kumar 29
 
 

Java




// Java implementation to Count the
// minimum number of groups formed in a string
// by replacing consecutive characters
// with same single character
class GFG {
     
    // Function to count the minimum number
    // of groups formed in the given string s
    static void group_formed(String S){
     
        // Initializing count as one since
        // the string is not NULL
        int count = 1;
     
        for (int i = 0; i < S.length() - 1; i++){
     
            // Comparing adjacent characters
            if ( S.charAt(i) != S.charAt(i+1))
                count += 1;
            }
     
        System.out.println(count);
    }
     
    // Driver Code
    public static void main (String[] args) {
        String S = "TTWWW";
     
        group_formed(S);
    }
}
 
 // This code is contributed by AnkitRai01
 
 

Python3




# Python3 implementation to Count the
# minimum number of groups formed in a string
# by replacing consecutive characters
# with same single character
 
# Function to count the minimum number
# of groups formed in the given string s
def group_formed(S):
     
    # Initializing count as one since
    # the string is not NULL
    count = 1
     
    for i in range (len(S)-1):
        a = S[i]
        b = S[i + 1]
         
        # Comparing adjacent characters
        if ( a != b):
             
            count += 1
             
    print (count)
 
# Driver Code
if __name__ == "__main__":
    S = "TTWWW"
     
    group_formed(S)
 
 

C#




// C# implementation to Count the
// minimum number of groups formed
// in a string by replacing consecutive
// characters with same single character
using System;
 
class GFG{
     
// Function to count the minimum number
// of groups formed in the given string s
static void group_formed(String S)
{
     
    // Initializing count as one since
    // the string is not NULL
    int count = 1;
     
    for(int i = 0; i < S.Length - 1; i++)
    {
        
       // Comparing adjacent characters
       if (S[i] != S[i + 1])
           count += 1;
    }
    Console.Write(count);
}
     
// Driver Code
public static void Main (String[] args)
{
    String S = "TTWWW";
     
    group_formed(S);
}
}
 
// This code is contributed by Rajnis09
 
 

Javascript




<script>
 
// Javascript implementation to Count the
// minimum number of groups formed
// in a string by replacing consecutive
// characters with same single character
 
// Function to count the minimum number
// of groups formed in the given string s
function group_formed(S)
{
     
    // Initializing count as one since
    // the string is not NULL
    let count = 1;
 
    for(let i = 0; i < S.length - 1; i++)
    {
         
        // Comparing adjacent characters
        if (S[i] != S[i + 1])
            count += 1;
    }
    document.write(count);
}
 
// Driver code
let S = "TTWWW";
   
group_formed(S);
 
// This code is contributed by divyesh072019 
 
</script>
 
 
Output
2       

Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Approach:

  • We can use stack to solve this problem.
  • Traverse the given string character by character and push each character onto the stack if it is not the same as the top of the stack.
  •  If it is the same as the top of the stack, we can pop the top element of the stack and push the new character onto the stack.
  • At the end, the size of the stack will give us the minimum number of groups required.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
int minGroups(string s) {
    stack<char> st;
    int n = s.size();
    for (int i = 0; i < n; i++) {
        if (st.empty() || s[i] != st.top()) {
            st.push(s[i]);
        } else {
            st.pop();
            st.push(s[i]);
        }
    }
    return st.size();
}
 
int main() {
    string s = "TTWWW";
    cout << minGroups(s) << endl;
    return 0;
}
 
 

Java




import java.util.Stack;
 
public class GFG {
        static int minGroups(String s) {
        Stack<Character> stack = new Stack<>();
        int n = s.length();
        for (int i = 0; i < n; i++) {
            if (stack.isEmpty() || s.charAt(i) != stack.peek()) {
                stack.push(s.charAt(i));
            } else {
                stack.pop();
                stack.push(s.charAt(i));
            }
        }
        return stack.size();
    }
 
    // Driver code
    public static void main(String[] args) {
        String s = "TTWWW";
        System.out.println(minGroups(s));
    }
}
 
 

Python3




def minGroups(s):
    st = []
    n = len(s)
    for i in range(n):
        if not st or s[i] != st[-1]:
            st.append(s[i])
        else:
            st.pop()
            st.append(s[i])
    return len(st)
 
def main():
    s = "TTWWW"
    print(minGroups(s))
 
if __name__ == "__main__":
    main()
 
 

C#




using System;
using System.Collections.Generic;
 
class Program {
    // Function to calculate the minimum number of groups
    static int MinGroups(string s)
    {
        Stack<char> st = new Stack<char>();
        int n = s.Length;
        for (int i = 0; i < n; i++) {
            // If the stack is empty or the current
            // character is different from the top of the
            // stack, push the current character onto the
            // stack.
            if (st.Count == 0 || s[i] != st.Peek()) {
                st.Push(s[i]);
            }
            // If the current character is the same as the
            // top of the stack, pop the top character from
            // the stack and then push the current
            // character.
            else {
                st.Pop();
                st.Push(s[i]);
            }
        }
        return st.Count;
    }
 
    static void Main()
    {
        string s = "TTWWW";
        // Call the MinGroups function and print the result
        Console.WriteLine(MinGroups(s));
    }
}
 
 

Javascript




// Function to find the minimum number of groups required
function minGroups(s) {
    // Create an empty stack to store characters
    const stack = [];
    const n = s.length;
 
    // Iterate through the input string
    for (let i = 0; i < n; i++) {
        // If the stack is empty or the current character is different from the top of the stack
        if (stack.length === 0 || s[i] !== stack[stack.length - 1]) {
            // Push the current character onto the stack
            stack.push(s[i]);
        } else {
            // If the current character is the same as the top of the stack, pop it (canceling out adjacent duplicates)
            stack.pop();
            // Push the current character onto the stack again (forming a new group)
            stack.push(s[i]);
        }
    }
 
    // The length of the stack represents the minimum number of groups required
    return stack.length;
}
 
// Driver code
const s = "TTWWW";
console.log(minGroups(s));
 
 
Output
2        

Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(n), since we are using stack.



Next Article
Find minimum number of Substrings with unique characters

P

parna_28
Improve
Article Tags :
  • DSA
  • Strings
Practice Tags :
  • Strings

Similar Reads

  • Minimize number of unique characters in string
    Given two strings A and B. Minimize the number of unique characters in string A by either swapping A[i] with B[i] or keeping it unchanged. The number of swaps can be greater than or equal to 0. Note that A[i] can be swapped only with same index element in B. Print the minimum number of unique charac
    11 min read
  • Find minimum number of Substrings with unique characters
    Given string 's', the task is to divide a given string s into multiple substrings, with each substring containing only unique characters. This means that no character should be repeated within a single substring. The goal is to find the minimum number of such substrings required to satisfy this cond
    12 min read
  • Find the minimum number of distinct Substrings formed by 0s in Binary String
    Given two integers N and M, the task is to output the minimum number of different substrings that can be formed using the Binary String of length N having M number of set bits. Note: Two substrings let say S[x, y] and S[a, b] are different. If either x != a or y != b. Examples: Input: N = 3, M = 1Ou
    6 min read
  • Concatenate strings in any order to get Maximum Number of "AB"
    Given an array of strings of length N, it is allowed to concatenate them in any order. Find the maximum possible number of occurrences of 'AB' in the resulting string. Examples: Input : N = 4, arr={ "BCA", "BGGGA", "JKA", "BALB" } Output : 3 Concatenate them in the order JKA + BGGA + BCA + BALB and
    9 min read
  • Count the number of unique characters in a given String
    Given a string, str consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: str = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 7 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}. Inp
    14 min read
  • Minimum cost to construct a string
    Given a string s (containing lowercase letters only), we have to find the minimum cost to construct the given string. The cost can be determined using the following operations: Appending a single character cost 1 unit A sub-string of a new string(intermediate string) can be appended without any cost
    5 min read
  • Count the number of Unique Characters in a String in Python
    We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8. Using setSet in Python is an unordered collection of unique elements automatically removing d
    2 min read
  • Maximum number of groups of size 3 containing two type of items
    Given n instance of item A and m instance of item B. Find the maximum number of groups of size 3 that can be formed using these items such that all groups contain items of both types, i.e., a group should not have either all items of type A or all items of type B. The total number of items of type A
    10 min read
  • Count number of distinct substrings of a given length
    Given a string S of length N consisting of lower-case English alphabets and an integer 'l', find the number of distinct substrings of length 'l' of the given string. Examples: Input : s = "abcbab", l = 2 Output : 4 All distinct sub-strings of length 2 will be {"ab", "bc", "cb", "ba"} Thus, answer eq
    6 min read
  • Number of ways to form a given String from the given set of Strings
    Given a string str and an array of strings dictionary[], the task is to find the number of ways str can be formed as a concatenation of strings (any number of times) in a dictionary[]. Examples: Input: str = abab, dictionary[] = { a, b, ab }Output: 4Explanation: There are 4 ways to form string str a
    15+ 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