Open In App

Check if both halves of the string have same set of characters

Last Updated : 14 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest.

Examples: 

Input: abbaab
Output: NO
The two halves contain the same characters
but their frequencies do not match so they
are NOT CORRECT

Input : abccab
Output : YES

Algorithm: 

  1. Declare two counter arrays for keeping count of characters in two half of the string, each of size 26.
  2. Now run a loop and take two variables i and j, where i starts from 0 and j starts from (length of string – 1).
  3. For each character in the string, go to the corresponding index in the counter arrays and increment the value by 1 and increment i and decrement j. Do this until i is less than j.
  4. After finishing STEP 3, again run a loop and compare values of counter arrays. If value of first array if not equal to value of second array, then return false.
  5. If all counts matched, return true.

Below is the implementation of above idea: 

C++




// C++ program to check if it is
// possible to split string or not
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
 
// function to check if we can split
// string or not
bool checkCorrectOrNot(string s)
{
    // Counter array initialized with 0
    int count1[MAX_CHAR] = {0};
    int count2[MAX_CHAR] = {0};
 
    // Length of the string
    int n = s.length();
    if (n == 1)
        return true;
 
    // traverse till the middle element
    // is reached
    for (int i=0,j=n-1; i<j; i++,j--)
    {
        // First half
        count1[s[i]-'a']++;
 
        // Second half
        count2[s[j]-'a']++;
    }
 
    // Checking if values are different
    // set flag to 1
    for (int i = 0; i<MAX_CHAR; i++)
        if (count1[i] != count2[i])
            return false;
 
    return true;
}
 
// Driver program to test above function
int main()
{
    // String to be checked
    string s = "abab";
 
    if (checkCorrectOrNot(s))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}


Java




// Java program to check if it two
// half of string contain same Character
// set or not
public class GFG {
 
    static final int MAX_CHAR = 26;
      
    // function to check both halves
    // for equality
    static boolean checkCorrectOrNot(String s)
    {
        // Counter array initialized with 0
        int[] count1 = new int[MAX_CHAR];
        int[] count2 = new int[MAX_CHAR];
      
        // Length of the string
        int n = s.length();
        if (n == 1)
            return true;
      
        // traverse till the middle element
        // is reached
        for (int i = 0, j = n - 1; i < j; i++, j--)
        {
            // First half
            count1[s.charAt(i) - 'a']++;
      
            // Second half
            count2[s.charAt(j) - 'a']++;
        }
      
        // Checking if values are different
        // set flag to 1
        for (int i = 0; i < MAX_CHAR; i++)
            if (count1[i] != count2[i])
                return false;
      
        return true;
    }
      
