KatInterview

336. Palindrome Pairs

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation

The problem asks us to find all pairs of indices (i, j) from a list of unique words such that the concatenation words[i] + words[j] forms a palindrome. A brute-force approach of checking every pair would be O(N^2 * K), where N is the number of words and K is the maximum word length, which is too slow given the constraints.

Solution

Palindrome Pairs in Python

class Solution:
    def palindromePairs(self, words: List[str]) -> List[List[int]]:
        word_map = {word: i for i, word in enumerate(words)}
        result = set()

        for i, word in enumerate(words):
            n = len(word)
            for j in range(n + 1):
                prefix = word[:j]
                suffix = word[j:]

                # Case 1: prefix is a palindrome, check for reversed suffix
                # This forms `reversed_suffix + word`
                if prefix == prefix[::-1]:
                    reversed_suffix = suffix[::-1]
                    if reversed_suffix in word_map and word_map[reversed_suffix] != i:
                        result.add((word_map[reversed_suffix], i))

                # Case 2: suffix is a palindrome, check for reversed prefix
                # This forms `word + reversed_prefix`
                # j != n is an optimization: when j=n, suffix is "". The prefix is the whole word.
                # We check for word's reverse. This will be covered when we process the other word.
                # e.g., for ("abc", "cba"), this finds ("abc", "cba") pair from "abc".
                # The symmetric pair is found from "cba". This avoids finding the first pair again.
                if j != n and suffix == suffix[::-1]:
                    reversed_prefix = prefix[::-1]
                    if reversed_prefix in word_map and word_map[reversed_prefix] != i:
                        result.add((i, word_map[reversed_prefix]))

        return [list(p) for p in result]

Palindrome Pairs in Java

class Solution {
    public List<List<Integer>> palindromePairs(String[] words) {
        Map<String, Integer> wordMap = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            wordMap.put(words[i], i);
        }

        Set<List<Integer>> result = new HashSet<>();

        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            int n = word.length();

            for (int j = 0; j <= n; j++) {
                String prefix = word.substring(0, j);
                String suffix = word.substring(j);

                // Case 1: prefix is a palindrome, find the reverse of the suffix.
                if (isPalindrome(prefix)) {
                    String reversedSuffix = new StringBuilder(suffix).reverse().toString();
                    if (wordMap.containsKey(reversedSuffix) && wordMap.get(reversedSuffix) != i) {
                        result.add(Arrays.asList(wordMap.get(reversedSuffix), i));
                    }
                }

                // Case 2: suffix is a palindrome, find the reverse of the prefix.
                // The j != n check is an optimization. When j=n, the suffix is empty (a palindrome).
                // We would then look for the reverse of the entire word. This pair will be found
                // when we process the other word in the pair. E.g., for ("abc", "cba"), this finds
                // ("abc", "cba") when processing "abc". The symmetric pair ("cba", "abc") is found
                // when processing "cba". The optimization avoids finding the first pair again here.
                if (j != n && isPalindrome(suffix)) {
                    String reversedPrefix = new StringBuilder(prefix).reverse().toString();
                    if (wordMap.containsKey(reversedPrefix) && wordMap.get(reversedPrefix) != i) {
                        result.add(Arrays.asList(i, wordMap.get(reversedPrefix)));
                    }
                }
            }
        }
        return new ArrayList<>(result);
    }

    private boolean isPalindrome(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left++) != s.charAt(right--)) {
                return false;
            }
        }
        return true;
    }
}

Palindrome Pairs in C++

class Solution {
public:
    vector<vector<int>> palindromePairs(vector<string>& words) {
        unordered_map<string, int> word_map;
        for (int i = 0; i < words.size(); ++i) {
            word_map[words[i]] = i;
        }

        set<vector<int>> result_set;

        for (int i = 0; i < words.size(); ++i) {
            string word = words[i];
            int n = word.length();

            for (int j = 0; j <= n; ++j) {
                string prefix = word.substr(0, j);
                string suffix = word.substr(j);

                // Case 1: prefix is a palindrome, check for reversed suffix
                if (isPalindrome(prefix)) {
                    string reversed_suffix = suffix;
                    reverse(reversed_suffix.begin(), reversed_suffix.end());
                    if (word_map.count(reversed_suffix) && word_map[reversed_suffix] != i) {
                        result_set.insert({word_map[reversed_suffix], i});
                    }
                }

                // Case 2: suffix is a palindrome, check for reversed prefix
                // j != n optimization: if j=n, suffix is empty, which is a palindrome.
                // We would check for reversed_prefix = reversed(word). This case will be
                // handled when we process the reversed_word itself. For example, if we have
                // "abc" and "cba", this check for "abc" would find "cba". The symmetric
                // case would be found when processing "cba", finding "abc". To avoid this
                // redundancy, we can skip the j=n check for suffix.
                if (j != n && isPalindrome(suffix)) {
                    string reversed_prefix = prefix;
                    reverse(reversed_prefix.begin(), reversed_prefix.end());
                    if (word_map.count(reversed_prefix) && word_map[reversed_prefix] != i) {
                        result_set.insert({i, word_map[reversed_prefix]});
                    }
                }
            }
        }

        return vector<vector<int>>(result_set.begin(), result_set.end());
    }

private:
    bool isPalindrome(const string& s) {
        int left = 0, right = s.length() - 1;
        while (left < right) {
            if (s[left++] != s[right--]) {
                return false;
            }
        }
        return true;
    }
};

Palindrome Pairs in TypeScript

function palindromePairs(words: string[]): number[][] {
    const wordMap: Map<string, number> = new Map();
    for (let i = 0; i < words.length; i++) {
        wordMap.set(words[i], i);
    }

    const resultSet: Set<string> = new Set();

    for (let i = 0; i < words.length; i++) {
        const word = words[i];
        const n = word.length;

        for (let j = 0; j <= n; j++) {
            const prefix = word.substring(0, j);
            const suffix = word.substring(j);

            // Case 1: prefix is a palindrome, find the reverse of the suffix.
            if (isPalindrome(prefix)) {
                const reversedSuffix = suffix.split('').reverse().join('');
                if (wordMap.has(reversedSuffix) && wordMap.get(reversedSuffix)! !== i) {
                    const pair = [wordMap.get(reversedSuffix)!, i];
                    resultSet.add(JSON.stringify(pair));
                }
            }

            // Case 2: suffix is a palindrome, find the reverse of the prefix.
            // The j !== n check is an optimization to avoid redundant checks.
            if (j !== n && isPalindrome(suffix)) {
                const reversedPrefix = prefix.split('').reverse().join('');
                if (wordMap.has(reversedPrefix) && wordMap.get(reversedPrefix)! !== i) {
                    const pair = [i, wordMap.get(reversedPrefix)!];
                    resultSet.add(JSON.stringify(pair));
                }
            }
        }
    }

    return Array.from(resultSet).map(s => JSON.parse(s));
}

function isPalindrome(s: string): boolean {
    let left = 0;
    let right = s.length - 1;
    while (left < right) {
        if (s[left++] !== s[right--]) {
            return false;
        }
    }
    return true;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.