94. Valid Anagram
easyAsked at OlaDetermine whether two strings are anagrams of each other.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram uses exactly the same characters with the same frequency.
Constraints
1 <= s.length, t.length <= 5 * 10^4s and t consist of lowercase English letters
Examples
Example 1
Input
s = "anagram", t = "nagaram"Output
trueExample 2
Input
s = "rat", t = "car"Output
falseApproaches
1. Sort and compare
Sort both strings and compare.
- Time
- O(n log n)
- Space
- O(n)
return [...s].sort().join('') === [...t].sort().join('');Tradeoff:
2. Counter array
Increment counts on s and decrement on t in a 26-length array; valid iff all zeros.
- Time
- O(n)
- Space
- O(1)
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const cnt = Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
cnt[s.charCodeAt(i) - 97]++;
cnt[t.charCodeAt(i) - 97]--;
}
return cnt.every(x => x === 0);
}Tradeoff:
Ola-specific tips
Ola interviewers like the 26-counter pattern; tie it to fast equality checks on hashed driver-feature bags during cohort grouping.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More Ola coding interview questions
- 1. Two Sum
- 2. Valid Parentheses
- 3. Merge Two Sorted Lists
- 4. Remove Duplicates from Sorted Array
- 5. Remove Element
- 6. Search Insert Position
- 7. Plus One
- 8. Merge Sorted Array