Maximize partitions such that no two substrings have any common character

Given string str of size N, the task is to print the number of substrings formed after maximum possible partitions such that no two substrings have a common character.
Examples: 

Input : str = “ababcbacadefegdehijhklij” 
Output :
Explanation: 
Partitioning at the index 8 and at 15 produces three substrings “ababcbaca”, “defegde” and “hijhklij” such that none of them have a common character. So, the maximum partitions is 3.
Input: str = “aaa” 
Output:
Explanation: 
Since, the string consists of a single character, no partition can be performed. 
 

Approach:

  1. Find the last index of every unique character from the end of the string and store it in a map.
  2. Traverse the array from the index 0 up to the last index and make a separate variable to store the ending index of partition.
  3. Traverse for every variable in the string and check if the end of the partition, denoted by the index of str[i] stored in the map, is greater than the previous end. If so, update it.
  4. Check if the current variable exceeds the end of the partition, it means the first partition is found. Update the end of the partition to max(k, mp[str[i]]).
  5. Traverse the whole string and use a similar process to find the next partition and so on.

Below is the implementation of the above approach : 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the
// maximum number of
// partitions possible such
// that no two substrings
// have common character
 
#include 
using namespace std;
 
// Function to calculate and return
// the maximum number of partitions
int maximum_partition(string str)
{
    // r: Stores the maximum number
    // of partitions
    // k: Stores the ending index
    // of the partition
    int i = 0, j = 0, k = 0;
    int c = 0, r = 0;
 
    // Stores the last index
    // of every unique character
    // of the string
    unordered_map m;
 
    // Traverse the string and
    // store the last index
    // of every character
    for (i = str.length() - 1;
        i >= 0;
        i--) {
 
        if (m[str[i]] == 0) {
            m[str[i]] = i;
        }
    }
 
    i = 0;
 
    // Store the last index of the
    // first character from map
    k = m[str[i]];
 
    for (i = 0; i < str.length(); i++) {
 
        if (i <= k) {
            c = c + 1;
 
            // Update K to find
            // the end of partition
            k = max(k, m[str[i]]);
        }
 
        // Otherwise, the end of
        // partition is found
        else {
 
            // Increment r
            r = r + 1;
            c = 1;
 
            // Update k for the
            // next partition
            k = max(k, m[str[i]]);
        }
    }
 
    // Add the last partition
    if (c != 0) {
        r = r + 1;
    }
    return r;
}
 
// Driver Program
int main()
{
    string str
        = "ababcbacadefegdehijhklij";
    cout << maximum_partition(str);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the
// maximum number of
// partitions possible such
// that no two subStrings
// have common character
import java.util.*;
class GFG{
 
// Function to calculate and return
// the maximum number of partitions
static int maximum_partition(String str)
{
  // r: Stores the maximum number
  // of partitions
  // k: Stores the ending index
  // of the partition
  int i = 0, j = 0, k = 0;
  int c = 0, r = 0;
 
  // Stores the last index
  // of every unique character
  // of the String
  HashMap<Character,
          Integer> m = new HashMap<>();
 
  // Traverse the String and
  // store the last index
  // of every character
  for (i = str.length() - 1;
       i >= 0; i--)
  {
    if (!m.containsKey(str.charAt(i)))
    {
      m.put(str.charAt(i), i);
    }
  }
 
  i = 0;
 
  // Store the last index of the
  // first character from map
  k = m.get(str.charAt(i));
 
  for (i = 0; i < str.length(); i++)
  {
    if (i <= k)
    {
      c = c + 1;
 
      // Update K to find
      // the end of partition
      k = Math.max(k, m.get(str.charAt(i)));
    }
 
    // Otherwise, the end of
    // partition is found
    else
    {
      // Increment r
      r = r + 1;
      c = 1;
 
      // Update k for the
      // next partition
      k = Math.max(k, m.get(str.charAt(i)));
    }
  }
 
  // Add the last
  // partition
  if (c != 0)
  {
    r = r + 1;
  }
  return r;
}
 
// Driver code
public static void main(String[] args)
{
  String str = "ababcbacadefegdehijhklij";
  System.out.print(maximum_partition(str));
}
}
 
// This code is contributed by Princi Singh

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the
# maximum number of
# partitions possible such
# that no two substrings
# have common character
 
# Function to calculate and return
# the maximum number of partitions
def maximum_partition(strr):
     
    # r: Stores the maximum number
    # of partitions
    # k: Stores the ending index
    # of the partition
    i = 0
    j = 0
    k = 0
    c = 0
    r = 0
 
    # Stores the last index
    # of every unique character
    # of the strring
    m = {}
 
    # Traverse the and
    # store the last index
    # of every character
    for i in range(len(strr) - 1, -1, -1):
 
        if (strr[i] not in m):
            m[strr[i]] = i
 
    i = 0
 
    # Store the last index of the
    # first character from map
    k = m[strr[i]]
 
    for i in range(len(strr)):
 
        if (i <= k):
            c = c + 1
             
            # Update K to find
            # the end of partition
            k = max(k, m[strr[i]])
 
        # Otherwise, the end of
        # partition is found
        else:
 
            # Increment r
            r = r + 1
            c = 1
 
            # Update k for the
            # next partition
            k = max(k, m[strr[i]])
 
    # Add the last partition
    if (c != 0):
        r = r + 1
 
    return r
 
# Driver Code
if __name__ == '__main__':
    strr = "ababcbacadefegdehijhklij"
    print(maximum_partition(strr))
 
# This code is contributed by Mohit Kumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the
// maximum number of
// partitions possible such
// that no two subStrings
// have common character
using System;
using System.Collections.Generic;
class GFG{
 
// Function to calculate and return
// the maximum number of partitions
static int maximum_partition(String str)
{
  // r: Stores the maximum number
  // of partitions
  // k: Stores the ending index
  // of the partition
  int i = 0, j = 0, k = 0;
  int c = 0, r = 0;
 
  // Stores the last index
  // of every unique character
  // of the String
  Dictionary<char,
             int> m = new Dictionary<char,  
                                     int>();
 
  // Traverse the String and
  // store the last index
  // of every character
  for (i = str.Length - 1;
       i >= 0; i--)
  {
    if (!m.ContainsKey(str[i]))
    {
      m.Add(str[i], i);
    }
  }
 
  i = 0;
 
  // Store the last index of the
  // first character from map
  k = m[str[i]];
 
  for (i = 0; i < str.Length; i++)
  {
    if (i <= k)
    {
      c = c + 1;
 
      // Update K to find
      // the end of partition
      k = Math.Max(k, m[str[i]]);
    }
 
    // Otherwise, the end of
    // partition is found
    else
    {
      // Increment r
      r = r + 1;
      c = 1;
 
      // Update k for the
      // next partition
      k = Math.Max(k, m[str[i]]);
    }
  }
 
  // Add the last
  // partition
  if (c != 0)
  {
    r = r + 1;
  }
   
  return r;
}
 
// Driver code
public static void Main(String[] args)
{
  String str = "ababcbacadefegdehijhklij";
  Console.Write(maximum_partition(str));
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output: 

3








 

Time complexity: O(N) 
Auxiliary Space: O(1)

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.




My Personal Notes arrow_drop_up

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.