Check if both halves of the string have same set of characters in C#

To check if both halves of a string have the same set of characters in C#, we need to split the string into two equal halves and compare the character frequencies in each half. This problem is useful for validating palindromic properties and string pattern matching.

Algorithm

The approach uses character frequency counting −

  • Create two frequency arrays to count characters in each half

  • Iterate from both ends of the string toward the center

  • Count character occurrences in the left half and right half

  • Compare the frequency arrays to determine if both halves contain the same characters

String Halves Comparison t i m e t i m e Split Point Left Half "time" Right Half "time" ? Same character frequencies e:1, i:1, m:1, t:1 in both halves

Syntax

Following is the syntax for character frequency counting −

int[] leftHalf = new int[26];   // frequency array for left half
int[] rightHalf = new int[26];  // frequency array for right half

// Count characters from both ends
for (int i = 0, j = length - 1; i < j; i++, j--) {
   leftHalf[str[i] - 'a']++;
   rightHalf[str[j] - 'a']++;
}

Using Character Frequency Arrays

This method counts the frequency of each character in both halves and compares the arrays −

using System;

class Program {
   static int MAX_CHAR = 26;
   
   static bool CheckSameCharacters(string str) {
      int[] leftHalf = new int[MAX_CHAR];
      int[] rightHalf = new int[MAX_CHAR];
      int length = str.Length;
      
      if (length == 1)
         return true;
      
      // Count character frequencies from both ends
      for (int i = 0, j = length - 1; i < j; i++, j--) {
         leftHalf[str[i] - 'a']++;
         rightHalf[str[j] - 'a']++;
      }
      
      // Compare frequency arrays
      for (int i = 0; i < MAX_CHAR; i++) {
         if (leftHalf[i] != rightHalf[i])
            return false;
      }
      
      return true;
   }
   
   public static void Main() {
      string str1 = "timetime";
      string str2 = "abccba";
      string str3 = "abcdef";
      
      Console.WriteLine($"'{str1}': {(CheckSameCharacters(str1) ? "Same" : "Different")} character sets");
      Console.WriteLine($"'{str2}': {(CheckSameCharacters(str2) ? "Same" : "Different")} character sets");
      Console.WriteLine($"'{str3}': {(CheckSameCharacters(str3) ? "Same" : "Different")} character sets");
   }
}

The output of the above code is −

'timetime': Same character sets
'abccba': Same character sets
'abcdef': Different character sets

Using LINQ GroupBy Method

An alternative approach using LINQ for more readable code −

using System;
using System.Linq;

class Program {
   static bool CheckSameCharactersLinq(string str) {
      int length = str.Length;
      if (length == 1) return true;
      
      string leftHalf = str.Substring(0, length / 2);
      string rightHalf = str.Substring(length / 2);
      
      var leftFreq = leftHalf.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());
      var rightFreq = rightHalf.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());
      
      return leftFreq.Count == rightFreq.Count && 
             leftFreq.All(kvp => rightFreq.ContainsKey(kvp.Key) && rightFreq[kvp.Key] == kvp.Value);
   }
   
   public static void Main() {
      string[] testStrings = {"abba", "racecar", "hello", "aabbcc"};
      
      foreach (string str in testStrings) {
         bool result = CheckSameCharactersLinq(str);
         Console.WriteLine($"'{str}': {(result ? "Same" : "Different")} character sets in both halves");
      }
   }
}

The output of the above code is −

'abba': Same character sets in both halves
'racecar': Different character sets in both halves
'hello': Different character sets in both halves
'aabbcc': Same character sets in both halves

Comparison

Approach Time Complexity Space Complexity Readability
Character Frequency Arrays O(n) O(1) - fixed size arrays Good
LINQ GroupBy O(n) O(k) - k unique characters Excellent

Conclusion

Both methods effectively determine if string halves contain the same character sets. The frequency array approach offers optimal space complexity for lowercase letters, while the LINQ approach provides better readability and handles any character set. Choose based on your performance requirements and code maintainability preferences.

Updated on: 2026-03-17T07:04:35+05:30

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements