

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Joining strings to form palindrome pairs in JavaScript
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 ] ]
- Related Questions & Answers
- Construct objects from joining two strings JavaScript
- Function to find out palindrome strings JavaScript
- Joining two strings with two words at a time - JavaScript
- Unique pairs in array that forms palindrome words in JavaScript
- Joining two Arrays in Javascript
- Joining two hash tables in Javascript
- Construct K Palindrome Strings in C++
- Rearrange characters to form palindrome if possible in C++
- Joining a JavaScript array with a condition?
- Nearest palindrome in JavaScript
- Palindrome numbers in JavaScript
- Palindrome array - JavaScript
- Program to split two strings to make palindrome using Python
- Joining Threads in Java
- Python program to count the pairs of reverse strings
Advertisements