-
Notifications
You must be signed in to change notification settings - Fork 321
Expand file tree
/
Copy pathq02.js
More file actions
28 lines (24 loc) · 755 Bytes
/
q02.js
File metadata and controls
28 lines (24 loc) · 755 Bytes
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
//10.2 Group Anagrams: Write a method to sort an array of strings so that all the anagrams are next to each other.
export function groupAnagrams(A) {
let buckets = [];
for (let i = 0, len = A.length; i < len; i++) {
const elementSorted = sortLetters(A[i]);
const bucket = buckets.find((element) => {
return elementSorted === element.sortedWord;
});
if (bucket) {
bucket.elements.push(A[i]);
}
else {
buckets.push({ sortedWord: elementSorted, elements: [A[i]] });
}
}
let result = [];
for (let i = 0, len = buckets.length; i < len; i++) {
result = result.concat(buckets[i].elements);
}
return result;
}
function sortLetters(word) {
return word.toLowerCase().split('').sort().join('');
}