Skip to content

Commit b948e5b

Browse files
add: solution for find-anagrams
1 parent 668d5fe commit b948e5b

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

find-anagrams/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Find All The Anagrams
2+
3+
Find all the anagrams within a series of words provided.
4+
5+
e.g.:
6+
7+
```console
8+
'eat', 'ate', 'tea', 'monk', 'konm', 'nkom', 'bbc', 'cbb', 'dell', 'ledl', 'llde'
9+
```
10+
11+
```console
12+
[
13+
['eat', 'ate', 'tea'],
14+
['monk', 'konm', 'nkom'],
15+
['bbc', 'cbb'],
16+
['dell', 'ledl', 'llde'],
17+
]
18+
```
19+
20+
## What is an Anagram?
21+
22+
Anagrams are words or phrases you spell by rearranging the letters of another word or phrase. For instance, fans of the Harry Potter series know that Lord Voldemort's full name is actually an anagram of his birth name, and some people even play games challenging one another to make anagrams still relevant to the original term. For example, "schoolmaster" can be turned into "the classroom", "punishments" becomes "nine thumps", and "debit card" turns into "bad credit".
23+
24+
## Execute
25+
26+
```bash
27+
node solution.js
28+
```

find-anagrams/solution.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const sortWord = (word) => {
2+
return word.split('').sort().join('');
3+
};
4+
5+
const findAnagrams = (words) => {
6+
let result = [];
7+
while (words.length) {
8+
const baseWord = words.shift();
9+
const group = [baseWord];
10+
const removeIndices = [];
11+
for (let i = 0; i < words.length; i++) {
12+
const word = words[i];
13+
if (word.length !== baseWord.length) {
14+
continue;
15+
}
16+
if (sortWord(baseWord) === sortWord(word)) {
17+
group.push(word);
18+
removeIndices.push(i);
19+
}
20+
}
21+
while (removeIndices.length) {
22+
words.splice(removeIndices.pop(), 1);
23+
}
24+
result.push(group);
25+
}
26+
return result;
27+
};
28+
29+
(() => {
30+
const words = [
31+
'eat',
32+
'ate',
33+
'tea',
34+
'monk',
35+
'konm',
36+
'nkom',
37+
'bbc',
38+
'cbb',
39+
'dell',
40+
'ledl',
41+
'llde',
42+
];
43+
console.log(findAnagrams(words));
44+
})();

0 commit comments

Comments
 (0)