Valid Anagram: Checking Character Arrangements
The "Valid Anagram" problem involves determining whether two strings are anagrams of each other, meaning they are made of the same characters, just in a different order.
Problem Statement
Given two strings s and t, write a function to determine if t is an anagram of s.
Example
- Input:
s = "anagram", t = "nagaram" - Output:
true
Solution Approach - Character Counting (javascript)
Breaking Down the Solution
- Length Check: First, check if
sandtare of the same length. If not, they can't be anagrams. - Count Characters in
s: Use a map to count the occurrences of each character ins. - Verify Characters in
t: Iterate overtand decrease the count for each character. If a character intisn't insor the count goes below zero,tis not an anagram ofs.
Solution in TypeScript
In this TypeScript solution:
- The function
isAnagramtakes two strings,sandt, and checks if they are anagrams. - It first compares the lengths of
sandt. If they are different, the function returnsfalseimmediately. - A record
countis used to count the occurrences of each character ins. - Then, the function iterates through
t, decrementing the count for each character. If a character intis not insor the count drops below zero,tis not an anagram ofs. - If all character counts are balanced, the function returns
true.
This implementation effectively checks whether two strings are anagrams by comparing the frequency of each character in both strings.
Conclusion
The Valid Anagram problem is a fundamental exercise in string manipulation and character counting. It's a simple yet effective way to understand the importance of character frequency and order in strings.
Rust Solution
Rust's entry(c).or_insert(0) returns a mutable reference to the slot, so *count.entry(c).or_insert(0) += 1 counts each character in a single lookup rather than a separate get-then-set; the value type of HashMap::new() is inferred from the 0 literal in or_insert, and chars() iterates Unicode scalar values rather than bytes. The verify pass uses match on count.get_mut(&c) — borrowing the key with &c — and dereferences the Some(v) binding with *v to test and decrement, while None => return false catches a character never present in s. The trailing bare true is the return value, since a Rust block's final expression needs no return keyword.
Go Solution
Go's map[rune]int{} leans on zero-value semantics: count[c]++ works even when c was never inserted (a missing key reads as 0), and the verify loop tests count[c] == 0 directly instead of the comma-ok v, ok := m[k] form. Ranging a string with for _, c := range s decodes it into rune code points, so c is a full Unicode character and the discarded _ is a byte offset rather than a sequential counter — which is why the map is keyed by rune to match what range yields.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.