forked from adamespii/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem_167.js
35 lines (29 loc) Β· 994 Bytes
/
problem_167.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
// prettier-ignore
/**
* Find all pairs of unique indices such that they are palindromes
* Time Complexity: O(n^2)
* Auxiliary Space: O(n)
* @param {string[]} list
* @return {number[]}
*/
function uniquePalindromes(list) {
// base case
if (list.length <= 1) return [];
const indicies = [];
const regex = /[\W_]/g; // regex
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < list.length; j++) {
if (i !== j) {
// check combined ordering
const combined = list[i] + list[j];
const left = combined.toLowerCase().replace(regex, '');
const right = left.split('').reverse().join('');
// check if forward and backward spelling are same
if (left === right) indicies.push([i, j]);
}
}
}
return indicies;
}
console.log(uniquePalindromes(['code', 'edoc', 'da', 'd'])); // [ [ 0, 1 ], [ 1, 0 ], [ 2, 3 ] ]
console.log(uniquePalindromes(['race', 'car', 'pa', 'ap'])); // [ [ 0, 1 ], [ 2, 3 ], [ 3, 2 ] ]