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

Last Updated : 13 Jul, 2026

Given a string s, split it into two halves from the middle. If the length of s is odd, ignore the middle character before splitting. Return true if the character frequencies in both halves are same, else return false.

Examples: 

Input: s = "abcdbca"
Output: true
Explanation: The string has length 7 which is odd, hence we ignore the middle character 'd'. The frequency of 'a', 'b' and 'c' is same in both the halves.

Input: s = "abbaab"
Output: false
Explanation: The first half "abb" and the second half "aab" do not have the same character frequencies.

Try It Yourself
redirect icon

[Naive Approach] Compare Frequency of Every Character Separately - O(26 * n) Time and O(1) Space

The idea is to split the string into two halves. If the string length is odd, ignore the middle character. Then, for every lowercase character from 'a' to 'z', count its occurrences in both halves separately. If the frequency of any character differs, return false; otherwise, return true.

Working of Approach:

  • Split the string into two halves. If the length is odd, ignore the middle character before splitting.
  • For every character from 'a' to 'z', count its occurrences separately in the left half and the right half.
  • If the frequency of any character differs in the two halves, return false immediately.
  • If the frequencies of all 26 characters match, return true.
C++
#include <iostream>
#include <string>
using namespace std;

// Function to check whether both halves have same character frequencies.
bool halvesMatch(string &s)
{

    int n = s.length();

    // Length of each half.
    int half = n / 2;

    // Starting index of second half.
    int rightStart = (n % 2 == 0) ? half : half + 1;

    // Check frequency of every lowercase character.
    for (char ch = 'a'; ch <= 'z'; ch++)
    {

        int leftCnt = 0;
        int rightCnt = 0;

        // Count in left half.
        for (int i = 0; i < half; i++)
        {
            if (s[i] == ch)
                leftCnt++;
        }

        // Count in right half.
        for (int i = rightStart; i < n; i++)
        {
            if (s[i] == ch)
                rightCnt++;
        }

        // Frequencies differ.
        if (leftCnt != rightCnt)
            return false;
    }

    return true;
}

int main()
{

    string s = "abcdbca";

    if (halvesMatch(s))
        cout << "true";
    else
        cout << "false";

    return 0;
}
Java
class GFG {

    // Function to check whether both halves have same
    // character frequencies.
    public boolean halvesMatch(String s)
    {

        int n = s.length();

        // Length of each half.
        int half = n / 2;

        // Starting index of second half.
        int rightStart = (n % 2 == 0) ? half : half + 1;

        // Check frequency of every lowercase character.
        for (char ch = 'a'; ch <= 'z'; ch++) {

            int leftCnt = 0;
            int rightCnt = 0;

            // Count in left half.
            for (int i = 0; i < half; i++) {
                if (s.charAt(i) == ch)
                    leftCnt++;
            }

            // Count in right half.
            for (int i = rightStart; i < n; i++) {
                if (s.charAt(i) == ch)
                    rightCnt++;
            }

            // Frequencies differ.
            if (leftCnt != rightCnt)
                return false;
        }

        return true;
    }

    public static void main(String[] args)
    {

        String s = "abcdbca";

        GFG obj = new GFG();

        if (obj.halvesMatch(s))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
def halvesMatch(s):

    n = len(s)

    # Length of each half.
    half = n // 2

    # Starting index of second half.
    rightStart = half if n % 2 == 0 else half + 1

    # Check frequency of every lowercase character.
    for ch in range(ord('a'), ord('z') + 1):

        leftCnt = 0
        rightCnt = 0

        # Count in left half.
        for i in range(half):
            if s[i] == chr(ch):
                leftCnt += 1

        # Count in right half.
        for i in range(rightStart, n):
            if s[i] == chr(ch):
                rightCnt += 1

        # Frequencies differ.
        if leftCnt != rightCnt:
            return False

    return True


if __name__ == "__main__":

    s = "abcdbca"

    if halvesMatch(s):
        print("true")
    else:
        print("false")
C#
using System;

class GFG {
    // Function to check whether both halves have same
    // character frequencies.
    public bool halvesMatch(string s)
    {
        int n = s.Length;

        // Length of each half.
        int half = n / 2;

        // Starting index of second half.
        int rightStart = (n % 2 == 0) ? half : half + 1;

        // Check frequency of every lowercase character.
        for (char ch = 'a'; ch <= 'z'; ch++) {
            int leftCnt = 0;
            int rightCnt = 0;

            // Count in left half.
            for (int i = 0; i < half; i++) {
                if (s[i] == ch)
                    leftCnt++;
            }

            // Count in right half.
            for (int i = rightStart; i < n; i++) {
                if (s[i] == ch)
                    rightCnt++;
            }

            // Frequencies differ.
            if (leftCnt != rightCnt)
                return false;
        }

        return true;
    }

    static void Main()
    {
        string s = "abcdbca";

        GFG obj = new GFG();

        if (obj.halvesMatch(s))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
function halvesMatch(s)
{

    const n = s.length;

    // Length of each half.
    const half = Math.floor(n / 2);

    // Starting index of second half.
    const rightStart = (n % 2 === 0) ? half : half + 1;

    // Check frequency of every lowercase character.
    for (let ch = "a".charCodeAt(0);
         ch <= "z".charCodeAt(0); ch++) {

        let leftCnt = 0;
        let rightCnt = 0;

        // Count in left half.
        for (let i = 0; i < half; i++) {
            if (s[i] === String.fromCharCode(ch)) {
                leftCnt++;
            }
        }

        // Count in right half.
        for (let i = rightStart; i < n; i++) {
            if (s[i] === String.fromCharCode(ch)) {
                rightCnt++;
            }
        }

        // Frequencies differ.
        if (leftCnt !== rightCnt) {
            return false;
        }
    }

    return true;
}

// Driver Code
const s = "abcdbca";

if (halvesMatch(s)) {
    console.log("true");
}
else {
    console.log("false");
}

Output
true

[Expected Approach] Using Frequency Array - O(n) Time and O(1) Space

The idea is to use a frequency array of size 26. Traverse the left half of the string and increment the frequency of each character. Then traverse the right half (ignoring the middle character when the length is odd) and decrement the corresponding frequency. If all frequencies become zero, both halves have identical character frequencies; otherwise, they do not.

Let us understand with an example:

  • Input: s = "abcdbca", n = 7. Since the length is odd, ignore the middle character 'd'.
  • Traverse the first half "abc" and increment the frequencies of 'a', 'b', and 'c'.
  • Traverse the second half "bca" and decrement the frequency of each character.
  • After both traversals, every entry in the frequency array becomes 0.
  • Since all frequencies are zero, both halves have the same character frequencies, so the output is true.
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;

bool halvesMatch(string &s)
{
    int n = s.size();
    int freq[26] = {0};

    // Count frequencies of characters in the first half
    for (int i = 0; i < n / 2; ++i)
        freq[s[i] - 'a']++;

    // Subtract frequencies of characters in the second half.
    // For odd length strings, skip the middle character.
    for (int i = n / 2 + n % 2; i < n; ++i)
        freq[s[i] - 'a']--;

    // If any frequency is non-zero, both halves do not match
    for (int i = 0; i < 26; ++i)
        if (freq[i] != 0)
            return false;

    return true;
}

int main()
{

    string s = "abcdbca";

    if (halvesMatch(s))
        cout << "true";
    else
        cout << "false";

    return 0;
}
Java
class GFG {

    // Function to check whether both halves have same
    // character frequencies.
    public boolean halvesMatch(String s)
    {

        int n = s.length();
        int[] freq = new int[26];

        // Count frequencies of characters in the first
        // half.
        for (int i = 0; i < n / 2; ++i)
            freq[s.charAt(i) - 'a']++;

        // Subtract frequencies of characters in the second
        // half. For odd length strings, skip the middle
        // character.
        for (int i = n / 2 + n % 2; i < n; ++i)
            freq[s.charAt(i) - 'a']--;

        // If any frequency is non-zero, both halves do not
        // match.
        for (int i = 0; i < 26; ++i)
            if (freq[i] != 0)
                return false;

        return true;
    }

    public static void main(String[] args)
    {

        String s = "abcdbca";

        GFG obj = new GFG();

        if (obj.halvesMatch(s))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
def halvesMatch(s):
    n = len(s)
    freq = [0] * 26

    # Count frequencies of characters in the first half
    for i in range(n // 2):
        freq[ord(s[i]) - ord('a')] += 1

    # Subtract frequencies of characters in the second half.
    # For odd length strings, skip the middle character.
    for i in range(n // 2 + n % 2, n):
        freq[ord(s[i]) - ord('a')] -= 1

    # If any frequency is non-zero, both halves do not match
    for i in range(26):
        if freq[i] != 0:
            return False

    return True


if __name__ == "__main__":

    s = "abcdbca"

    if halvesMatch(s):
        print("true")
    else:
        print("false")
C#
using System;

class GFG {
    // Function to check whether both halves have same
    // character frequencies.
    public bool halvesMatch(string s)
    {
        int n = s.Length;
        int[] freq = new int[26];

        // Count frequencies of characters in the first
        // half.
        for (int i = 0; i < n / 2; ++i)
            freq[s[i] - 'a']++;

        // Subtract frequencies of characters in the second
        // half. For odd length strings, skip the middle
        // character.
        for (int i = n / 2 + n % 2; i < n; ++i)
            freq[s[i] - 'a']--;

        // If any frequency is non-zero, both halves do not
        // match.
        for (int i = 0; i < 26; ++i)
            if (freq[i] != 0)
                return false;

        return true;
    }

    static void Main()
    {
        string s = "abcdbca";

        GFG obj = new GFG();

        if (obj.halvesMatch(s))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
function halvesMatch(s)
{
    let n = s.length;
    let freq = new Array(26).fill(0);

    // Count frequencies of characters in the first half
    for (let i = 0; i < Math.floor(n / 2); ++i)
        freq[s.charCodeAt(i) - "a".charCodeAt(0)]++;

    // Subtract frequencies of characters in the second
    // half. For odd length strings, skip the middle
    // character.
    for (let i = Math.floor(n / 2) + n % 2; i < n; ++i)
        freq[s.charCodeAt(i) - "a".charCodeAt(0)]--;

    // If any frequency is non-zero, both halves do not
    // match
    for (let i = 0; i < 26; ++i)
        if (freq[i] != 0)
            return false;

    return true;
}

// Driver Code
let s = "abcdbca";

if (halvesMatch(s))
    console.log("true");
else
    console.log("false");

Output
true
Comment