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 are given a list of envelopes, each with a width and height. You want to find the maximum number of envelopes you can nest inside each other such that each envelope fits strictly inside the next one by both width and height. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Greedy approach by sorting envelopes by width and picking the tallest envelope at each step.
B. Sort envelopes by width ascending and height descending, then find the Longest Increasing Subsequence (LIS) on heights using binary search.
C. Dynamic programming with a 2D table tracking all pairs of envelopes to find the longest chain.
D. Use a graph and find the longest path by topological sorting.

Solution

  1. Step 1: Understand problem constraints

    The problem requires strict increasing order in both width and height for nesting envelopes.
  2. Step 2: Identify optimal approach

    Sorting by width ascending and height descending ensures envelopes with the same width do not interfere. Then LIS on heights finds the longest chain efficiently.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Sorting + LIS with binary search is the known optimal approach [OK]
Hint: Sort width asc, height desc, then LIS on heights [OK]
Common Mistakes:
  • Using greedy picking tallest envelope only
  • Applying LIS on widths instead of heights
  • Using DP without sorting properly
2. Given the following Python code snippet implementing the merge step of the skyline problem, and the input skylines left = [[1, 3], [5, 0]] and right = [[2, 4], [6, 0]], what is the value of the variable merged after the while loop completes (before extending remaining points)?
easy
A. [[1, 3], [2, 4], [5, 0], [6, 0]]
B. [[1, 3], [2, 4]]
C. [[1, 3], [2, 4], [5, 0]]
D. [[1, 3], [2, 4], [5, 0], [6, 0], [7, 0]]

Solution

  1. Step 1: Trace first iteration

    left[0] = [1,3], right[0] = [2,4]. Since 1 < 2, x=1, h1=3, h2=0, maxH=3 -> merged = [[1,3]]
  2. Step 2: Trace second iteration

    left[1] = [5,0], right[0] = [2,4]. Since 2 < 5, x=2, h2=4, h1=3 (from previous), maxH=4 -> merged = [[1,3],[2,4]]
  3. Step 3: Trace third iteration

    left[1] = [5,0], right[1] = [6,0]. Since 5 < 6, x=5, h1=0, h2=4 (previous), maxH=4 -> merged = [[1,3],[2,4],[5,0]]
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Correctly merged points before extending remaining [OK]
Hint: Trace pointer increments carefully to avoid off-by-one errors [OK]
Common Mistakes:
  • Forgetting to update h1 or h2 correctly
  • Appending points with same height consecutively
  • Misaligning indices causing skipped points
3. Consider the following buggy code snippet for the optimal median of two sorted arrays. Which line contains the subtle bug that can cause incorrect median calculation or runtime error?
medium
A. Line 10: max_left_nums1 = float('-inf') if i == 0 else nums1[i - 1]
B. Line 7: i = (low + high) // 2
C. Line 17: elif max_left_nums1 > min_right_nums2:
D. Line 2: if len(nums1) < len(nums2): nums1, nums2 = nums2, nums1

Solution

  1. Step 1: Check array swap condition

    The code swaps arrays only if len(nums1) < len(nums2), which is incorrect. It should swap if nums1 is larger to ensure binary search on smaller array.
  2. Step 2: Consequences of wrong swap

    Without correct swap, binary search range can be large, causing inefficiency or index errors.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Swap condition reversed causes subtle bugs [OK]
Hint: Swap arrays so binary search is on smaller one [OK]
Common Mistakes:
  • Swapping arrays incorrectly or not at all
  • Off-by-one errors in partition indices
  • Incorrect median calculation for odd/even lengths
4. What is the time complexity of the optimal two-pointer approach for finding the smallest range covering k lists, where n is the total number of elements across all lists and k is the number of lists?
medium
A. O(n * k) due to scanning each element for each list
B. O(n^2) since the two-pointer window can move over all pairs
C. O(n) as the two-pointer technique scans the merged array once
D. O(n log n) because of sorting the merged array of all elements

Solution

  1. Step 1: Identify main operations

    Merging all elements takes O(n), sorting merged array takes O(n log n).
  2. Step 2: Analyze two-pointer sliding window

    Two pointers scan merged array linearly, O(n) time.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Sorting dominates, so total time is O(n log n) [OK]
Hint: Sorting merged array dominates time complexity [OK]
Common Mistakes:
  • Assuming two-pointer is O(n^2)
  • Ignoring sorting cost
  • Confusing k factor in complexity
5. Consider the following buggy implementation of the two-pointer approach for trapping rain water. Which line contains the subtle bug that can cause incorrect trapped water calculation?
medium
A. Line 7: if height[left] < height[right]:
B. Line 15: if height[right] >= right_max:
C. Line 17: water += right_max - height[right]
D. Line 9: if height[left] > left_max:

Solution

  1. Step 1: Compare condition for updating left_max

    The original buggy code used '>' instead of '>=' which causes left_max not to update when height[left] equals left_max.
  2. Step 2: Effect of bug

    When height[left] == left_max, water is incorrectly added (left_max - height[left] = 0), which is harmless but logically incorrect and can cause issues in some cases.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Using '>=' ensures correct max update and prevents unnecessary water addition [OK]
Hint: Use '>=' when updating max heights to avoid underestimation [OK]
Common Mistakes:
  • Using '>' instead of '>=' for max updates
  • Incorrect pointer movement
  • Adding water without checking max heights
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