Skip to main content

94. Valid Anagram

easyAsked at Ola

Determine 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^4
  • s and t consist of lowercase English letters

Examples

Example 1

Input
s = "anagram", t = "nagaram"
Output
true

Example 2

Input
s = "rat", t = "car"
Output
false

Approaches

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.

Output

Press Run or Cmd+Enter to execute

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 →