CodingReported in a candidate post, Aug 2020
Check if two words are anagram or not
Filed under Oracle
Free read 1 of 3The question
Given two strings, determine whether they are anagrams of each other. Two strings are anagrams if they contain the same characters with the same frequencies.
Constraints
- Strings consist of lowercase English letters
- Length of strings can be up to 10^5
- Time complexity should be O(n)
Examples
- Input
- s1 = 'listen', s2 = 'silent'
- Output
- True
- Why
- Both contain the same characters in different orders.
Approach
Confirm if case sensitivity and whitespace matter.
Sort both strings and compare them for equality.
Use a hash map or an array of size 26 to count character frequencies for both strings and compare counts.
Handle strings of different lengths immediately by returning False.
Solution
O(n) time, O(1) space
def is_anagram(s1, s2):
if len(s1) != len(s2): return False
count = {}
for char in s1:
count[char] = count.get(char, 0) + 1
for char in s2:
if char not in count or count[char] == 0: return False
count[char] -= 1
return True
Tips
- What they are testing: Tests character frequency counting and edge cases like empty strings or different lengths.
- Common mistake: Sorting both strings (O(n log n)) instead of using a frequency map (O(n)).
Related Oracle questions
Collected from public candidate posts and coding forums. Updated Nov 2026.