Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Unique pairs in array that forms palindrome words in JavaScript
We are required to write a JavaScript function that takes in an array of unique words.
Our function should return an array of all such index pairs, the words at which, when combined yield a palindrome word.
Problem
Given an array of unique words, find all pairs of indices where concatenating the words at those indices creates a palindrome. A palindrome reads the same forwards and backwards, like "racecar" or "abccba".
Example
Following is the code:
const arr = ["abcd", "dcba", "lls", "s", "sssll"];
const findPairs = (arr = []) => {
const res = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i !== j) {
let k = `${arr[i]}${arr[j]}`;
let l = [...k].reverse().join('');
if (k === l)
res.push([i, j]);
}
}
}
return res;
};
console.log(findPairs(arr));
Output
[ [ 0, 1 ], [ 1, 0 ], [ 2, 4 ], [ 3, 2 ] ]
How It Works
The algorithm uses nested loops to check every possible pair combination:
// Example walkthrough with arr = ["abcd", "dcba", "lls", "s", "sssll"]
// Checking pair [0, 1]: "abcd" + "dcba" = "abcddcba"
let combined = "abcddcba";
let reversed = "abcddcba"; // Same when reversed - it's a palindrome!
// Checking pair [2, 4]: "lls" + "sssll" = "llssssll"
let combined2 = "llssssll";
let reversed2 = "llssssll"; // Also a palindrome!
console.log("abcddcba" === "abcddcba"); // true
console.log("llssssll" === "llssssll"); // true
true true
Optimized Version
Here's a more readable version with helper function:
const findPalindromePairs = (words) => {
const isPalindrome = (str) => {
return str === str.split('').reverse().join('');
};
const result = [];
for (let i = 0; i < words.length; i++) {
for (let j = 0; j < words.length; j++) {
if (i !== j) {
const combined = words[i] + words[j];
if (isPalindrome(combined)) {
result.push([i, j]);
}
}
}
}
return result;
};
const testArray = ["race", "car", "abc", "cba"];
console.log(findPalindromePairs(testArray));
[ [ 0, 1 ], [ 2, 3 ], [ 3, 2 ] ]
Key Points
- Time Complexity: O(n² × m) where n is array length and m is average word length
- Space Complexity: O(k) where k is the number of palindrome pairs found
- The algorithm checks all possible pairs, excluding self-pairing (i ? j)
- Each combined string is compared with its reverse to detect palindromes
Conclusion
This solution efficiently finds all index pairs that form palindromes when concatenated. The nested loop approach ensures all combinations are checked, making it suitable for small to medium-sized arrays.
