#336

Palindrome Pairs

Hard
ArrayHash TableStringTrieHash FunctionHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * k²)
Space
O(1)
O(n)
💡

Intuition

Time O(n * k²)Space O(n)

The optimal solution uses a hash map to store the words and checks for possible palindromic combinations more efficiently. This reduces unnecessary checks and leverages the properties of palindromes.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a hash map to store each word and its index.
  2. 2Step 2: For each word, check all possible prefixes and suffixes to see if they can form a palindrome when combined with another word.
  3. 3Step 3: If a valid palindrome pair is found, add it to the results.
solution.py13 lines
1def is_palindrome(s): return s == s[::-1]
2
3def palindrome_pairs(words):
4    result = []
5    word_map = {word: i for i, word in enumerate(words)}
6    for i, word in enumerate(words):
7        for j in range(len(word) + 1):
8            prefix, suffix = word[:j], word[j:]
9            if is_palindrome(suffix) and prefix[::-1] in word_map:
10                result.append([word_map[prefix[::-1]], i])
11            if j != len(word) and is_palindrome(prefix) and suffix[::-1] in word_map:
12                result.append([i, word_map[suffix[::-1]]])
13    return result

Complexity note: This complexity arises because we iterate through each word and check all its prefixes and suffixes, where k is the average length of the words.

  • 1Using a hash map allows for O(1) average time complexity lookups, significantly speeding up the process.
  • 2Recognizing the properties of palindromes helps in reducing unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.