def can_construct(ransom_note, magazine): # create an empty hash map to store the frequency of each character in the magazine string frequency = {} for char in magazine: # if character is already present in hash map then increment # its frequency by 1 if char in frequency: frequency[char] += 1 # else count its first occurrence else: frequency[char] = 1 for char in ransom_note: # if the character is not in the hash map or its count is 0, return False if char not in frequency or frequency[char] == 0: return False # otherwise, decrease the character's frequency in the hash map by 1 else: frequency[char] -= 1 return True # driver code def main(): ransom_notes = [ 'aab', 'hello', 'letsgothere', 'weneedtogetitdone', 'youhaveakindheart' ] magazines = [ 'abcva', 'helhoidde', 'edttsgftothsereleed', 'eunwueeydtwogyewbtitovnxe', 'abecdefghiavjklmaonopqhrtuvweaxyz' ] for i in range(len(ransom_notes)): print(i + 1, ".\t Ransom note: ", ransom_notes[i], sep="") print("\t Magazine : ", magazines[i], sep="") print("\n\t Can ransom note be constructed from magazine: ", can_construct(ransom_notes[i], magazines[i]), sep="") print("-" * 100) if __name__ == '__main__': main()