Count Earlier IDs That Are Both Prefix and Suffix of Later Ones

Last updated: November 29, 2026

Quick Overview

Given a list of strings, count pairs i < j where words[i] is simultaneously a prefix and a suffix of words[j], in time near linear in total length.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given a list of strings, count pairs i < j where words[i] is simultaneously a prefix and a suffix of words[j], in time near linear in total length.

A Google onsite follow-up to simpler prefix questions, framed as finding resource IDs that frame longer IDs. The interviewer expects the trick of keying a trie on character pairs (s[k], s[n-1-k]) so one walk checks prefix and suffix together.

What the Interviewer Expects
  • Show the quadratic pairwise check first
  • Observe that prefix and suffix of length L match exactly when the first L pairs (s[k], s[n-1-k]) match
  • Build a trie over these pairs
  • Count matches from earlier words while walking, then insert
  • Prove why the pair encoding is both necessary and sufficient
Key Topics to Cover
trie
string matching
prefix and suffix
counting
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Can you solve it with the Z-function instead?
  • How would you count pairs in either order rather than only i < j?
  • How would you list the pairs, not just count them?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: words, a list of lowercase strings (duplicates allowed). Output: the number of index pairs i < j such that words[j].startswith(words[i]) and words[j].endswith(words[i]). Total length ca...

High-Level Design

Write s = words[j] with length n. A string t of length L is both prefix and suffix of s exactly when t[k] = s[k] and t[k] = s[n-L+k] for all k < L. Encode each word as the sequence of ...


Submit Your Answer
Markdown supported