The Wayback Machine - https://web.archive.org/web/20240624030821/https://www.geeksforgeeks.org/split-a-string-into-maximum-number-of-unique-substrings/
Open In App

Split a string into maximum number of unique substrings

Last Updated : 18 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given string str, the task is to split the string into the maximum number of unique substrings possible and print their count.

Examples: 

Input: str = “ababccc”
Output: 5
Explanation:
Split the given string into the substrings “a”, “b”, “ab”, “c” and “cc”.
Therefore, the maximum count of unique substrings is 5.

Input: str = “aba”
Output: 2

Approach: The problem can be solved by the Greedy approach. Follow the steps below to solve the problem: 

  1. Initialize a Set S.
  2. Iterate over the characters of the string str and for each i and find the substring up to that index.
  3. If the given substring is not present in the Set S, insert it updates the maximum count, and remove it from the Set, because the same character cannot be reused.
  4. Return the maximum count.

Below is the implementation of the above approach:

C++

// CPP program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Utility function to find maximum count of
// unique substrings by splitting the string
int maxUnique(string S, set<string> st)
{
 
  // Stores maximum count of unique substring
  // by splitting the string into substrings
  int mx = 0;
 
  // Iterate over the characters of the string
  for (int i = 1; i <= S.length(); i++)
  {
 
    // Stores prefix substring
    string tmp = S.substr(0, i);
 
    // Check if the current substring
    // already exists
    if (st.find(tmp) == st.end())
    {
 
      // Insert tmp into set
      st.insert(tmp);
 
      // Recursively call for remaining
      // characters of string
      mx = max(mx, maxUnique(S.substr(i), st) + 1);
 
      // Remove from the set
      st.erase(tmp);
    }
  }
 
  // Return answer
  return mx;
}
 
 
// Function to find the maximum count of
// unique substrings by splitting a string
// into maximum number of unique substrings
int maxUniqueSplit(string S)
{
  set<string> st;
  return maxUnique(S, st);
}
 
// Driver Code
int main()
{
  string S = "ababccc";
  int res = maxUniqueSplit(S);
 
  cout<<res;
}
 
// This code is contributed by jana_sayantan.

                    

Java

// Java program for the above approach
import java.io.*;
import java.util.*;
class Solution {
 
    // Function to find the maximum count of
    // unique substrings by splitting a string
    // into maximum number of unique substrings
    public int maxUniqueSplit(String S)
    {
        return maxUnique(S, new HashSet<String>());
    }
 
    // Utility function to find maximum count of
    // unique substrings by splitting the string
    public int maxUnique(String S, Set<String> set)
    {
 
        // Stores maximum count of unique substring
        // by splitting the string into substrings
        int max = 0;
 
        // Iterate over the characters of the string
        for (int i = 1; i <= S.length(); i++) {
 
            // Stores prefix substring
            String tmp = S.substring(0, i);
 
            // Check if the current substring
            // already exists
            if (!set.contains(tmp)) {
 
                // Insert tmp into set
                set.add(tmp);
 
                // Recursively call for remaining
                // characters of string
                max = Math.max(max, maxUnique(
                                        S.substring(i), set)
                                        + 1);
 
                // Remove from the set
                set.remove(tmp);
            }
        }
 
        // Return answer
        return max;
    }
}
 
// Driver Code
class GFG {
 
    public static void main(String[] args)
    {
        Solution st = new Solution();
        String S = "ababccc";
        int res = st.maxUniqueSplit(S);
 
        System.out.println(res);
    }
}

                    

Python3

# Python3 program for the above approach
 
# Utility function to find maximum count of
# unique substrings by splitting the string
def maxUnique(S):
    global d
 
    # Stores maximum count of unique substring
    # by splitting the string into substrings
    maxm = 0
 
    # Iterate over the characters of the string
    for i in range(1, len(S) + 1):
 
        # Stores prefix substring
        tmp = S[0:i]
 
        # Check if the current substring
        # already exists
        if (tmp not in d):
 
            # Insert tmp into set
            d[tmp] = 1
 
            # Recursively call for remaining
            # characters of string
            maxm = max(maxm, maxUnique(S[i:]) + 1)
 
            # Remove from the set
            del d[tmp]
 
    # Return answer
    return maxm
 
# Driver Code
if __name__ == '__main__':
   
    # Solution st = new Solution()
    S = "ababccc"
    d = {}
    res = maxUnique(S)
    # d = {}
 
    print(res)
 
# This code is contributed by mohit kumar 29.

                    

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  // Function to find the maximum count of
  // unique substrings by splitting a string
  // into maximum number of unique substrings
  public int maxUniqueSplit(String S)
  {
    return maxUnique(S, new HashSet<String>());
  }
 
  // Utility function to find maximum count of
  // unique substrings by splitting the string
  public int maxUnique(String S, HashSet<String> set)
  {
 
    // Stores maximum count of unique substring
    // by splitting the string into substrings
    int max = 0;
 
    // Iterate over the characters of the string
    for (int i = 1; i <= S.Length; i++) {
 
      // Stores prefix substring
      String tmp = S.Substring(0, i);
 
      // Check if the current substring
      // already exists
      if (!set.Contains(tmp)) {
 
        // Insert tmp into set
        set.Add(tmp);
 
        // Recursively call for remaining
        // characters of string
        max = Math.Max(max, maxUnique(
          S.Substring(i), set)
                       + 1);
 
        // Remove from the set
        set.Remove(tmp);
      }
    }
 
    // Return answer
    return max;
  }
}
 
// Driver Code
public class GFG {
 
  public static void Main(String[] args)
  {
    Solution st = new Solution();
    String S = "ababccc";
    int res = st.maxUniqueSplit(S);
 
    Console.WriteLine(res);
  }
}
 
// This code contributed by shikhasingrajput

                    

Javascript

<script>
 
// Javascript program for the above approach
 
// Utility function to find maximum count of
// unique substrings by splitting the string
function maxUnique(S, st)
{
 
  // Stores maximum count of unique substring
  // by splitting the string into substrings
  var mx = 0;
 
  // Iterate over the characters of the string
  for (var i = 1; i <= S.length; i++)
  {
 
    // Stores prefix substring
    var tmp = S.substring(0, i);
 
    // Check if the current substring
    // already exists
    if (!st.has(tmp))
    {
 
      // Insert tmp into set
      st.add(tmp);
 
      // Recursively call for remaining
      // characters of string
      mx = Math.max(mx, maxUnique(S.substring(i), st) + 1);
 
      // Remove from the set
      st.delete(tmp);
    }
  }
 
  // Return answer
  return mx;
}
 
 
// Function to find the maximum count of
// unique substrings by splitting a string
// into maximum number of unique substrings
function maxUniqueSplit(S)
{
  var st = new Set();
  return maxUnique(S, st);
}
 
// Driver Code
var S = "ababccc";
var res = maxUniqueSplit(S);
document.write( res);
 
 
</script>

                    

Output: 
5

 

Time Complexity: O(2^N  )

Auxiliary Space: O(N)



Similar Reads

Minimum length of a rod that can be split into N equal parts that can further be split into given number of equal parts
Given an array arr[] consisting of N positive integers, the task is to find the minimum possible length of a rod that can be cut into N equal parts such that every ith part can be cut into arr[i] equal parts. Examples: Input: arr[] = {1, 2}Output: 4Explanation:Consider the length of the rod as 4. Then it can be divided in 2 equal parts, each having
7 min read
Split a String into two Substring such that the sum of unique characters is maximum
Given a string str, the task is to partition the string into two substrings such that the sum of unique characters of both substrings is the maximum possible. Examples: Input: str = "abcabcd” Output: 7Explanation: Partition the given string into "abc" and "abcd", the sum of unique characters is 3 + 4 = 7 which is maximum possible. Input: str = "aaa
14 min read
Check if a string can be split into two substrings with equal number of vowels
Given a string S, the task is to check if the string can be split into two substrings such that the number of vowels in both of them are equal. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "geeks"Output: YesExplanation: Splitting the strings into substrings "ge" (count of vowels = 1) and "eks" (count of vowels
15+ min read
Split the binary string into substrings with equal number of 0s and 1s
Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: Input: str = "0100110101" Output: 4 The required substr
8 min read
Split Parenthesis Sequence into maximum valid Substrings
Given a String S which contains balanced Parentheses Brackets ( i.e '(' and ')' ), we need to split them in such a way that they form the maximum number of balanced groups. Examples: Input: S = "()()(()())()"Output: (), (), (()()), () Input: S = "()()"Output: (), () Input: S = "()()(())"Output: (), (), (()) Approach: To solve the problem follow the
7 min read
Split the string into substrings using delimiter
Given a string and a delimiter character. Split the string based on the delimiter and print the list of resulting sub strings. Examples: Input : str = "geeks;for;geeks" d_ch = ';' Output : geeks for geeks Input : str = "##ayush##jauhari####" d_ch = '#' Output : ayush jauhari Source: Microsoft IDC Bangalore Interview | Set 153 Algorithm: splitString
6 min read
Count ways to split string into K Substrings starting with even digit and min length M
Given a string S of length N consisting of digits from '0' to '9' .The task is to determine the total number of possible ways to partition the string into K substrings such that : Each substring has a minimum length of M (M&gt;=2).Substring must start with an even digit number and end with an odd digit number. Examples: Input: N = 9, M = 2, k = 3,
15+ min read
Remove minimum characters from string to split it into three substrings under given constraints
Given a string str of lowercase alphabets, the task is to remove minimum characters from the given string so that string can be break into 3 substrings str1, str2, and str3 such that each substring can be empty or can contains only characters 'a', 'b', and 'c' respectively.Example: Input: str = "aaaabaaxccac" Output: 3 Explanation: String after rem
8 min read
Check if a string can be split into even length palindromic substrings
Given a string str, the task is to check if it is possible to split the given string into even length palindromic substrings. Examples: Input: str = "abbacc" Output: Yes Explanation: Strings "abba" and "cc" are the even length palindromic substrings.Input: str = "abcde" Output: No Explanation: No even length palindromic substrings possible. Approac
6 min read
Check if a string can be split into substrings starting with N followed by N characters
Given a string str, the task is to check if it can be split into substrings such that each substring starts with a numeric value followed by a number of characters represented by that numeric integer. Examples: Input: str = "4g12y6hunter" Output: Yes Explanation: Substrings "4g12y" and "6hunter" satisfy the given condition Input: str = "31ba2a" Out
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg