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)
function isAnagram(s, t) {
if (s.length !== t.length) return false;
let count = {};
for (let char of s) {
count[char] = (count[char] || 0) + 1;
}
for (let char of t) {
if (!count[char]) return false;
count[char]--;
}
return true;
}
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
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) {
return false;
}
const count: Record<string, number> = {};
for (const char of s) {
count[char] = (count[char] || 0) + 1;
}
for (const char of t) {
if (!count[char]) {
return false;
}
count[char]--;
}
return true;
}
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.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.