-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid-anagram.ts
More file actions
35 lines (32 loc) · 1.03 KB
/
Copy pathvalid-anagram.ts
File metadata and controls
35 lines (32 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 242. Valid Anagram (Easy)
* Link: https://leetcode.com/problems/valid-anagram/
*
* Given two strings `s` and `t`, return true if `t` is an anagram of `s`
* (uses exactly the same characters with the same frequencies).
*
* Example:
* Input: s = "anagram", t = "nagaram"
* Output: true
*
* Approach:
* Anagrams must have identical character counts. Tally `s` in a map, then
* decrement while scanning `t`; if any count goes negative or a character is
* missing, or lengths differ, they are not anagrams.
*
* Time: O(n) — two passes over the strings.
* Space: O(k) — k = size of the character alphabet.
*/
export function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const counts = new Map<string, number>();
for (const ch of s) {
counts.set(ch, (counts.get(ch) ?? 0) + 1);
}
for (const ch of t) {
const remaining = counts.get(ch);
if (remaining === undefined || remaining === 0) return false;
counts.set(ch, remaining - 1);
}
return true;
}