-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations.js
More file actions
68 lines (60 loc) · 1.51 KB
/
permutations.js
File metadata and controls
68 lines (60 loc) · 1.51 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// O(n*n!) time | O(n*n!) space
function getPermutations(array) {
const permutations = [];
permutationsHelper(0, array, permutations);
return permutations;
}
function permutationsHelper(i, array, permutations) {
if (i === array.length - 1) {
permutations.push(array.slice());
} else {
for (let j = i; j < array.length; j++) {
swap(i, j, array);
permutationsHelper(i + 1, array, permutations);
swap(i, j, array);
}
}
}
function swap(i, j, array) {
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
//
// Time O(n!)
// Space O(n!)
// This solution works well with strings with duplicated chars
//
function getPermutations(string) {
const freq = buildFreqTable(string);
const result = [];
getPermsHelper(freq, "", string.length, result);
return result;
}
function getPermsHelper(freq, prefix, remaining, result) {
// Base case, permutation has been complited
if (remaining === 0) {
result.push(prefix);
return;
}
// Try remaining letters for next char, and generate remaining permutations
for (const [char, count] of Object.entries(freq)) {
if (count > 0) {
freq[char] -= 1;
getPermsHelper(freq, prefix + char, remaining - 1, result);
freq[char] = count;
}
}
}
function buildFreqTable(string) {
const hashTable = {};
for (const char of string) {
if (hashTable.hasOwnProperty(char)) {
hashTable[char] += 1;
} else {
hashTable[char] = 1;
}
}
return hashTable;
}
console.log(getPermutations("ab"));