Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters.
Examples:
Input : s1 = ABHISHEKsinGH
: s2 = gfhfBHkooIHnfndSHEKsiAnG
Output : Possible
Input : s1 = Hello
: s2 = dnaKfhelddf
Output : Not Possible
Input : s1 = GeeksforGeeks
: s2 = rteksfoGrdsskGeggehes
Output : Possible
We have existing solution for this problem please refer Make a string from another by deletion and rearrangement of characters link. We will this problem quickly in python. Approach is very simple,
Convert both string into dictionary using Counter(iterable) method, each dictionary contains characters within string as Key and their frequencies as Value.
Now take intersection of two dictionaries and compare resultant output with dictionary of first string, if both are equal that means it is possible to convert string otherwise not.
Implementation:
Python3
from collections import Counter
def makeString(str1,str2):
dict1 = Counter(str1)
dict2 = Counter(str2)
result = dict1 & dict2
return result == dict1
if __name__ == "__main__":
str1 = 'ABHISHEKsinGH'
str2 = 'gfhfBHkooIHnfndSHEKsiAnG'
if (makeString(str1,str2)==True):
print("Possible")
else:
print("Not Possible")
Time Complexity: O(n)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule. Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
21 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...