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
Joining strings to form palindrome pairs in JavaScript
We are required to write a JavaScript function that takes in an array of strings as the only argument. The function is supposed to return an array of arrays of all the index pairs joining the strings at which yields a new palindrome string.
For example, if the input to the function is:
const arr = ['tab', 'cat', 'bat'];
Then the output should be:
[[0, 2], [2, 0]]
Output Explanation
Because both the strings 'battab' and 'tabbat' are palindromes when we join:
- arr[0] + arr[2] = 'tab' + 'bat' = 'tabbat' (palindrome)
- arr[2] + arr[0] = 'bat' + 'tab' = 'battab' (palindrome)
Helper Function: Check Palindrome
First, we need a function to check if a string is a palindrome:
const isPalindrome = (str = '') => {
let i = 0;
let j = str.length - 1;
while (i
true
true
false
Main Solution
const arr = ['tab', 'cat', 'bat'];
const isPalindrome = (str = '') => {
let i = 0;
let j = str.length - 1;
while (i {
const res = [];
for (let i = 0; i
[[0, 2], [2, 0]]
How It Works
The algorithm works in two steps:
-
Helper Function:
isPalindrome() uses two pointers to check if a string reads the same forwards and backwards
-
Main Function: Uses nested loops to try all possible pairs of strings, checking both orders (i+j and j+i) for palindrome formation
Example with Different Input
const words = ['abc', 'cba', 'def'];
console.log(palindromePairs(words));
// Check the palindromes formed
console.log('abc' + 'cba'); // abccba
console.log('cba' + 'abc'); // cbaabc
[[0, 1], [1, 0]]
abccba
cbaabc
Time Complexity
The time complexity is O(n² × m), where n is the number of strings and m is the average length of strings. This is because we check all pairs (O(n²)) and for each pair, we verify if the concatenation is a palindrome (O(m)).
Conclusion
This solution efficiently finds all index pairs that form palindromes when their corresponding strings are concatenated. The key is using a two-pointer approach for palindrome checking and testing both concatenation orders for each pair.
