DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

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
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

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


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

Top comments (0)