Given two strings s
and t
, determine if t
is an anagram of s
. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Return true
if t
is an anagram of s
, and false
otherwise.
Example 1:
s = "anagram", t = "nagaram"
true
Example 2:
s = "rat", t = "car"
false
Constraints:
1 <= s.length, t.length <= 5 * 10^4
s
and t
consist of lowercase English letters.Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force way to check if two words are anagrams (meaning they contain the same letters, but in a different order) is to consider all possible arrangements of the letters in one word. Then, compare each arrangement with the other word to see if there's a match.
Here's how the algorithm would work step-by-step:
def is_anagram_brute_force(first_string, second_string):
# Function to generate all permutations of a string
def find_all_permutations(input_string, current_permutation, all_permutations):
if not input_string:
all_permutations.append(''.join(current_permutation))
return
for index in range(len(input_string)):
find_all_permutations(
input_string[:index] + input_string[index+1:],
current_permutation + [input_string[index]],
all_permutations
)
# Generate all permutations of the first string
all_possible_permutations = []
# Need to start recursion with empty list
find_all_permutations(first_string, [], all_possible_permutations)
# Now we check if any permutation matches second string
for permutation in all_possible_permutations:
# If a match is found, strings are anagrams
if permutation == second_string:
return True
# If no permutation matches, not anagrams
return False
The goal is to efficiently determine if two words are anagrams of each other. A clever approach is to count the occurrences of each letter in both words and then compare the counts. If the counts are identical for all letters, the words are anagrams.
Here's how the algorithm would work step-by-step:
def are_anagrams(first_word, second_word):
if len(first_word) != len(second_word):
return False
# Use a dictionary to store character counts
character_counts = {}
for character in first_word:
character_counts[character] = character_counts.get(character, 0) + 1
# Decrement counts based on the second word
for character in second_word:
if character in character_counts:
character_counts[character] -= 1
else:
return False
# Check if all counts are zero
# Meaning both words contain the same characters
for count in character_counts.values():
if count != 0:
return False
return True
Case | How to Handle |
---|---|
Both input strings are empty | Return true, as empty strings can be considered anagrams of each other. |
One string is empty, and the other is not | Return false, as an empty string cannot be an anagram of a non-empty string. |
Input strings have different lengths | Return false immediately, as anagrams must have the same length. |
Input strings are very long (e.g., 1 million characters) | The solution's time complexity should be O(n) or O(n log n) to handle large inputs efficiently, using a hash map or sorting. |
Input strings contain unicode characters | The character counting mechanism (e.g., hash map) must support unicode characters correctly. |
Input strings contain only one distinct character repeated many times, but with different counts (e.g., 'aaaa' and 'aaa') | The solution must correctly count the occurrences of each character to distinguish between these cases and return false. |
Input strings are identical | Return true, as identical strings are anagrams of each other. |
Input strings contain mixed case (e.g., 'Anagram' and 'anagram') | Convert both strings to lowercase or uppercase before comparison to ensure case-insensitive anagram detection. |