
Problem
Solution
Submissions
Palindrome Pairs
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program to find all pairs of distinct indices i and j in an array of words such that the concatenation of words[i] + words[j] forms a palindrome.
Example 1
- Input: words = ["bat", "tab", "cat"]
- Output: [[0,1], [1,0]]
- Explanation:
- The palindrome pairs are:
- - "bat" + "tab" = "battab", which is a palindrome
- - "tab" + "bat" = "tabbat", which is a palindrome
Example 2
- Input: words = ["abcd", "dcba", "lls", "s", "sssll"]
- Output: [[0,1], [1,0], [2,4], [3,2]]
- Explanation:
- The palindrome pairs are:
- - "abcd" + "dcba" = "abcddcba", which is a palindrome
- - "dcba" + "abcd" = "dcbaabcd", which is a palindrome
- - "lls" + "sssll" = "llssssll", which is a palindrome
- - "s" + "lls" = "slls", which is a palindrome
Constraints
- 1 ≤ words.length ≤ 5000
- 0 ≤ words[i].length ≤ 300
- words[i] consists of lowercase English letters
- Time Complexity: O(n * k²) where n is the number of words and k is the maximum length of a word
- 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 hash map to store words and their indices for quick lookup
- For each word, check if its reverse exists in the array
- Also check if any prefix or suffix of the word forms a palindrome
- Be careful to exclude the word from pairing with itself
- Pay attention to empty strings, which can form palindromes with any palindromic word