1
\$\begingroup\$

The task

Given a list of words, find all pairs of unique indices such that the concatenation of the two words is a palindrome.

For example, given the list ["code", "edoc", "da", "d"], return [(0, 1), (1, 0), (2, 3)].

const lst = ["code", "edoc", "da", "d"];

My functional solution

const findPalindromePairs = lst => {
  const isPalindrome = str => str === [...str].reverse().join("");
  return lst.reduce((pairs, w1, i) => {
    return [...pairs, ...lst.reduce((match, w2, j) => {
      if (i !== j && isPalindrome(`${w1}${w2}`)) { match.push([i,j]); }
      return match;
    }, [])];
  }, []);
};

console.log(findPalindromePairs(lst));

My imperative solution

function findPalindromePairs2 (lst) {
  const len = lst.length;
  const pairs = [];

  const isPalindrome = str => str === [...str].reverse().join("");
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len; j++) {
      if (i !== j && isPalindrome(lst[i] + lst[j])) { pairs.push([i,j]); }
    }
  }
  return pairs;
}

console.log(findPalindromePairs2(lst));
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.