![]() |
VOOZH | about |
Given two Strings, separated by delim, check if both contain same characters.
Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!' Output : True Explanation : Same characters, just diff. positions. Input : test_str1 = 'e!e!k!s', test_str2 = 'g!e!e!k!s', delim = '!' Output : False Explanation : g missing in 1st String.
Method #1 : Using sorted() + split()
In this, we perform split using split(), and then perform the task of sorting to get strings in order, post that strings are compared using the comparison operator.
The original string 1 is : e:e:k:s:g The original string 2 is : g:e:e:k:s Are strings similar : True
Time Complexity: O(n) -> (split function)
Auxiliary Space: O(n)
Method #2 : Using set() + split()
In this, instead of sort(), we convert strings to set(), to get ordering. This works only on unique character strings.
The original string 1 is : e:k:s:g The original string 2 is : g:e:k:s Are strings similar : True
Time Complexity: O(n) -> (split function)
Auxiliary Space: O(n)
Method #3: Using dictionary
In this approach, we can use dictionaries to count the frequency of each character in both the strings. Then, we can compare the frequency of each character between the two dictionaries to check if the strings have the same characters or not.
Here are the steps:
The original string 1 is : e:k:s:g The original string 2 is : g:e:k:s Are strings similar : True
Time complexity: O(n), where n is the length of the longer string (as we are looping through each character in each string once).
Auxiliary space: O(k), where k is the number of unique characters in both strings (as we are creating dictionaries to store the frequency of each character).
Method 4: using the Counter() function from the collections module.
This approach involves the following steps:
The original string 1 is : e:k:s:g The original string 2 is : g:e:k:s Are strings similar : True
Time complexity: The time complexity of this approach is O(n), where n is the length of the longest string.
Auxiliary space: The auxiliary space required by this approach is O(k), where k is the number of unique characters in both strings.
Method 5 : Using list comprehension and all()
step-by-step approach of the code:
Are strings similar : True
Time complexity: O(n^2) where n is the length of the longer string (due to the all() function in the list comprehension)
Auxiliary space: O(n) where n is the length of the longer string (for the two lists created in memory)