Open In App

Split string to get maximum common characters

Last Updated : 17 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S of length, N. Split them into two strings such that the number of common characters between the two strings is maximized and return the maximum number of common characters.

Examples:

Input: N = 6, S = abccba
Output: 3
Explanation: Splitting two strings as “abc” and “cba” has at most 3 distinct characters. Splitting in “abcc” and “ba” gives only two which is not the maximum.

Input: N = 5, S = abbdb
Output: 1
Explanation: Splitting it in “ab” and “bdb” has only 1 character common which is “b” and it is the maximum.

Approach: To solve the problem follow the below idea:

Use two frequency arrays to store the frequency of characters in the given string. freq1 will store frequency from starting and freq2 will store frequency from behind. If we find any character with a frequency greater than or equal to 1 in both freq1 and freq2 then this will be a common character. 

Steps involved in the implementation of code:

  • Declare 2 frequency array freq1 and freq2 of size 26.
  • First increment frequency of every character of the string in freq1.
  • Iterate over the string from behind and for every character decrement its frequency from freq1 and increment its frequency in freq2.
  • Iterate over the frequency array and if we find any character with a frequency greater than or equal to 1 in both freq1 and freq2 then this will be a common character.

Below is the implementation of the above approach:

C++




// C++ program to find maximum common
// character after splitting string
#include <bits/stdc++.h>
using namespace std;
 
// Main function to find maximum common
// character after splitting string
int maximumCommonCharacterAfterSplit(int n, string s)
{
 
    // Frequency array to store frequency
    // of characters freq1 to store
    // frequency of characters from
    // starting freq2 to store frequency
    // of characters from ending
    vector<int> freq1(26, 0);
    vector<int> freq2(26, 0);
 
    // Increment frequency of every
    // characters initially in freq1
    for (int i = 0; i < n; i++)
        freq1[s[i] - 'a']++;
 
    // To store maximum common characters
    int ans = 0;
 
    // Iterate from ending of string
    for (int i = n - 1; i >= 1; i--) {
        freq1[s[i] - 'a']--;
 
        freq2[s[i] - 'a']++;
 
        int common = 0;
        for (int j = 0; j < 26; j++) {
            if (freq1[j] >= 1 && freq2[j] >= 1)
                common++;
        }
 
        ans = max(ans, common);
    }
 
    return ans;
}
 
// Drivers code
int main()
{
 
    int N = 6;
    string S = "abccba";
 
    // Function Call
    cout << maximumCommonCharacterAfterSplit(N, S);
 
    return 0;
}


Java




// Java program to find maximum common
// character after splitting string
import java.util.*;
 
public class GFG {
 
  // Main function to find maximum common
  // character after splitting string
  static int maximumCommonCharacterAfterSplit(int n,
                                              String s)
  {
 
    // Frequency array to store frequency
    // of characters freq1 to store
    // frequency of characters from
    // starting freq2 to store frequency
    // of characters from ending
    int[] freq1 = new int[26];
    int[] freq2 = new int[26];
 
    // Increment frequency of every
    // characters initially in freq1
    for (int i = 0; i < n; i++) {
      freq1[s.charAt(i) - 'a']++;
    }
 
    // To store maximum common characters
    int ans = 0;
 
    // Iterate from ending of string
    for (int i = n - 1; i >= 1; i--) {
      freq1[s.charAt(i) - 'a']--;
 
      freq2[s.charAt(i) - 'a']++;
 
      int common = 0;
      for (int j = 0; j < 26; j++) {
        if (freq1[j] >= 1 && freq2[j] >= 1)
          common++;
      }
 
      ans = Math.max(ans, common);
    }
 
    return ans;
  }
 
  // Drivers code
  public static void main(String[] args)
  {
 
    int N = 6;
    String S = "abccba";
 
    // Function Call
    System.out.print(
      maximumCommonCharacterAfterSplit(N, S));
  }
}
 
// This code is contributed by Susobhan Akhuli


Python3




# Python3 program to find maximum common
# character after splitting string
 
# Main function to find maximum common
# character after splitting string
def maximumCommonCharacterAfterSplit(n, s):
  # Frequency array to store frequency
  # of characters freq1 to store
  # frequency of characters from
  # starting freq2 to store frequency
  # of characters from ending
  freq1 = [0] * 26
  freq2 = [0] * 26
 
  # Increment frequency of every
  # characters initially in freq1
  for i in range(n):
      freq1[ord(s[i]) - ord('a')] += 1
 
  # To store maximum common characters
  ans = 0
 
  # Iterate from ending of string
  for i in range(n - 1, 0, -1):
      freq1[ord(s[i]) - ord('a')] -= 1
      freq2[ord(s[i]) - ord('a')] += 1
      common = 0
 
      for j in range(26):
          if freq1[j] >= 1 and freq2[j] >= 1:
              common += 1
 
      ans = max(ans, common)
 
  return ans
 
 
# Drivers code
N = 6
S = "abccba"
 
# Function Call
print(maximumCommonCharacterAfterSplit(N, S))


Javascript




// JavaScript program to find maximum common
// character after splitting string
 
// Main function to find maximum common
// character after splitting string
function maximumCommonCharacterAfterSplit(n, s) {
  // Frequency array to store frequency
  // of characters freq1 to store
  // frequency of characters from
  // starting freq2 to store frequency
  // of characters from ending
  const freq1 = new Array(26).fill(0);
  const freq2 = new Array(26).fill(0);
 
  // Increment frequency of every
  // characters initially in freq1
  for (let i = 0; i < n; i++) {
    freq1[s.charCodeAt(i) - 97]++;
  }
 
  // To store maximum common characters
  let ans = 0;
 
  // Iterate from ending of string
  for (let i = n - 1; i >= 1; i--) {
    freq1[s.charCodeAt(i) - 97]--;
    freq2[s.charCodeAt(i) - 97]++;
 
    let common = 0;
    for (let j = 0; j < 26; j++) {
      if (freq1[j] >= 1 && freq2[j] >= 1) {
        common++;
      }
    }
 
    ans = Math.max(ans, common);
  }
 
  return ans;
}
 
// Drivers code
const N = 6;
const S = "abccba";
 
// Function Call
console.log(maximumCommonCharacterAfterSplit(N, S));


C#




// C# program to find maximum common
// character after splitting string
 
using System;
using System.Collections.Generic;
 
class GFG {
    // Main function to find maximum common
    // character after splitting string
    static int maximumCommonCharacterAfterSplit(int n,
                                                string s)
    {
 
        // Frequency array to store frequency
        // of characters freq1 to store
        // frequency of characters from
        // starting freq2 to store frequency
        // of characters from ending
        List<int> freq1 = new List<int>();
        List<int> freq2 = new List<int>();
        for (int i = 0; i < 26; i++) {
            freq1.Add(0);
            freq2.Add(0);
        }
 
        // Increment frequency of every
        // characters initially in freq1
        for (int i = 0; i < n; i++)
            freq1[s[i] - 'a']++;
 
        // To store maximum common characters
        int ans = 0;
 
        // Iterate from ending of string
        for (int i = n - 1; i >= 1; i--) {
            freq1[s[i] - 'a']--;
            freq2[s[i] - 'a']++;
 
            int common = 0;
            for (int j = 0; j < 26; j++) {
                if (freq1[j] >= 1 && freq2[j] >= 1)
                    common++;
            }
 
            ans = Math.Max(ans, common);
        }
 
        return ans;
    }
 
    // Drivers code
    public static void Main()
    {
 
        int N = 6;
        string S = "abccba";
 
        // Function Call
        Console.WriteLine(
            maximumCommonCharacterAfterSplit(N, S));
    }
}


Output

3

Time complexity: O(26 * N)
Auxiliary Space: O(26), size of frequency array.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads