İçeriğe atla
ΣDSA Patterns
Menü
Dil

Hashing

Rehber 5 / 6 · Yol 5 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Valid Anagram

Problem (restated)

Return true if t is an anagram of s (same characters with same frequencies).

Intuition

Anagrams share a multiset of characters. compare frequency maps or sorted forms.

Approaches

Character counts

Tested only
Time O(n)Space O(1)

Idea. Count letters in s, decrement with t; all zeros means anagram. Assumes lowercase English.

Walkthrough. “anagram” / “nagaram” → counts cancel → true.

Trade-offs. Sorting is simpler but O(n log n). Unicode needs a hash map.

Solution
export function isAnagram(s: string, t: string): boolean {
  if (s.length !== t.length) return false;
  const cnt = new Array<number>(26).fill(0);
  for (let i = 0; i < s.length; i++) {
    cnt[s.charCodeAt(i)! - 97]!++;
    cnt[t.charCodeAt(i)! - 97]!--;
  }
  return cnt.every((c) => c === 0);
}
export function isAnagram(s: string, t: string): boolean {
  if (s.length !== t.length) return false;
  const cnt = new Array<number>(26).fill(0);
  for (let i = 0; i < s.length; i++) {
    cnt[s.charCodeAt(i)! - 97]!++;
    cnt[t.charCodeAt(i)! - 97]!--;
  }
  return cnt.every((c) => c === 0);
}

Reflection