Maximized partitions of a string such that each character of the string appears in one substring

Given a string S, split the given string into as many substrings as possible such that each character from the given string appears in a single substring and print all these possible parts. The task is to print those substrings.

Examples:

Input: S = “ababcbacadefegdehijhklij” 
Output: 
ababcbaca defegde hijhklij 
Explanation: 
a, b, c are only present in the first string. 
d, e, f, g are only present in the second string. 
h, i, j, k, l are only present in the third string.

Input: S = “acbbcc” 
Output: 
a cbbcc 
Explanation: 
a are only present in the first string. 
b, c are only present in the second string.

Approach: Follow the steps below to solve the problem:



  1. Store the last index of occurrence of all characters in the string.
  2. Since the string contains only lowercase letters, simply use an array of fixed size 26 to store the last indices of each character.
  3. Initialize an empty string ans = “” and iterate over the given string and follow the steps below: 
    • Add the current character to the string ans if the last position of the character is more than the current index and increase the length of the partition.
    • If the last position of the current character is equal to the current index, then print the current string stored in ans and initialize ans to “” for storing the next partition of the string.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print all the substrings
void print_substring(string s)
{
    int n = s.size();
 
    // Stores the substrings
    string str = "";
 
    // Stores last index of
    // charcters of string s
    vector<int> ans;
 
    if (n == 0) {
        cout << "-1";
        return;
    }
 
    // Find the last position of
    // each character in the string
    vector<int> last_pos(26, -1);
 
    for (int i = n - 1; i >= 0; --i) {
 
        // Update the last index
        if (last_pos[s[i] - 'a'] == -1) {
            last_pos[s[i] - 'a'] = i;
        }
    }
 
    int minp = -1;
 
    // Iterate the given string
    for (int i = 0; i < n; ++i) {
 
        // Get the last index of s[i]
        int lp = last_pos[s[i] - 'a'];
 
        // Extend the current partition
        // characters last pos
        minp = max(minp, lp);
 
        // If the current pos of
        // character equals the min pos
        // then the end of partition
        if (i == minp) {
 
            // Add the respective character first
            str += s[i];
 
            // Store the partition's
            // len and reset variables
            cout << str << ' ';
 
            // Update the minp and str
            minp = -1;
            str = "";
        }
        else {
            str += s[i];
        }
    }
}
 
// Driver Code
int main()
{
    // Input string
    string S = "ababcbacadefegdehijhklij";
 
    // Function call
    print_substring(S);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to print all the substrings
    public static void print_substring(String s)
    {
        int n = s.length();
 
        // Stores the substrings
        String str = "";
 
        // Stores last index of
        // charcters of string s
        Vector<Integer> ans = new Vector<Integer>();
 
        if (n == 0) {
            System.out.print("-1");
            return;
        }
 
        // Find the last position of
        // each character in the string
        int[] last_pos = new int[26];
        Arrays.fill(last_pos, -1);
 
        for (int i = n - 1; i >= 0; --i) {
 
            // Update the last index
            if (last_pos[s.charAt(i) - 'a'] == -1) {
                last_pos[s.charAt(i) - 'a'] = i;
            }
        }
 
        int minp = -1;
 
        // Iterate the given string
        for (int i = 0; i < n; ++i) {
 
            // Get the last index of s[i]
            int lp = last_pos[s.charAt(i) - 'a'];
 
            // Extend the current partition
            // characters last pos
            minp = Math.max(minp, lp);
 
            // If the current pos of
            // character equals the min pos
            // then the end of partition
            if (i == minp) {
                 
                // Add the respective character first
                str += s.charAt(i);
 
                // Store the partition's
                // len and reset variables
                System.out.print(str + ' ');
 
                // Update the minp and str
                minp = -1;
                str = "";
            }
            else {
                str += s.charAt(i);
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Input string
        String S = "ababcbacadefegdehijhklij";
 
        // Function call
        print_substring(S);
    }
}
 
// This code is contributed by divyeshrabadiya07
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to print all the substrings
def print_substring(s):
 
    n = len(s)
 
    # Stores the substrings
    str = ""
 
    # Stores last index of
    # charcters of string s
    ans = []
 
    if (n == 0):
        print("-1")
        return
 
    # Find the last position of
    # each character in the string
    last_pos = [-1] * 26
 
    for i in range(n - 1, -1, -1):
 
        # Update the last index
        if (last_pos[ord(s[i]) - ord('a')] == -1):
            last_pos[ord(s[i]) - ord('a')] = i
 
    minp = -1
 
    # Iterate the given string
    for i in range(n):
 
        # Get the last index of s[i]
        lp = last_pos[ord(s[i]) - ord('a')]
 
        # Extend the current partition
        # characters last pos
        minp = max(minp, lp)
 
        # If the current pos of
        # character equals the min pos
        # then the end of partition
        if (i == minp):
               
            #Add the respective character to the string
            str += s[i]
             
            # Store the partition's
            # len and reset variables
            print(str, end = " ")
 
            # Update the minp and str
            minp = -1
            str = ""
 
        else:
            str += s[i]
 
# Driver Code
 
# Input string
S = "ababcbacadefegdehijhklij"
 
# Function call
print_substring(S)
 
# This code is contributed by Shivam Singh
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to print all the substrings
public static void print_substring(String s)
{
    int n = s.Length;
 
    // Stores the substrings
    String str = "";
 
    // Stores last index of
    // charcters of string s
    //List<int> ans = new List<int>();
 
    if (n == 0)
    {
        Console.Write("-1");
        return;
    }
 
    // Find the last position of
    // each character in the string
    int[] last_pos = new int[26];
    for(int i = 0; i < 26; i++)
        last_pos[i] = -1;
 
    for(int i = n - 1; i >= 0; --i)
    {
         
        // Update the last index
        if (last_pos[s[i] - 'a'] == -1)
        {
            last_pos[s[i] - 'a'] = i;
        }
    }
 
    int minp = -1;
 
    // Iterate the given string
    for(int i = 0; i < n; ++i)
    {
         
        // Get the last index of s[i]
        int lp = last_pos[s[i] - 'a'];
 
        // Extend the current partition
        // characters last pos
        minp = Math.Max(minp, lp);
 
        // If the current pos of
        // character equals the min pos
        // then the end of partition
        if (i == minp)
        {
            //Add respective character to the string 
            str += s[i];
           
            // Store the partition's
            // len and reset variables
            Console.Write(str + ' ');
 
            // Update the minp and str
            minp = -1;
            str = "";
        }
        else
        {
            str += s[i];
        }
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Input string
    String S = "ababcbacadefegdehijhklij";
 
    // Function call
    print_substring(S);
}
}
 
// This code is contributed by Amit Katiyar
chevron_right

Output
ababcbaca defegde hijhklij 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :