• Difficulty: Medium
  • Patterns:

Problem Definition

Given an array of strings, find the number of pairs of strings s and t such that either s ends with t or t ends with s or s equals t. I.e., find the number of pairs of words where one is a suffix of the other.


Examples

Some test cases to verify our solution.

assert(suffix_pairs(["door", "backdoor", "back", "outback", "out", "outdoor", "backout"]) == 4) # the pairs [("door", "backdoor"), ("door", "outdoor") ("back", "outback"), ("out", "backout")]
assert(suffix_pairs(["something"]) == 0)
assert(suffix_pairs(["thing", "something", "some"]) == 1) # the pair ("thing", "something")

Brute Force Solution

def suffix_pairs(words: list[str]) -> int:
    count = 0
    n = len(words)
    for i in range(n):
        for j in range(i + 1, n):
            if words[i].endswith(words[j]) or words[j].endswith(words[i]):
                count += 1
    return count

Brute Force Solution Complexity

Let $n =$ len(words) and $k =$ max(len(w) for w in words).

Comparing every pair of strings takes $\binom{n}{2} = O(n^2)$ comparisons. In each comparison, endswith() compares up to $k$ characters. Therefore, the runtime complexity is $O(n^2 \cdot k)$.

Auxiliary space complexity is $O(1)$ since only scalar counters are maintained.


Length-Sorted Trie Solution

A string s is a suffix of t if and only if the reverse of s is a prefix of the reverse of t. This allows us to reframe the problem into prefix matching using a trie on the reversed words.

If we sort the words by ascending length, any potential suffix of a word w will be shorter than (or equal in length to) w, meaning it will always be inserted into the trie before w. We insert each word from back to front into the trie, using a dictionary for $O(1)$ child lookups. Whenever our traversal encounters a node where a previously inserted shorter word terminated, we increment our suffix counter.

class TrieNode:
    def __init__(self):
        self.children = {}
        self.terminal = 0

def suffix_pairs(words: list[str]) -> int:
    root = TrieNode()
    # Sort by length so shorter candidates are inserted before longer words
    sorted_words = sorted(words, key=len)
    count = 0
    for word in sorted_words:
        curr = root
        for i in range(len(word) - 1, -1, -1):
            c = word[i]
            if c not in curr.children:
                curr.children[c] = TrieNode()
            curr = curr.children[c]
            count += curr.terminal
        curr.terminal += 1
    return count

Length-Sorted Trie Complexity

Let $n =$ len(words) and $k =$ max(len(w) for w in words).

Sorting the $n$ words by length takes $O(n \log n)$ time. Inserting each word into the trie takes $O(k)$ time using dictionary lookups, giving $O(n \cdot k)$ across all words. The total runtime complexity is $O(n \log n + n \cdot k)$.

Auxiliary space complexity is $O(n \cdot k)$ to store the trie nodes and the sorted array.


Optimal Single-Pass Trie Solution

We can eliminate the $O(n \log n)$ sorting step entirely and process the words in a single, online pass.

When processing words in arbitrary order, a suffix pair $(s, t)$ can occur in two orientations relative to arrival order:

  1. The shorter word was inserted before the longer word (the longer word visits a node where a shorter word already terminated).
  2. The longer word was inserted before the shorter word (the shorter word terminates at a node that a longer word already passed through).

We can track both cases simultaneously by maintaining two counters on each node:

  • terminal_count: The number of words that terminate at this node.
  • pass_count: The number of words whose paths visit or pass through this node.

For each word, as we traverse its reversed characters:

  • At intermediate characters (i > 0), any previously inserted word that terminated at this node is a proper suffix of the current word, so we add curr.terminal_count to our total.
  • At the final character (i == 0), any previously inserted word that passed through this node contains the current word as a suffix, so we add curr.pass_count to our total.
  • We increment curr.pass_count at every visited node, and increment curr.terminal_count at the final node.
class TrieNode:
    def __init__(self):
        self.children = {}
        self.terminal_count = 0
        self.pass_count = 0

def suffix_pairs(words: list[str]) -> int:
    root = TrieNode()
    total_pairs = 0
    for word in words:
        curr = root
        for i in range(len(word) - 1, -1, -1):
            c = word[i]
            if c not in curr.children:
                curr.children[c] = TrieNode()
            curr = curr.children[c]
            if i > 0:
                total_pairs += curr.terminal_count
            else:
                total_pairs += curr.pass_count
            curr.pass_count += 1
        curr.terminal_count += 1
    return total_pairs

Optimal Solution Complexity

Let $N = \sum_{w \in words} |w| \le n \cdot k$ be the total number of characters across all words.

Runtime complexity is $O(N)$ (or $O(n \cdot k)$), which is strictly linear in the input size. Each character is processed in $O(1)$ time with no sorting required.

Auxiliary space complexity is $O(N)$ (or $O(n \cdot k)$) to store the trie nodes.