336. Palindrome Pairs
Palindrome Pairs
Given a list of unique words, return all the pairs of the distinct indices (i, j)
in the given list, so that the concatenation of the two words words[i] + words[j]
is a palindrome.
Example 1:
Input: words = ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
Example 2:
Input: words = ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]
Example 3:
Input: words = ["a",""]
Output: [[0,1],[1,0]]
Constraints:
1 <= words.length <= 5000
0 <= words[i].length <= 300
words[i]
consists of lower-case English letters.
Idea:
/**
* @param {string[]} words
* @return {number[][]}
*/
var palindromePairs = function(words) {
let word_map = new Map(), ans = []
for (let i = 0; i < words.length; i++)
word_map.set(words[i], i)
for (let i = 0; i < words.length; i++) {
if (words[i] === "") {
for (let j = 0; j < words.length; j++)
if (is_Palindrome(words[j]) && j !== i)
ans.push([i, j], [j, i])
continue
}
let reverse_str = words[i].split("").reverse().join("")
let res = word_map.get(reverse_str)
if (res !== undefined && res !== i)
ans.push([i, res])
for (let j = 1; j < reverse_str.length; j++) {
if (is_Palindrome(reverse_str, 0, j - 1)) {
let res = word_map.get(reverse_str.slice(j))
if (res !== undefined)
ans.push([i, res])
}
if (is_Palindrome(reverse_str, j)) {
let res = word_map.get(reverse_str.slice(0,j))
if (res !== undefined)
ans.push([res, i])
}
}
}
return ans
};
//check if a word is palindrome
const is_Palindrome = (word, i=0, j=word.length-1) => {
while (i < j)
if (word[i++] !== word[j--]) return false
return true
}
Complexity analysis.
Time ComplexityO(N * M^2) where N is the length of words and M is the average length of the words in words
Space Complexity
We are using a map as an extra space, hence space complexity is O(N).
That’s all folks! In this post, we solved LeetCode problem #336. Palindrome Pairs
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment