How I Understood Checking Anagrams in Python (LeetCode 242)
When I first saw this problem, it looked like it might require sorting or multiple passes, but after thinking about it, I realized it can be solved efficiently with frequency counting.
Problem
Given two strings s and t, determine if t is an anagram of s.
An anagram means both strings contain the same characters with the same frequency, but possibly in a different order.
Examples:
Python
s = "anagram"
t = "nagaram"
Output: True
Python
s = "rat"
t = "car"
Output: False
** What I Noticed**
Instead of sorting both strings (O(n log n)), I focused on:
Counting how many times each character appears in s
Subtracting counts based on characters in t
If all counts are zero at the end, the strings are anagrams
This approach is linear time O(n) and uses minimal extra space.
**What Helped Me
**Using a single frequency dictionary worked perfectly:
Check lengths first: If lengths differ, they can’t be anagrams
Count characters:
Add for s
Subtract for t
Check all counts: If any value isn’t zero, return False
This combines counting for both strings in one pass, making it efficient.
Code (Python)
Python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# Step 1: Base case - different lengths cannot be anagrams
if len(s) != len(t):
return False
# Step 2: Initialize frequency dictionary
count = {}
for i in range(len(s)):
# Increment count for string s
count[s[i]] = count.get(s[i], 0) + 1
# Decrement count for string t
count[t[i]] = count.get(t[i], 0) - 1
# Step 3: Check if all values are zero
for val in count.values():
if val != 0:
return False
return True
** Example Usage**
Python
s = "anagram"
t = "nagaram"
solution = Solution()
print(solution.isAnagram(s, t))
Output:
Plain text
True
Complexity
Time: O(n) — iterate through both strings once
Space: O(1) — at most 26 keys for lowercase letters (or O(n) in general for all characters)
What I Learned
This problem shows that thinking in terms of frequency counting is often more efficient than sorting.
Check lengths first
Use one dictionary for both strings
One pass is enough to verify anagrams
Final Thought
At first, I thought this problem required sorting.
Once I realized:
“Count characters for s and subtract counts for t”
…it became clean and intuitive.
This is a great example of clever use of hash maps for string problems.
United States
NORTH AMERICA
Related News
Jeff Bezos Seeking $100 Billion to Buy Manufacturing Companies, 'Transform' Them With AI
9h ago
Firefox Announces Built-In VPN and Other New Features - and Introduces Its New Mascot
9h ago
Can Private Space Companies Replace the ISS Before 2030?
9h ago
Juicier Steaks Soon? The UK Approves Testing of Gene-Edited Cow Feed
9h ago
White House Unveils National AI Policy Framework To Limit State Power
9h ago