Given a string S of size N, the duty is to verify if a string could be break up into two non-intersecting strings such that the variety of distinct characters are equal in each.
Enter: N = 6, S = “abccba”
Clarification: Splitting two strings as “abc” and “cba” has 3 distinct characters every.
Enter: N = 5, S = “aacaa”
Clarification: Not doable to separate it into two strings of the identical distinct characters.
Method: To resolve the issue comply with the beneath instinct:
The instinct behind fixing the issue of checking if a string could be break up into two components such that each components have the identical variety of distinct letters to maintain observe of the frequency of the characters within the string and evaluate it with the frequency of characters within the substrings as we iterate by means of the string.
Observe the beneath steps to resolve the issue:
- Begins by storing the frequency of every character within the enter string in an array known 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 cut back the frequency of the present character within the freq array and enhance 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 signifies that the enter string could be break up into two components such that they’ve the identical variety of distinct letters, and the operate 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 operate returns False.
Under is the implementation of the above strategy.
Time Complexity: O(N*26), the place N represents the scale of the given string and 26 for the interior loop.
Auxiliary Area: O(N), the place N represents the scale of the freq and temp array.