94. Valid Anagram
easyAsked at OlaDetermine whether two strings are anagrams of each other.
By Alex Chen, 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
s = "anagram", t = "nagaram"trueExample 2
s = "rat", t = "car"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.
Practice these live with InterviewChamp.AI
Drill Valid Anagram and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →