Given a string S of size N, the duty is to test if a string might be break up into two non-intersecting strings such that the variety of distinct characters are equal in each.
Examples:
Enter: N = 6, S = “abccba”
Output: True
Rationalization: Splitting two strings as “abc” and “cba” has 3 distinct characters every.Enter: N = 5, S = “aacaa”
Output: False
Rationalization: Not doable to separate it into two strings of the identical distinct characters.
Method: To unravel the issue comply with the under instinct:
The instinct behind fixing the issue of checking if a string might be break up into two components such that each components have the identical variety of distinct letters to maintain monitor of the frequency of the characters within the string and examine it with the frequency of characters within the substrings as we iterate by means of the string.
Comply with the under steps to unravel the issue:
- Begins by storing the frequency of every character within the enter string in an array referred to as freq of dimension 26.
- Then, creates one other array temp of dimension 26 to retailer the frequency of every character in a portion of the enter string.
- Then iterates over the enter string and in every iteration scale back the frequency of the present character within the freq array and improve the frequency of the present character within the temp array.
- After that, initializes two variables cnt1 and cnt2 to 0 and iterate over each the freq and temp arrays to depend the variety of non-zero values in every array.
- If cnt1 and cnt2 are equal, it implies that the enter string might be break up into two components such that they’ve the identical variety of distinct letters, and the perform returns True.
- If it’s not doable to separate the string into two components such that they’ve the identical variety of distinct letters, the perform returns False.
Under is the implementation of the above method.
C++
|
Time Complexity: O(N*26), the place N represents the scale of the given string and 26 for the inside loop.
Auxiliary House: O(N), the place N represents the scale of the freq and temp array.