Skip to main content

6. Valid Anagram

easyAsked at Confluent

Decide if two strings are anagrams — Confluent uses it as a warm-up to test count-based hashing before moving to streaming-character-frequency questions.

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. Anagram means the same character counts in any order.

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 both strings

Sort each string and compare equality.

Time
O(n log n)
Space
O(n)
return s.split('').sort().join('') === t.split('').sort().join('');

Tradeoff:

2. Character count

Build a 26-slot count from s; subtract from t. If any count is non-zero at the end the strings differ.

Time
O(n)
Space
O(1)
function isAnagram(s, t) {
  if (s.length !== t.length) return false;
  const c = new Array(26).fill(0);
  const A = 'a'.charCodeAt(0);
  for (let i = 0; i < s.length; i++) {
    c[s.charCodeAt(i)-A]++;
    c[t.charCodeAt(i)-A]--;
  }
  return c.every(x => x === 0);
}

Tradeoff:

Confluent-specific tips

Confluent will ask how to do this on a stream of characters arriving over Kafka — answer with per-partition count vectors plus a final reduce on a global topic, so consumer-group rebalance doesn't lose progress.

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 Confluent interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →