Joining strings to form palindrome pairs in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

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 −

const output = [[0, 2], [2, 0]];

Output Explanation:

Because both the strings ‘battab’ and ‘tabbat’ are palindromes.

Example

The code for this will be −

const arr = ['tab', 'cat', 'bat'];
const isPalindrome = (str = '') => {
   let i = 0;
   let j = str.length - 1;
   while (i < j) {
      if (str[i] != str[j]) return false;
      i++;
      j--;
   };
   return true;
};
const palindromePairs = (arr = []) => {
   const res = [];
   for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
         if (isPalindrome(arr[i] + arr[j])) {
            res.push([i, j])
         }
         if (isPalindrome(arr[j] + arr[i])) {
            res.push([j, i])
         };
      };
   };
   return res;
};
console.log(palindromePairs(arr));

Code Explanation

We have here used a helper function isPalindome() to check whether a string is palindrome or not and our main function uses all combinations to generate all possible pairs and the ones the match our conditions, their index is pushed in the res array.

Output

And the output in the console will be −

[ [ 0, 2 ], [ 2, 0 ] ]
raja
Published on 19-Mar-2021 06:01:04
Advertisements