LeetCode 242: Valid Anagram — Python Solution

LeetCode 242: Valid Anagram is an Easy hashmap problem. This Python walkthrough develops a frequency equality solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyEasy
TopicHashmap
Reusable patternfrequency equality
ComplexityO(n) time and O(k) space

Recognizing the pattern

A hash table converts a repeated search for prior information into an average constant-time lookup.

For this problem specifically, count characters in one string and subtract characters from the other; all counts must finish at zero. The invariant worth writing beside the code is: The counter equals the frequency difference for the processed characters.

Step-by-step algorithm

  1. Identify the input state consumed by isAnagram(s, t) and initialize the data required by the frequency equality pattern.
  2. Count characters in one string and subtract characters from the other; all counts must finish at zero.
  3. After each update, verify the page’s central invariant: The counter equals the frequency difference for the processed characters.
  4. Finish only after the boundary behavior is covered: Different lengths cannot be anagrams; Unicode characters work as dictionary keys.

Python solution

from collections import Counter

class Solution:
    def isAnagram(self, s, t):
        return Counter(s) == Counter(t)

Reading the implementation

The main entry point is isAnagram(s, t). The implementation keeps little named state because each operation can be resolved directly from the current input position.

The method expresses the transformation directly without a general traversal loop. In concrete terms, count characters in one string and subtract characters from the other; all counts must finish at zero.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Count characters in one string and subtract characters from the other; all counts must finish at zero. Each update records the current item without invalidating earlier decisions; consequently, the counter equals the frequency difference for the processed characters.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(k) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Sorting may reduce implementation state and reveal ordering, but it can lose original positions and normally costs O(n log n). That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().isAnagram("anagram","nagaram")

Common mistakes and edge cases

  • Problem-specific boundary: Different lengths cannot be anagrams; Unicode characters work as dictionary keys.
  • Pattern-level pitfall: Choose whether to look up before inserting: inserting too early can accidentally match an element with itself.
  • Invariant check: after every update, confirm that the counter equals the frequency difference for the processed characters.

Interview review checklist

  • Explain why frequency equality matches the structure of this input.
  • State the invariant in one sentence before tracing code: The counter equals the frequency difference for the processed characters.
  • Derive O(n) time and O(k) space from how many times each element or state is visited.
  • Test the boundary explicitly: Different lengths cannot be anagrams; Unicode characters work as dictionary keys.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 290. Word Pattern · Next: 49. Group Anagrams