Taro Logo

Valid Anagram

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+26
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.5K views
Topics:
Strings

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Example 1:

Input: s = "anagram", t = "nagaram"

Output: true

Example 2:

Input: s = "rat", t = "car"

Output: false

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • 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?

Solution


Clarifying Questions

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:

  1. What character set should we expect? Are we dealing strictly with lowercase English letters (a-z), or should we support Unicode characters, uppercase letters, spaces, and punctuation?
  2. How should we handle empty strings or strings of unequal lengths?
  3. Is the comparison case-sensitive (e.g., does 'A' match 'a'), and should whitespace or special characters be ignored?
  4. Are there any memory limitations we need to be mindful of if the input strings are extremely large?
  5. Can we assume that both strings fit entirely in memory?

Brute Force Solution

Approach

To figure out if two words are anagrams of each other using the most straightforward approach, you can imagine making every single possible rearrangement of the first word. Then, you simply compare each of those creations against the second word to see if any of them match.

Here's how the algorithm would work step-by-step:

  1. Take the first word and write down every possible scrambled version or combination of its letters, no matter how nonsensical it might look.
  2. Go through each of those newly created letter combinations one by one.
  3. Compare each combination directly to the entire second word.
  4. If you find even one combination that is an exact match for the second word, you know they are anagrams.
  5. If you check every single scrambled combination and none of them match the second word, conclude that they are not anagrams.

Code Implementation

import itertools


def is_valid_anagram(first_word, second_word):
    # Generate every possible permutation to check all letter rearrangement possibilities
    all_permutations = itertools.permutations(first_word)


    for current_permutation in all_permutations:
        joined_permutation = "".join(current_permutation)


        # Check every generated rearrangement against the target word for an exact match
        if joined_permutation == second_word:
            return True


    # Return false if all possible permutations were exhausted without a match
    return False

Big(O) Analysis

Time Complexity
O(n!) – To determine if two words are anagrams using this permutation approach, we must first generate every possible scrambled combination of the first word, where n represents the length of the string. Generating all permutations requires factorial time because there are n factorial distinct ways to arrange n unique characters. For each of these n factorial generated combinations, we then perform a direct string comparison against the second word. This leads to approximately n! * n operations, which is dominated by the factorial term and simplifies to O(n!).
Space Complexity
O(N!) – The plain English explanation requires generating every possible scrambled version or permutation of the first word, which results in N factorial total combinations. Storing all of these intermediate letter combinations simultaneously requires an auxiliary data structure whose size grows exponentially with the input length N. Consequently, the memory consumption is dominated by storing this massive set of permutations, leading to a space complexity of O(N!).

Optimal Solution

Approach

Instead of comparing every single character of both words against each other from scratch, the optimal approach counts how many times each letter appears in the first word. Then, it uses those exact same counts to check off every matching letter in the second word.

Here's how the algorithm would work step-by-step:

  1. Look at the first word and count how many times each letter shows up, keeping a tally of your findings.
  2. Move on to the second word and subtract one from your tally every time you see a letter matching your earlier counts.
  3. If you ever try to subtract a letter that was not in your original tally, or if you end up with leftover counts at the very end, realize the words do not match.
  4. If every tally is used up completely and perfectly, conclude that both words contain the exact same letters in different arrangements.

Code Implementation

def is_anagram(first_word, second_word):
    if len(first_word) != len(second_word):
        return False

    # Different lengths cannot be anagrams, so we fail early to save computation time.
    letter_frequency_map = {}

    for current_character in first_word:
        if current_character in letter_frequency_map:
            letter_frequency_map[current_character] += 1
        else:
            letter_frequency_map[current_character] = 1

    for current_character in second_word:
        if current_character not in letter_frequency_map or letter_frequency_map[current_character] == 0:
            return False

        # We decrement to ensure every character from the second word cancels out the first.
        letter_frequency_map[current_character] -= 1

    # All counts must be perfectly exhausted to confirm both words are true anagrams.
    return True

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the total length of the strings. The first step iterates through the first word of length n to count the frequency of each character. The second step iterates through the second word of length n to subtract those counts. Since these two sequential passes process each character a constant number of times, the total operations approximate n + n, which simplifies to O(n).
Space Complexity
O(1) – The algorithm allocates a fixed-size frequency tally representing the alphabet to store character counts. Because the number of possible unique characters is bounded by a constant, such as 26 English letters, the extra memory required remains entirely constant regardless of the input string length N. Therefore, the auxiliary space complexity simplifies to O(1) constant time.

Edge Cases

Strings of different lengths
How to Handle:
Return false immediately by checking if the lengths of s and t are equal at the start.
Empty strings
How to Handle:
Return true because two empty strings are technically valid anagrams of each other.
Single-character strings that match or do not match
How to Handle:
Compare the single characters directly or through the frequency count to return true or false accurately.
Strings with all identical characters
How to Handle:
Frequency counter correctly increments and decrements the counts to ensure exact matching quantities.
Strings with Unicode characters or emojis
How to Handle:
Use a hash map instead of a fixed-size array to support arbitrary character sets beyond standard ASCII.
Extremely large strings exceeding memory limits
How to Handle:
Process the strings in a single pass using a compact frequency array to optimize space and time complexity.
Case sensitivity where uppercase and lowercase letters differ
How to Handle:
Treat characters strictly as case-sensitive unless a normalization step is explicitly required by the prompt.
Completely disjoint character sets
How to Handle:
The frequency array will encounter negative counts or unmatched non-zero entries, resulting in an early return of false.
0/75 completed