101 Logo
onenoughtone

Code Implementation

Word Puzzle Challenge Implementation

Below is the implementation of the word puzzle challenge:

solution.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function isAnagram(s, t) {
// Clean the input strings
s = s.toLowerCase().replace(/[^a-z0-9]/g, '');
t = t.toLowerCase().replace(/[^a-z0-9]/g, '');
// Check if lengths are equal
if (s.length !== t.length) {
return false;
}
// Approach 1: Character Frequency Counting
const counter = {};
// Count characters in first string
for (let char of s) {
counter[char] = (counter[char] || 0) + 1;
}
// Decrement counts for second string
for (let char of t) {
if (!counter[char]) {
return false;
}
counter[char]--;
}
// Check if all counts are zero
return Object.values(counter).every(count => count === 0);
}
// Alternative approach using sorting
function isAnagramAlt(s, t) {
// Clean the input strings
s = s.toLowerCase().replace(/[^a-z0-9]/g, '');
t = t.toLowerCase().replace(/[^a-z0-9]/g, '');
// Check if lengths are equal
if (s.length !== t.length) {
return false;
}
// Sort both strings and compare
return s.split('').sort().join('') === t.split('').sort().join('');
}
// Test cases
console.log(isAnagram("listen", "silent")); // true
console.log(isAnagram("Astronomer", "Moon starer")); // true
console.log(isAnagram("hello", "world")); // false

Step-by-Step Explanation

Let's break down the implementation:

  1. Clean the Input: Normalize both strings by converting to lowercase and removing non-alphanumeric characters.
  2. Check Lengths: If the cleaned strings have different lengths, they cannot be anagrams, so return false.
  3. Count Characters: Create a hash table to count the frequency of each character in the first string.
  4. Verify Counts: Iterate through the second string, decrementing the counts. If any character is missing or has a count of zero, return false.
  5. Final Check: Ensure all character counts are zero, which confirms the strings are anagrams.
ProblemSolutionCode
101 Logo
onenoughtone