Unique pairs in array that forms palindrome words in JavaScript



Problem

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.

Example

Following is the code −

 Live Demo

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 ] ]
Updated on: 2021-04-19T11:18:04+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements