LeetCode 242: Valid Anagram — Step-by-Step Visual Trace


Easy — Hash Table | String | Sorting

The Problem

Determine if two strings are anagrams of each other, meaning they contain the exact same characters with the same frequencies but possibly in different orders.

Approach

Use a hash map to count character frequencies in the first string, then iterate through the second string decrementing counts. If any character is missing or count goes below zero, the strings aren’t anagrams.

Time: O(n) · Space: O(n)

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        char_frequency = {}

        # Build character frequency map for string s
        for char in s:
            char_frequency[char] = char_frequency.get(char, 0) + 1

        # Compare with string t
        for char in t:
            if char not in char_frequency or char_frequency[char] == 0:
                return False
            char_frequency[char] -= 1

        return True

Watch It Run

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.


Comments