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

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase string; we have to check whether we can split the string from middle which will give two halves having at least one-character difference between two sides. It may hold different characters or different frequency of each character. If the string is odd length string, then ignore the middle element and check for the remaining elements.

So, if the input is like s = "helloohekk", then the output will be True as "helloohekk" so left part is "hello" right part is "ohekk" left and right are different.

To solve this, we will follow these steps −

• left_freq := an empty map
• right_freq := an empty map
• n := size of s
• for i in range 0 to quotient of (n/2) - 1, do
• left_freq[s[i]] := left_freq[s[i]] + 1
• for i in range quotient of (n/2) to n - 1, do
• right_freq[s[i]] := right_freq[s[i]] + 1
• for each char in s, do
• if right_freq[char] is not same as left_freq[char], then
• return True
• return False

Let us see the following implementation to get better understanding −

## Example

Live Demo

from collections import defaultdict
def solve(s):
left_freq = defaultdict(int)
right_freq = defaultdict(int)
n = len(s)
for i in range(n//2):
left_freq[s[i]] += 1
for i in range(n//2, n):
right_freq[s[i]] += 1
for char in s:
if right_freq[char] != left_freq[char]:
return True
return False
s = "helloohekk"
print(solve(s))

## Input

"helloohekk"

## Output

True
Published on 30-Dec-2020 18:02:21