π·οΈ Category: Strings / HashMap | π― Difficulty: Easy | π₯ Frequency: β
β
β
β
β
π Problem Statement
Given two strings, return True if they are anagrams of each other (same characters, same frequency, different order). This process is often referred to as an anagram check.
π₯ Input β "listen", "silent" π€ Output β True
π₯ Input β "triangle", "integral" π€ Output β True
π₯ Input β "hello", "world" π€ Output β False
π§ What the Interviewer is Testing
| Concept | Why It Matters |
|---|---|
| Counter comparison | Python library knowledge |
| Sorting approach | Alternative thinking |
| Edge cases | Different lengths, empty strings |
π‘ Approach
Two strings are anagrams if:
β Same length AND
β Same character frequencies
Methods:
β
Counter comparison β O(n)
β
Sorted comparison β O(n log n)
β Optimal Solution β Counter
from collections import Counter
def is_anagram(s1: str, s2: str) -> bool:
return Counter(s1.lower()) == Counter(s2.lower())
# ββ Test Cases βββββββββββββββββββββββββββββββββ
print(is_anagram("listen", "silent")) # β
True
print(is_anagram("triangle", "integral")) # β
True
print(is_anagram("hello", "world")) # β
False
print(is_anagram("", "")) # β
True
π Sorting Approach
def is_anagram_sort(s1: str, s2: str) -> bool:
return sorted(s1.lower()) == sorted(s2.lower())
π Complexity Analysis
ββββββββββββββββββββ¬βββββββββββββ¬βββββββββββββββββββββββββββ
β Approach β Time β Space β
ββββββββββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββββ€
β Counter β
β O(n) β O(k) k=unique chars β
β Sorted β O(n log n) β O(n) β
ββββββββββββββββββββ΄βββββββββββββ΄βββββββββββββββββββββββββββ
π€ How to Explain in the Interview
βTwo strings are anagrams if they have the same characters with the same frequencies. Counter creates a character frequency map for each string β if theyβre equal, itβs an anagram. This is O(n). Alternatively, sorting both strings and comparing is O(n log n) but simpler to reason about.β
βTwo strings are anagrams if they have the same characters with the same frequencies. Counter creates a character frequency map for each string β if theyβre equal, itβs an anagram. This is O(n). Alternatively, sorting both strings and comparing is O(n log n) but simpler to reason about.β
π Common Follow-up Questions
Q1 β Group all anagrams from a list?
from collections import defaultdict
def group_anagrams(words: list) -> list:
groups = defaultdict(list)
for word in words:
key = tuple(sorted(word))
groups[key].append(word)
return list(groups.values())
# ["eat","tea","tan","ate","nat","bat"]
# β [["eat","tea","ate"], ["tan","nat"], ["bat"]]
π Set 1 of 4 β Python Interview Prep Series β devprepguide.com
