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

1.6

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 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 spilt
// string or not
bool checkCorrectOrNot(string s)
{
    // Counter array inisialized 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 diffrent
    // 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 inisialized 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


Output:

YES

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 spilt
// string or not
bool checkCorrectOrNot(string s)
{
    // Counter array inisialized 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 diffrent
    // 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 inisialized 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


Output:

YES

This article is contributed by Sahil Rajput. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.6 Average Difficulty : 1.6/5.0
Based on 12 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.