Bird
Raised Fist0
Interview Prepchallenge-problemshardGoogleAmazonAirbnb

Palindrome Pairs

Choose your preparation mode4 modes available
📋
Problem

Imagine a search engine that suggests pairs of words which, when combined, form palindromes - a fun feature for word games or linguistic puzzles.

Given a list of unique words, find all pairs of distinct indices (i, j) such that the concatenation of words[i] + words[j] is a palindrome. Return all such pairs as a list of lists.

1 ≤ n ≤ 10^5 (number of words)1 ≤ length of each word ≤ 300All words consist of lowercase English lettersWords are unique
Edge cases: Empty string present → pairs with any palindrome wordSingle character words → always palindrome pairs with themselves reversedWords that are already palindromes → can form pairs with empty string
</>
IDE
def palindromePairs(words: list[str]) -> list[list[int]]:public List<List<Integer>> palindromePairs(List<String> words)vector<vector<int>> palindromePairs(vector<string> &words)function palindromePairs(words)
def palindromePairs(words):
    # Write your solution here
    pass
class Solution {
    public List<List<Integer>> palindromePairs(List<String> words) {
        // Write your solution here
        return new ArrayList<>();
    }
}
#include <vector>
#include <string>
using namespace std;

vector<vector<int>> palindromePairs(vector<string> &words) {
    // Write your solution here
    return {};
}
function palindromePairs(words) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Missing pairs involving empty string and palindrome wordsNot handling empty string special case for palindrome pairs✅ Add explicit checks to pair empty string with all palindrome words at different indices
Wrong: Pairs with same index (e.g. [0,0]) includedNot enforcing distinct indices condition✅ Add condition to skip pairs where i == j
Wrong: Only pairs with fully reversed words found, missing partial palindrome pairsGreedy approach checking only full reversed words✅ Check palindrome prefixes and suffixes for partial matches to find all pairs
Wrong: Fails on large input due to timeoutBrute force O(n^2*k) approach used✅ Implement hash map or trie-based approach with O(n*k^2) complexity
Wrong: Misses pairs involving duplicate wordsMapping words to single index instead of all indices✅ Map words to all their indices and check all pairs
✓
Test Cases
t1_01basic
Input["abcd","dcba","lls","s","sssll"]
Expected[[0,1],[1,0],[3,2],[2,4]]

Pairs: 'abcd' + 'dcba' = 'abcddcba' palindrome, 'dcba' + 'abcd' palindrome, 's' + 'lls' palindrome, 'lls' + 'sssll' palindrome.

t1_02basic
Input["bat","tab","cat"]
Expected[[0,1],[1,0]]

'bat' + 'tab' and 'tab' + 'bat' form palindromes; 'cat' forms no palindrome pairs.

t2_01edge
Input[""]
Expected[]

Single empty string alone cannot form pairs with distinct indices.

t2_02edge
Input["a"]
Expected[]

Single character word alone cannot form pairs with distinct indices.

t2_03edge
Input["a",""]
Expected[[0,1],[1,0]]

Empty string pairs with palindrome 'a' in both orders.

t3_01corner
Input["abcd","dcba","lls","s","sssll","lls"]
Expected[[0,1],[1,0],[3,2],[2,4],[5,4]]

Detects duplicates and pairs correctly; 'lls' repeated at index 5 pairs with 'sssll' at 4.

t3_02corner
Input["a","abc","cba"]
Expected[[1,2],[2,1]]

'abc' + 'cba' and 'cba' + 'abc' form palindromes; single character 'a' does not form pairs.

t3_03corner
Input["a","aa","aaa"]
Expected[[0,1],[1,0],[0,2],[2,0],[1,2],[2,1]]

Tests confusion between 0/1 knapsack style and unbounded; all pairs of palindromic words form pairs.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

Input size n=100000 with max word length 300; brute force O(n^2*k) will TLE; efficient O(n*k^2) or trie-based needed.

Practice

(1/5)
1. You need to design a data structure that supports adding words and searching for words, where the search query may contain '.' as a wildcard matching any single character. Which algorithmic approach best guarantees efficient search and add operations for this problem?
easy
A. Use a hash set to store all words and perform linear scan with backtracking on search queries containing wildcards.
B. Use a balanced binary search tree to store words and perform prefix-based search with wildcard expansion.
C. Use a trie data structure combined with iterative DFS/backtracking to handle wildcard searches efficiently.
D. Use dynamic programming to precompute all possible wildcard matches for each word and store results for quick lookup.

