1. Signal

2. Edge cases

Edge case Example Expected output
Both strings empty ("", "") True
Same single character ("a", "a") True
Different characters ("a", "b") False
Different lengths ("ab", "a") False
Same characters, different order ("anagram", "nagaram") True
Different character frequencies ("aab", "abb") False
Repeated characters ("aacc", "ccaa") True
Large strings Two long strings Correct result

3. Brute force

Idea

Sort both strings and compare the sorted results. If the sorted strings are equal, the original strings contain exactly the same characters with the same frequencies.

Dry run

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

image.png

Step-by-step algorithm

  1. Check lengths: If len(s) != len(t), return False.
  2. Sort s: Create a sorted version of s.
  3. Sort t: Create a sorted version of t.
  4. Compare: Return whether the sorted strings are equal.

Implementation

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # Step 1: Check lengths.
        if len(s) != len(t):
            return False

        # Step 2-3: Sort both strings.
        sorted_s = sorted(s)
        sorted_t = sorted(t)

        # Step 4: Compare sorted characters.
        return sorted_s == sorted_t