Check if both halves of the string have at least one different character in Python

When working with strings, sometimes we need to check if two halves have different character compositions. This involves splitting a string from the middle and comparing character frequencies between the left and right halves. For odd-length strings, we ignore the middle character.

Problem Understanding

Given a string, we need to ?

  • Split the string into two equal halves (ignoring middle character if odd length)
  • Count character frequencies in each half
  • Check if any character has different frequencies between halves

Algorithm Steps

The solution follows these steps ?

  • Create frequency maps for left and right halves
  • Populate left half frequencies from index 0 to n//2-1
  • Populate right half frequencies from index n//2 to n-1
  • Compare frequencies for each character in the string
  • Return True if any character has different frequencies

Implementation

from collections import defaultdict

def solve(s):
    left_freq = defaultdict(int)
    right_freq = defaultdict(int)
    n = len(s)
    
    # Count frequencies in left half
    for i in range(n//2):
        left_freq[s[i]] += 1
    
    # Count frequencies in right half  
    for i in range(n//2, n):
        right_freq[s[i]] += 1
    
    # Check if any character has different frequencies
    for char in s:
        if right_freq[char] != left_freq[char]:
            return True
    
    return False

# Test the function
s = "helloohekk"
print(f"String: {s}")
print(f"Result: {solve(s)}")
String: helloohekk
Result: True

How It Works

For the string "helloohekk" ?

  • Left half: "hello" ? {'h':1, 'e':1, 'l':2, 'o':1}
  • Right half: "ohekk" ? {'o':1, 'h':1, 'e':1, 'k':2}
  • Comparison: Character 'l' appears 2 times in left but 0 times in right
  • Result: True (halves have different character compositions)

Additional Examples

# Test with different cases
test_cases = ["abccba", "abcdef", "aabbaa", "abcabc"]

for test in test_cases:
    result = solve(test)
    left_half = test[:len(test)//2]
    right_half = test[len(test)//2:]
    print(f"'{test}' ? Left: '{left_half}', Right: '{right_half}' ? {result}")
'abccba' ? Left: 'abc', Right: 'cba' ? False
'abcdef' ? Left: 'abc', Right: 'def' ? True
'aabbaa' ? Left: 'aab', Right: 'baa' ? False
'abcabc' ? Left: 'abc', Right: 'abc' ? False

Time and Space Complexity

  • Time Complexity: O(n) where n is the string length
  • Space Complexity: O(k) where k is the number of unique characters

Conclusion

This algorithm efficiently checks if string halves have different character compositions by comparing frequency maps. It handles both even and odd-length strings by automatically ignoring the middle character in odd-length cases.

Updated on: 2026-03-25T14:24:54+05:30

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements