Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trie

Palindrome Pairs

Hard · Trie · Asked at Google, Airbnb, Amazon

Given a list of distinct words, count the ordered pairs (i, j) with i ≠ j such that words[i] + words[j] (concatenation) is a palindrome.

Input

First line: n. Next n lines: one word each.

Output

The number of palindrome pairs.

Constraints

Put every word, reversed, in a hash map (or trie). For each word w and each split w = left + right: if right is a palindrome and reverse(left) is another word, that word goes after w; if left is a palindrome and reverse(right) is another word, it goes before w. Skip one of the two cases for the empty split so pairs are not counted twice.

Example 1

Input

5
abcd
dcba
lls
s
sssll

Output

4

Example 2

Input

2
bat
tab

Output

2

Hints

  1. Checking all n² pairs costs O(n² · L).
  2. Split each word w into left + right at every position.
  3. If right is a palindrome, any word equal to reverse(left) can follow w; if left is a palindrome, any word equal to reverse(right) can precede w.

Approach

Map every word to its index. For each word w and every split point j = 0 … |w|: let left = w[0..j) and right = w[j..). If right is a palindrome and reverse(left) is a different word, then w + that word is a palindrome — count it. If j > 0, left is a palindrome and reverse(right) is a different word, then that word + w is a palindrome — count it. The j > 0 condition prevents counting the same pair twice when both splits are the full/empty string. This is O(n · L²).

Complexity: O(n · L²) time · O(n · L) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

bool isPal(const string &s, int a, int b) { // s[a..b)
    for (int i = a, j = b - 1; i < j; i++, j--)
        if (s[i] != s[j]) return false;
    return true;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<string> w(n);
    unordered_map<string, int> idx;
    for (int i = 0; i < n; i++) {
        cin >> w[i];
        idx[w[i]] = i;
    }
    long long count = 0;
    for (int i = 0; i < n; i++) {
        const string &s = w[i];
        int L = s.size();
        for (int j = 0; j <= L; j++) {
            if (isPal(s, j, L)) {
                string rl(s.rend() - j, s.rend());
                auto it = idx.find(rl);
                if (it != idx.end() && it->second != i) count++;
            }
            if (j > 0 && isPal(s, 0, j)) {
                string rr(s.rbegin(), s.rend() - j);
                auto it = idx.find(rr);
                if (it != idx.end() && it->second != i) count++;
            }
        }
    }
    cout << count << "\n";
    return 0;
}

Python solution

import sys

data = sys.stdin.read().split()
n = int(data[0])
words = data[1 : 1 + n]
idx = {w: i for i, w in enumerate(words)}
count = 0
for i, w in enumerate(words):
    L = len(w)
    for j in range(L + 1):
        left, right = w[:j], w[j:]
        if right == right[::-1]:
            k = idx.get(left[::-1])
            if k is not None and k != i:
                count += 1
        if j > 0 and left == left[::-1]:
            k = idx.get(right[::-1])
            if k is not None and k != i:
                count += 1
print(count)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    static boolean isPal(String s, int a, int b) {
        for (int i = a, j = b - 1; i < j; i++, j--)
            if (s.charAt(i) != s.charAt(j)) return false;
        return true;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine().trim());
        String[] w = new String[n];
        HashMap<String, Integer> idx = new HashMap<>();
        for (int i = 0; i < n; i++) {
            w[i] = br.readLine().trim();
            idx.put(w[i], i);
        }
        long count = 0;
        for (int i = 0; i < n; i++) {
            String s = w[i];
            int L = s.length();
            for (int j = 0; j <= L; j++) {
                if (isPal(s, j, L)) {
                    Integer k = idx.get(new StringBuilder(s.substring(0, j)).reverse().toString());
                    if (k != null && k != i) count++;
                }
                if (j > 0 && isPal(s, 0, j)) {
                    Integer k = idx.get(new StringBuilder(s.substring(j)).reverse().toString());
                    if (k != null && k != i) count++;
                }
            }
        }
        System.out.println(count);
    }
}

Solve Palindrome Pairs online · All practice problems