Open In App

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

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 :

  1. 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.
  2. 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




# Function to Check if both halves of
# the string have same set of characters
from collections import Counter
 
def checkTwoHalves(input):
     
    length = len(input)
     
    # Break input string in two parts
    if (length % 2 != 0):
        first = input[0:length // 2]
        second = input[(length // 2) + 1:]
    else:
        first = input[0:length // 2]
        second = input[length // 2:]
 
    # Convert both halves into dictionary and compare
    if Counter(first) == Counter(second):
        print ('YES')
    else:
        print ('NO')
 
# Driver program
if __name__ == "__main__":
    input = 'abbaab'
    checkTwoHalves(input)


Output

NO

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"
 
# Example usage
s = "abccab"
print(same_set_of_chars(s)) # Output: YES


Output

YES

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.



Similar Reads

Check if both halves of the string have same set of characters
Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give 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 h
12 min read
Check if both halves of the string have at least one different character
Earlier we have discussed on how to check if both halves of the string have same set of characters. Now, we further extend our problem on checking if both halves of the string have at least one different character. Examples: Input : baaaabOutput: No, both halves do not differ at allThe two halves contain the same characters and their frequencies ma
15 min read
Maximum length of subarray consisting of same type of element on both halves of sub-array
Given an array arr[] of N integers, the task is to find the maximum length of sub-array consisting of the same type of element on both halves of the sub-array. Also, the elements on both halves differ from each other. Examples: Input: arr[] = {2, 3, 4, 4, 5, 5, 6, 7, 8, 10}Output: 4Explanation:{2, 3}, {3, 4}, {4, 4, 5, 5}, {5, 6}, etc, are the vali
8 min read
Check if both halves of a string are Palindrome or not
Given a string str, the task is to check whether the given string can be split into two halves, each of which is palindromic. If it is possible, print Yes. Otherwise, print No. Examples: Input: str = "naan" Output: No Explanation: Since both halves "na" and "an" are not palindrome. Input: momdad Output: Yes Explanation: Since both half "mom" and "d
5 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
Count ways to partition a string such that both parts have equal distinct characters
Content has been removed on Author's request.
1 min read
Partition the string in two parts such that both parts have at least k different characters
Given a string of lowercase English alphabets and an integer 0 < K <= 26. The task is to divide the string into two parts (also print them) such that both parts have at least k different characters. If there are more than one answers possible, print one having the smallest left part. If there is no such answers, print "Not Possible".Examples:
14 min read
All possible binary numbers of length n with equal sum in both halves
Given a number n, we need to print all n-digit binary numbers with equal sum in left and right halves. If n is odd, then mid element can be either 0 or 1. Examples: Input : n = 4 Output : 0000 0101 0110 1001 1010 1111 Input : n = 5 Output : 00000 00100 01001 01101 01010 01110 10001 10101 10010 10110 11011 11111 The idea is to recursively build left
10 min read
Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Check if a String can be converted to another by inserting character same as both neighbours
Given 2 strings A and B . The task is to check if A can be converted into B by performing the following operation any number of times : Choose an index from 0 to N - 2 (suppose N is the length of A). If the character at ith index is equal to the character at (i + 1 )th index, then insert the same character between the ith and (i + 1)th index. Examp
9 min read
Article Tags :
Practice Tags :