JSFiddle - React, Tailwind, and code Playground

by kkdaily

HTML

<p>
Given a list of strings, find all the pairs that when concatenated, form a palindrome
</p>

JavaScript

/**
- ex: ['cat', 'ac', 'dog', 'god', 'g', 'g'] --> { 'cat': 'ac', 'dog': 'god', 'g': 'g' }

- iterate through the list of strings
- starting with the first string, concatenate that with the next string
- run a palindrome check on the concatenated string
- if it's a palindrome, store the 2 strings as a key/value pair in a hash table
- increment i by 1, and compare the first string with the next string etc until the end of the list of strings
- once at the end, set the current string to the next string in the list
- iterate over the list of strings starting at the current string + 1 index

palindrome checker
- if the str length is 1 return true
- iterate over the string chars
- store each char in a hash table; increment by 1 if already present
- if the str was odd length, then return true if the hash contains exactly 1 odd value
- if the str was even length, return true if the hash contains all even values
**/

const findPalindromePairs = (stringList) => {
	if (stringList.length <= 1) {
  	return "List of strings must contain 2 or more strings"
  }
  
  const palindromePairs = []
  
  for (let currentStringIndex = 0; currentStringIndex < stringList.length; currentStringIndex++) {
  	let currentString = stringList[currentStringIndex]
    for (let stringToCompareIndex = currentStringIndex; stringToCompareIndex < stringList.length; stringToCompareIndex++) {
    	let stringToCompare = stringList[stringToCompareIndex + 1]
      if (stringToCompare !== -1) {

        if (isPalindrome(currentString + stringToCompare)) {
        	palindromePairs.push({ [currentString]: stringToCompare })
        }
        
        if (isPalindrome(stringToCompare + currentString)) {
					palindromePairs.push({ [stringToCompare]: currentString })
        }
      }
    }
  }
  
  return palindromePairs
}

const isPalindrome = (str) => {
	if (str.length === 1) {
  	return true
  }
  
  const seenChars = {}
  const chars = str.split('')
  
  chars.forEach((char) => {
  	if (seenChars[char])...