    // Driver program to test above function
    public static void main(String args[])
    {
        // String to be checked
        String s = "abab";
      
        if (checkCorrectOrNot(s))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program to check if it is
# possible to split string or not
MAX_CHAR = 26
 
# Function to check if we
# can split string or not
def checkCorrectOrNot(s):
     
    global MAX_CHAR
     
    # Counter array initialized with 0
    count1 = [0] * MAX_CHAR
    count2 = [0] * MAX_CHAR
 
    # Length of the string
    n = len(s)
     
    if n == 1:
        return true
 
    # Traverse till the middle
    # element is reached
    i = 0; j = n - 1
     
    while (i < j):
         
        # First half
        count1[ord(s[i]) - ord('a')] += 1
 
        # Second half
        count2[ord(s[j]) - ord('a')] += 1
 
        i += 1; j -= 1
 
    # Checking if values are
    # different set flag to 1
    for i in range(MAX_CHAR):
         
        if count1[i] != count2[i]:
            return False
             
    return True
 
 
# Driver Code
 
# String to be checked
s = "ababc"
 
print("Yes" if checkCorrectOrNot(s) else "No")
 
 
# This code is contributed by Ansu Kumari.


C#




// C# program to check if it two half of
// string contain same Character set or not
using System;
 
class GFG {
 
    static int MAX_CHAR = 26;
     
    // function to check both halves for
    // equality
    static bool checkCorrectOrNot(string s)
    {
         
        // Counter array initialized with 0
        int []count1 = new int[MAX_CHAR];
        int []count2 = new int[MAX_CHAR];
     
        // Length of the string
        int n = s.Length;
        if (n == 1)
            return true;
     
        // traverse till the middle element
        // is reached
        for (int i = 0, j = n - 1; i < j;
                                   i++, j--)
        {
             
            // First half
            count1[s[i] - 'a']++;
     
            // Second half
            count2[s[j] - 'a']++;
        }
     
        // Checking if values are different
        // set flag to 1
        for (int i = 0; i < MAX_CHAR; i++)
            if (count1[i] != count2[i])
                return false;
     
        return true;
    }
     
    // Driver program to test above function
    public static void Main()
    {
        // String to be checked
        string s = "abab";
     
        if (checkCorrectOrNot(s))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
 
// This code is contributed by nitin mittal


PHP




<?php
// PHP program to check if it is
// possible to split string or not
$MAX_CHAR = 26;
 
// function to check if we
// can split string or not
function checkCorrectOrNot($s)
{
    global $MAX_CHAR;
     
    // Counter array initialized with 0
    $count1 = array_fill(0, $MAX_CHAR, NULL);
    $count2 = array_fill(0, $MAX_CHAR, NULL);
 
    // Length of the string
    $n = strlen($s);
    if ($n == 1)
        return true;
 
    // traverse till the middle
    // element is reached
    for ($i = 0, $j = $n - 1;
         $i < $j; $i++, $j--)
    {
        // First half
        $count1[$s[$i] - 'a']++;
 
        // Second half
        $count2[$s[$j] - 'a']++;
    }
 
    // Checking if values are
    // different set flag to 1
    for ($i = 0; $i < $MAX_CHAR; $i++)
        if ($count1[$i] != $count2[$i])
            return false;
 
    return true;
}
 
// Driver Code
 
// String to be checked
$s = "abab";
if (checkCorrectOrNot($s))
    echo "Yes\n";
else
    echo "No\n";
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
// Javascript program to check if it two
// half of string contain same Character
// set or not
     
    let MAX_CHAR = 26;
     
    // function to check both halves
    // for equality
    function checkCorrectOrNot(s)
    {
        // Counter array initialized with 0
        let count1 = new Array(MAX_CHAR);
        let count2 = new Array(MAX_CHAR);
        for(let i=0;i<MAX_CHAR;i++)
        {
            count1[i]=0;
            count2[i]=0;
        }
        
        // Length of the string
        let n = s.length;
        if (n == 1)
            return true;
        
        // traverse till the middle element
        // is reached
        for (let i = 0, j = n - 1; i < j; i++, j--)
        {
            // First half
            count1[s[i] - 'a']++;
        
            // Second half
            count2[s[j] - 'a']++;
        }
        
        // Checking if values are different
        // set flag to 1
        for (let i = 0; i < MAX_CHAR; i++)
            if (count1[i] != count2[i])
                return false;
        
        return true;
    }   
     
    // Driver program to test above function
     
    // String to be checked
    let  s = "abab";
    if (checkCorrectOrNot(s))
        document.write("Yes");
    else
        document.write("No");
     
    //This code is contributed by avanitrachhadiya2155
     
</script>


Output

Yes

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

Space optimized solution: 

Below is the space optimized solution of the above approach. 

  1. We can solve this problem by using only 1 counter array.
  2. Take a string and increment counts for first half and then decrement counts for second half.
  3. If final counter array is 0, then return true, Else False.

Below is the implementation of above idea:  

C++




// C++ program to check if it is
// possible to split string or not
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
 
// function to check if we can split
// string or not
bool checkCorrectOrNot(string s)
{
    // Counter array initialized with 0
    int count[MAX_CHAR] = {0};
 
    // Length of the string
    int n = s.length();
    if (n == 1)
        return true;
 
    // traverse till the middle element
    // is reached
    for (int i=0,j=n-1; i<j; i++,j--)
    {
        // First half
        count[s[i]-'a']++;
 
        // Second half
        count[s[j]-'a']--;
    }
 
    // Checking if values are different
    // set flag to 1
    for (int i = 0; i<MAX_CHAR; i++)
        if (count[i] != 0)
            return false;
 
    return true;
}
 
// Driver program to test above function
int main()
{
    // String to be checked
    string s = "abab";
 
    if (checkCorrectOrNot(s))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}


Java




// Java program to check if it two
// half of string contain same Character
// set or not
public class GFG {
 
    static final int MAX_CHAR = 26;
      
    // function to check both halves
    // for equality
    static boolean checkCorrectOrNot(String s)
    {
        // Counter array initialized with 0
        int[] count = new int[MAX_CHAR];
      
        // Length of the string
        int n = s.length();
        if (n == 1)
            return true;
      
        // traverse till the middle element
        // is reached
        for (int i = 0,j = n - 1; i < j; i++, j--)
        {
            // First half
            count[s.charAt(i) - 'a']++;
      
            // Second half
            count[s.charAt(j) - 'a']--;
        }
      
        // Checking if values are different
        // set flag to 1
        for (int i = 0; i < MAX_CHAR; i++)
            if (count[i] != 0)
                return false;
      
        return true;
    }
      
    // Driver program to test above function
    public static void main(String args[])
    {
        // String to be checked
        String s = "abab";
      
        if (checkCorrectOrNot(s))
            System.out.println("Yes");
        else
           System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program to check if it is
# possible to split string or not
MAX_CHAR = 26
 
# Function to check if we 
# can split string or not
def checkCorrectOrNot(s):
     
    global MAX_CHAR
     
    # Counter array initialized with 0
    count = [0] * MAX_CHAR
 
    # Length of the string
    n = len(s)
     
    if n == 1:
        return true
 
    # Traverse till the middle
    # element is reached
    i = 0; j = n-1
     
    while i < j:
         
        # First half
        count[ord(s[i]) - ord('a')] += 1
 
        # Second half
        count[ord(s[j])-ord('a')] -= 1
 
        i += 1; j -= 1
 
    # Checking if values are
    # different, set flag to 1
    for i in range(MAX_CHAR):
         
        if count[i] != 0:
            return False
 
    return True
 
 
# Driver Code
 
# String to be checked
s = "abab"
 
print("Yes" if checkCorrectOrNot(s) else "No")
 
 
# This code is contributed by Ansu Kumari.


C#




// C# program to check if it two
// half of string contain same Character
// set or not
using System;
 
public class GFG {
 
    static int MAX_CHAR = 26;
     
    // function to check both halves
    // for equality
    static bool checkCorrectOrNot(String s)
    {
         
        // Counter array initialized with 0
        int[] count = new int[MAX_CHAR];
     
        // Length of the string
        int n = s.Length;
        if (n == 1)
            return true;
     
        // traverse till the middle element
        // is reached
        for (int i = 0, j = n - 1; i < j; i++, j--)
        {
            // First half
            count[s[i] - 'a']++;
     
            // Second half
            count[s[j] - 'a']--;
        }
     
        // Checking if values are different
        // set flag to 1
        for (int i = 0; i < MAX_CHAR; i++)
            if (count[i] != 0)
                return false;
     
        return true;
    }
     
    // Driver program to test above function
    public static void Main(String []args)
    {
         
        // String to be checked
        String s = "abab";
     
        if (checkCorrectOrNot(s))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
 
// This code is contributed by parashar.


PHP




<?PHP
// PHP program to check if it is
// possible to split string or not
$MAX_CHAR = 26;
 
// function to check if we
// can split string or not
function checkCorrectOrNot($s)
{
    global $MAX_CHAR;
     
    // Counter array initialized with 0
    $count = array_fill(0, $MAX_CHAR, NULL);
 
    // Length of the string
    $n = strlen($s);
    if ($n == 1)
        return true;
 
    // traverse till the middle
    // element is reached
    for ($i = 0, $j = $n - 1;
         $i < $j; $i++, $j--)
    {
        // First half
        $count[$s[$i] - 'a']++;
 
        // Second half
        $count[$s[$j] - 'a']--;
    }
 
    // Checking if values are
    // different set flag to 1
    for ($i = 0; $i < $MAX_CHAR; $i++)
        if ($count[$i] != 0)
            return false;
 
    return true;
}
 
// Driver Code
 
// String to be checked
$s = "abab";
if (checkCorrectOrNot($s))
    echo "Yes\n";
else
    echo "No\n";
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
 
// Javascript program to check if it two
// half of string contain same Character
// set or not
     
let MAX_CHAR = 26;
 
// Function to check both halves
// for equality
function checkCorrectOrNot(s)
{
     
    // Counter array initialized with 0
    let count = new Array(MAX_CHAR);
    for(let i = 0; i < count.length; i++)
    {
        count[i] = 0;
    }
   
    // Length of the string
    let n = s.length;
    if (n == 1)
        return true;
   
    // Traverse till the middle element
    // is reached
    for(let i = 0, j = n - 1; i < j; i++, j--)
    {
         
        // First half
        count[s[i] - 'a']++;
   
        // Second half
        count[s[j] - 'a']--;
    }
   
    // Checking if values are different
    // set flag to 1
    for(let i = 0; i < MAX_CHAR; i++)
        if (count[i] != 0)
            return false;
   
    return true;
}
 
// Driver Code
let s = "abab";
 
if (checkCorrectOrNot(s))
    document.write("Yes");
else
    document.write("No");
 
// This code is contributed by rag2127
     
</script>


Output

Yes

 Time Complexity : O(n)
Auxiliary Space: O(1)

 



Similar Reads

Check if both halves of the string have same set of characters in Python
Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest. Examples: Input : abbaab Output : NO The two ha
3 min read
Check if both halves of the string have at least one different character
Earlier we have discussed on how to check if both halves of the string have same set of characters. Now, we further extend our problem on checking if both halves of the string have at least one different character. Examples: Input : baaaabOutput: No, both halves do not differ at allThe two halves contain the same characters and their frequencies ma
15 min read
Maximum length of subarray consisting of same type of element on both halves of sub-array
Given an array arr[] of N integers, the task is to find the maximum length of sub-array consisting of the same type of element on both halves of the sub-array. Also, the elements on both halves differ from each other. Examples: Input: arr[] = {2, 3, 4, 4, 5, 5, 6, 7, 8, 10}Output: 4Explanation:{2, 3}, {3, 4}, {4, 4, 5, 5}, {5, 6}, etc, are the vali
8 min read
Check if both halves of a string are Palindrome or not
Given a string str, the task is to check whether the given string can be split into two halves, each of which is palindromic. If it is possible, print Yes. Otherwise, print No. Examples: Input: str = "naan" Output: No Explanation: Since both halves "na" and "an" are not palindrome. Input: momdad Output: Yes Explanation: Since both half "mom" and "d
5 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
Count ways to partition a string such that both parts have equal distinct characters
Content has been removed on Author's request.
1 min read
Partition the string in two parts such that both parts have at least k different characters
Given a string of lowercase English alphabets and an integer 0 &lt; K &lt;= 26. The task is to divide the string into two parts (also print them) such that both parts have at least k different characters. If there are more than one answers possible, print one having the smallest left part. If there is no such answers, print "Not Possible".Examples:
14 min read
All possible binary numbers of length n with equal sum in both halves
Given a number n, we need to print all n-digit binary numbers with equal sum in left and right halves. If n is odd, then mid element can be either 0 or 1. Examples: Input : n = 4 Output : 0000 0101 0110 1001 1010 1111 Input : n = 5 Output : 00000 00100 01001 01101 01010 01110 10001 10101 10010 10110 11011 11111 The idea is to recursively build left
10 min read
Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Check if a String can be converted to another by inserting character same as both neighbours
Given 2 strings A and B . The task is to check if A can be converted into B by performing the following operation any number of times : Choose an index from 0 to N - 2 (suppose N is the length of A). If the character at ith index is equal to the character at (i + 1 )th index, then insert the same character between the ith and (i + 1)th index. Examp
9 min read
Article Tags :
Practice Tags :