Check if both halves of the string have same set of characters in Python
Last Updated :
10 Apr, 2023
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
This problem has existing solution, please refer Check if both halves of the string have same set of characters link. We will solve this problem in Python quickly using Dictionary comparison. Approach is very simple :
- Break string in two parts and convert both parts into dictionary using Counter(iterator) method, each dictionary contains it’s character as key and frequency as value.
- Now compare these two dictionaries. In python we can compare two using == operator, it first checks keys of both dictionaries are same or not, then it checks for values of each key. If everything is equal that means two dictionaries are identical.
Implementation:
Python3
from collections import Counter
def checkTwoHalves( input ):
length = len ( input )
if (length % 2 ! = 0 ):
first = input [ 0 :length / / 2 ]
second = input [(length / / 2 ) + 1 :]
else :
first = input [ 0 :length / / 2 ]
second = input [length / / 2 :]
if Counter(first) = = Counter(second):
print ( 'YES' )
else :
print ( 'NO' )
if __name__ = = "__main__" :
input = 'abbaab'
checkTwoHalves( input )
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach#2: using sorted()
This approach checks if both halves of a given string have the same set of characters. It first checks if the length of the string is odd, in which case the answer is “NO”. Otherwise, it sorts the left and right halves of the string and checks if they are equal. If they are, the answer is “YES”, otherwise it is “NO”.
Algorithm
1. Divide the input string into two halves, left and right.
2. If the length of the string is odd, return “NO” because it is not possible to divide the string into two halves of equal length.
3. Sort both halves and compare them.
Python3
def same_set_of_chars(s):
n = len (s)
if n % 2 = = 1 :
return "NO"
left = sorted (s[:n / / 2 ])
right = sorted (s[n / / 2 :])
return "YES" if left = = right else "NO"
s = "abccab"
print (same_set_of_chars(s))
|
Time Complexity: O(n log n), where n is the length of the input string.
Space Complexity: O(n), where n is the length of the input string.
Please Login to comment...