Solution

  1. Step 1: Understand the problem requirements

    The data structure must support adding words and searching with '.' wildcards that match any character.
  2. Step 2: Evaluate algorithmic approaches

    A trie with iterative DFS/backtracking efficiently supports prefix and wildcard searches by exploring only relevant branches, unlike brute force or DP which are inefficient or infeasible.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Trie with backtracking handles '.' wildcard efficiently [OK]
Hint: Trie + backtracking handles wildcards efficiently [OK]
Common Mistakes:
  • Thinking brute force with backtracking is efficient enough
  • Confusing DP with trie for wildcard search
  • Assuming BST supports wildcard search efficiently
2. You need to design a data structure that efficiently supports insertion of strings, exact search for strings, and prefix-based search queries. Which of the following data structures guarantees optimal time complexity for these operations regardless of the number of stored strings?
easy
A. Hash Set storing all strings for O(1) average search but no efficient prefix search
B. Trie (Prefix Tree) that stores characters in nodes with links to children nodes
C. Sorting all strings and using binary search for prefix queries
D. Using a balanced binary search tree keyed by entire strings

Solution

  1. Step 1: Understand operation requirements

    Insertion, exact search, and prefix search must be efficient. Hash sets provide O(1) average search but cannot efficiently support prefix queries.
  2. Step 2: Compare data structures

    Tries store characters in nodes allowing O(m) time for insert/search/startsWith, where m is length of word or prefix. Binary search on sorted strings is O(m log n) and BSTs do not support prefix queries efficiently.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Trie supports prefix queries in O(m) time [OK]
Hint: Tries enable prefix queries in O(m) time [OK]
Common Mistakes:
  • Confusing hash sets as supporting prefix queries efficiently
3. You are building a feature that, given a list of product names and a search query typed character-by-character, returns up to three lexicographically smallest products starting with the current prefix after each character is typed. Which algorithmic approach best guarantees efficient retrieval of these suggestions for every prefix?
easy
A. Build a trie from the sorted product list and store up to three suggestions at each node to retrieve suggestions efficiently.
B. Use a brute force approach that filters and sorts the entire product list for each prefix typed.
C. Apply dynamic programming to precompute all possible prefix matches and their top suggestions.
D. Use a greedy algorithm that picks the first three products starting with the prefix without sorting.

Solution

  1. Step 1: Understand the problem requirements

    The problem requires returning up to three lexicographically smallest products for every prefix of the search word efficiently.
  2. Step 2: Evaluate algorithmic approaches

    Brute force filtering and sorting for each prefix is inefficient. Dynamic programming is not suitable for prefix-based retrieval. A greedy approach without sorting fails lex order requirements. Building a trie with stored top 3 suggestions at each node allows O(m) retrieval where m is prefix length.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Trie with stored suggestions matches problem constraints and efficiency [OK]
Hint: Trie with stored suggestions enables fast prefix queries [OK]
Common Mistakes:
  • Assuming brute force is efficient enough
  • Confusing DP with prefix search
  • Ignoring lexicographic order in greedy approach
4. What is the time complexity of the optimal bitwise trie approach to count pairs with XOR in a range for an input array of size n and maximum number M (max element)?
medium
A. O(n * log M)
B. O(n^2)
C. O(n * M)
D. O(n * log n)

Solution

  1. Step 1: Identify operations per element

    Each number is inserted into the trie in O(log M) time, where M is the max number (bit length).
  2. Step 2: Query per element also takes O(log M)

    For each number, querying the trie for counts less than a limit also takes O(log M).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Overall complexity is O(n * log M) due to insert and query per element [OK]
Hint: Trie operations scale with bit length, not array size squared [OK]
Common Mistakes:
  • Assuming O(n^2) due to pairs
  • Confusing M with n in complexity
  • Ignoring log factor from bit length
5. What is the time complexity of processing Q queries using the optimal StreamChecker approach that builds a trie of reversed words and maintains a stream buffer limited to the maximum word length L? Assume W words with maximum length L. Choose the most accurate complexity.
medium
A. O(Q * W * L)
B. O(Q * L^2)
C. O(Q * L)
D. O(Q + W * L)

Solution

  1. Step 1: Identify operations per query

    Each query appends a letter and traverses at most L nodes in the trie (limited by max word length).
  2. Step 2: Calculate total complexity

    Building the trie takes O(W * L) once. Each query takes O(L) time. Total is O(Q * L) for queries plus O(W * L) for setup, dominated by O(Q * L) for large Q.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Traversal limited to max word length L per query [OK]
Hint: Traversal limited to max word length L per query [OK]
Common Mistakes:
  • Confusing brute force O(Q*W*L) with trie approach
  • Assuming quadratic in L
  • Ignoring trie build cost
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard