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 the number of Substrings with even number of K
Next article icon

Find minimum number of Substrings with unique characters

Last Updated : 19 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 condition.

Examples:

Input: s = "abacaba"
Output: 4
Explanation: Two possible partitions are ("a", "ba", "cab", "a") and ("ab", "a", "ca", "ba"). It can be shown that 4 is the minimum number of substrings needed.

Input: s = "ssssss"
Output: 6
Explanation: The only valid partition is ("s", "s", "s", "s", "s", "s").

Naive Approach: The basic way to solve the problem follows the below idea:

  • We initialize an empty set and iterate through the given string. For each character encountered, we check if it is already present in the set. 
  • If it is, this means that we need to start a new substring since the current substring has a repeated character. We increase our answer variable and clear the set to start a new substring. We then add the current character to the set.
  • After iterating through the entire string, the value of the answer variable gives us the minimum number of substrings required to partition the given string such that each substring has unique characters.

Below is the implementation for the above approach:

C++
// C++ program to Finding minimum number // of Substrings with unique Characters #include <bits/stdc++.h> using namespace std;  // Function to Find Minimum Number of // Substrings with Unique Characters int partitionString(string s) {      // Create an unordered set to     // store unique characters     unordered_set<char> st;      // Initialize the answer     // variable to 1     int ans = 1;      // Iterate through the given string     for (int i = 0; i < s.size(); i++) {          // Check if the current character         // is already present in the set         if (st.find(s[i]) != st.end()) {              // If it is, increment the             // answer variable and clear             // the set to start a             // new substring             ans++;             st.clear();         }          // Add the current character         // to the set         st.insert(s[i]);     }      // Return the answer variable, which     // gives the minimum number     // of substrings required     return ans; }  // Drivers code int main() {     string S = "abacaba";      // Function Call     cout << "Minimum Number of Substrings with Unique "             "Characters: "          << partitionString(S);      return 0; } 
Java
// Java program to Finding Minimum Number of Substrings with // Unique Characters import java.util.*;  // Function to Find Minimum Number of Substrings with Unique // Characters class GFG {     static int partitionString(String s)     {         // Create a HashSet to store unique characters         Set<Character> set = new HashSet<>();         // Initialize the answer variable to 1         int ans = 1;         // Iterate through the given string         for (int i = 0; i < s.length(); i++) {             // Check if the current character is already             // present in the set             if (set.contains(s.charAt(i))) {                 // If it is, increment the answer variable                 // and clear the set to start a new                 // substring                 ans++;                 set.clear();             }             // Add the current character to the set             set.add(s.charAt(i));         }         // Return the answer variable, which gives the         // minimum number of substrings required         return ans;     }      public static void main(String[] args)     {         String S = "abacaba";          System.out.print(partitionString(S));     } } // This code is contributed by Ravi Singh 
Python3
# Function to Find Minimum Number of # Substrings with Unique Characters def partitionString(s):     # Create an unordered set to     # store unique characters     st = set()      # Initialize the answer     # variable to 1     ans = 1      # Iterate through the given string     for i in range(len(s)):         # Check if the current character         # is already present in the set         if s[i] in st:             # If it is, increment the             # answer variable and clear             # the set to start a             # new substring             ans += 1             st.clear()          # Add the current character         # to the set         st.add(s[i])      # Return the answer variable, which     # gives the minimum number     # of substrings required     return ans   # Drivers code S = "abacaba"  # Function Call print("Minimum Number of Substrings with Unique Characters:", partitionString(S)) 
C#
// C# program to Finding Minimum Number of Substrings with // Unique Characters  using System; using System.Collections.Generic;  public class GFG {      static int partitionString(string s)     {         // Create a HashSet to store unique characters         HashSet<char> set = new HashSet<char>();         // Initialize the answer variable to 1         int ans = 1;         // Iterate through the given string         for (int i = 0; i < s.Length; i++) {             // Check if the current character is already             // present in the set             if (set.Contains(s[i])) {                 // If it is, increment the answer variable                 // and clear the set to start a new                 // substring                 ans++;                 set.Clear();             }             // Add the current character to the set             set.Add(s[i]);         }         // Return the answer variable, which gives the         // minimum number of substrings required         return ans;     }      static public void Main()     {          // Code         String S = "abacaba";          Console.Write("Minimum Number of Substrings with Unique Characters: " + partitionString(S));     } }  // THis code is contributed by karthik 
JavaScript
// JavaScript program to Finding minimum number // of Substrings with unique Characters  // Function to Find Minimum Number of Substrings with Unique // Characters function partitionString(s) {     // Create a set to store unique characters     let st = new Set();      // Initialize the answer     // variable to 1     let ans = 1;      // Iterate through the given string     for (let i = 0; i < s.length; i++) {          // Check if the current character         // is already present in the set         if (st.has(s[i])) {              // If it is, increment the             // answer variable and clear             // the set to start a             // new substring             ans++;             st.clear();         }          // Add the current character         // to the set         st.add(s[i]);     }      // Return the answer variable, which     // gives the minimum number     // of substrings required     return ans; }  // Driver code let S = "abacaba";  // Function Call console.log(     "Minimum Number of Substrings with Unique Characters: "     + partitionString(S)); 

Output
Minimum Number of Substrings with Unique Characters: 4

Time Complexity: O(n) where n is the length of the input string.
Auxiliary Space: O(n) in the worst case This is because we store each character of the input string in the hash set, and in the worst case, all characters of the string are unique. 

Efficient Approach: To solve the problem using a Greedy approach follow the below idea:

To solve this problem, we need to keep track of the last occurrence of each character in the string s. Whenever we encounter a repeated character, we know that the current substring contains a character that is repeated, so we need to start a new substring. We can determine the start of the new substring by setting the value of start to the index of the repeated character. We also increased the value of ans to indicate that we have started a new substring.

Below are the steps for the above approach:

  • Create an array list of size 26 to store the last index of each character (initially set to -1).
    Initialize the starting index of the current substring to 0.
  • Initialize the answer variable ans to 1.
  • Iterate through the given string s:
    • Get the index of the current character in the array by subtracting 'a' from it.
    • Check if the current character is already present in the current substring by comparing its last index with the starting index of the current substring.
    • If it is, increment the answer variable ans and update the starting index of the new substring to the current index.
  • Update the last index of the current character in the array with the current index.
  • Return the answer variable ans, which gives the minimum number of substrings required.

Below is the implementation for the above approach:

C++
// C++ program to Finding Minimum // Number of Substrings with // Unique Characters  #include <bits/stdc++.h> using namespace std;  // Function to Find Minimum Number of // Substrings with Unique characters int partitionString(string s) {      // Create an array to store the     // last index of each character     vector<int> last(26, -1);      // Initialize the starting index     // of the current substring to 0     int start = 0;      // Initialize the answer variable to 1     int ans = 1;      // Iterate through the given string     for (int i = 0; i < s.length(); i++) {          // Get the index of the current         // character in the array         int index = s[i] - 'a';          // Check if the current character         // is already present in the         // current substring         if (last[index] >= start) {              // If it is, increment the answer             // variable and update the             // starting index of the             // new substring             ans++;             start = i;         }          // Update the last index         // of the current character         last[index] = i;     }      // Return the answer variable, which     // gives the minimum number of     // substrings required     return ans; }  // Drivers code int main() {      string S = "abacaba";      // Function Call     cout << "Minimum Number of Substrings with Unique "             "Characters: "          << partitionString(S);      return 0; } 
Java
// Java program to Finding Minimum Number of Substrings with // Unique Characters import java.util.*;  // Function to Find Minimum Number of Substrings with Unique // Characters  class GFG {     static int partitionString(String s)     {         // Create an array to store the last index of each         // character         int[] last = new int[26];         Arrays.fill(last, -1);          // Initialize the starting index of the current         // substring to 0         int start = 0;          // Initialize the answer variable to 1         int ans = 1;          // Iterate through the given string         for (int i = 0; i < s.length(); i++) {             // Get the index of the current character in the             // array             int index = s.charAt(i) - 'a';              // Check if the current character is already             // present in the current substring             if (last[index] >= start) {                 // If it is, increment the answer variable                 // and update the starting index of the new                 // substring                 ans++;                 start = i;             }              // Update the last index of the current             // character             last[index] = i;         }          // Return the answer variable, which gives the         // minimum number of substrings required         return ans;     }      public static void main(String[] args)     {          String S = "ssssss";          System.out.print(partitionString(S));     } } // This code is contributed by Ravi Singh 
Python3
# Function to Find Minimum Number of # Substrings with Unique characters def partitionString(s):     # Create an array to store the     # last index of each character     last = [-1] * 26      # Initialize the starting index     # of the current substring to 0     start = 0      # Initialize the answer variable to 1     ans = 1      # Iterate through the given string     for i in range(len(s)):         # Get the index of the current         # character in the array         index = ord(s[i]) - ord('a')          # Check if the current character         # is already present in the         # current substring         if last[index] >= start:             # If it is, increment the answer             # variable and update the             # starting index of the             # new substring             ans += 1             start = i          # Update the last index         # of the current character         last[index] = i      # Return the answer variable, which     # gives the minimum number of     # substrings required     return ans   # Drivers code if __name__ == '__main__':     S = "abacaba"      # Function Call     print("Minimum Number of Substrings with Unique Characters: ", partitionString(S)) 
C#
using System; using System.Collections.Generic;  public class Program {   // Function to find minimum number of substrings with unique characters   public static int PartitionString(string s)   {     // Create a dictionary to store the last index of each character     Dictionary<char, int> last = new Dictionary<char, int>();      // Initialize the starting index of the current substring to 0     int start = 0;      // Initialize the answer variable to 1     int ans = 1;      // Iterate through the given string     for (int i = 0; i < s.Length; i++)     {       char c = s[i];        // Check if the current character is       // already present in the current substring       if (last.ContainsKey(c) && last[c] >= start)       {         // If it is, increment the answer variable and         // update the starting index of the new substring         ans++;         start = i;       }        // Update the last index of the current character       last[c] = i;     }      // Return the answer variable, which gives      // the minimum number of substrings required     return ans;   }    // Driver's code   public static void Main()   {     string S = "abacaba";      // Function call     Console.WriteLine("Minimum Number of Substrings with Unique Characters: " + PartitionString(S));   } } // This code is contributed by Prajwal Kandekar 
JavaScript
// JavaScript program to Finding Minimum // Number of Substrings with // Unique Characters  function partitionString(s) {    // Create an array to store the   // last index of each character   const last = new Array(26).fill(-1);    // Initialize the starting index   // of the current substring to 0   let start = 0;    // Initialize the answer variable to 1   let ans = 1;    // Iterate through the given string   for (let i = 0; i < s.length; i++) {      // Get the index of the current     // character in the array     const index = s.charCodeAt(i) - 97;      // Check if the current character     // is already present in the     // current substring     if (last[index] >= start) {        // If it is, increment the answer       // variable and update the       // starting index of the       // new substring       ans++;       start = i;     }      // Update the last index     // of the current character     last[index] = i;   }    // Return the answer variable, which   // gives the minimum number of   // substrings required   return ans; }  // Example usage const S = "abacaba"; console.log(`Minimum Number of Substrings with Unique Characters: ${partitionString(S)}`); 

Output
Minimum Number of Substrings with Unique Characters: 4

Time Complexity: O(n) where n is the length of the input string.
Auxiliary Space: O(1)


Next Article
Find the number of Substrings with even number of K
author
the_ravisingh
Improve
Article Tags :
  • Strings
  • Greedy
  • DSA
  • Set
  • Greedy Algorithms
  • substring
Practice Tags :
  • Greedy
  • set
  • Strings

Similar Reads

  • 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 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
  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Find the number of Substrings with even number of K
    Given a string str of length N and an integer K, the task is to count the number of substrings with even numbers of K. It means the count of 'K' in each substring will be even and must not be zero. Examples: Input: N = 4, str = "2131", K = 1Output: 2 Explanation: There are two substrings "2131" and
    8 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
  • Number of substrings with each character occurring even times
    Given a string S consisting of N lowercase alphabets, the task is to count the number of substrings whose frequency of each character is even. Examples: Input: S = "abbaa"Output: 4Explanation:The substrings having frequency of each character is even are {"abba", "aa", "bb", "bbaa"}.Therefore, the co
    14 min read
  • Number of substrings with count of each character as k
    Given a string and an integer k, find the number of substrings in which all the different characters occur exactly k times. Examples: Input : s = "aabbcc" k = 2 Output : 6 The substrings are aa, bb, cc, aabb, bbcc and aabbcc. Input : s = "aabccc" k = 2 Output : 3 There are three substrings aa, cc an
    15 min read
  • Count the minimum number of groups formed in a string
    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 : 2Explanation : There are 2 gro
    7 min read
  • Count substrings with k distinct characters
    Given a string consisting of lowercase characters and an integer k, the task is to count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Examples: Input: s = "abc", k = 2Output: 2Explanation: Possible substrings are {"ab", "bc"} Input: s = "aba", k = 2Outp
    10 min read
  • Number of substrings with equal character frequencies and fixed distance
    Given a string S and an integer K, the task is to count the number of substrings which have each character exactly K times and maximum distance between two same characters <= K. Examples: Input: S= " de", K = 2Output: 3Explanation: "abab", "ababcc" and "cc" are substrings having each character ex
    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