
Problem
Solution
Submissions
Palindrome Pairs
Certification: Advanced Level
Accuracy: 33.33%
Submissions: 3
Points: 15
Write a Java program to find all pairs of distinct indices i and j in the given list of words where the concatenation of the two words, i.e., 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: Step 1: words[0] + words[1] = "abcd" + "dcba" = "abcddcba" is a palindrome. Step 2: words[1] + words[0] = "dcba" + "abcd" = "dcbaabcd" is a palindrome. Step 3: words[3] + words[2] = "s" + "lls" = "slls" is a palindrome. Step 4: words[2] + words[4] = "lls" + "sssll" = "llssssll" is a palindrome.
Example 2
- Input: words = ["bat", "tab", "cat"]
- Output: [[0, 1], [1, 0]]
- Explanation: Step 1: words[0] + words[1] = "bat" + "tab" = "battab" is a palindrome. Step 2: words[1] + words[0] = "tab" + "bat" = "tabbat" is a palindrome. Step 3: words[0] + words[2] = "bat" + "cat" = "batcat" is not a palindrome. Step 4: words[2] + words[0] = "cat" + "bat" = "catbat" is not a palindrome.
Constraints
- 1 <= words.length <= 5000
- 0 <= words[i].length <= 300
- words[i] consists of lowercase English letters.
- All entries in words are distinct.
- Time Complexity: O(n * k²) where n is the number of words and k is the average length of words
- Space Complexity: O(n * k)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a trie data structure to efficiently search for palindrome pairs.
- For each word, check if its reverse exists in the list.
- Handle empty strings as special cases.
- Consider partial matches where only part of the word needs to be palindromic.
- Preprocess the list to efficiently look up words.