Count Category Path Pairs Where One Is Both Prefix and Suffix
Last updated: November 29, 2026
Quick Overview
Given a list of category path strings, count index pairs i < j such that `paths[i]` is both a prefix and a suffix of `paths[j]`. The list can hold up to 10^5 strings with total length up to 5 x 10^5.
Amazon
November 29, 20260
0
0 solved
Given a list of category path strings, count index pairs i < j such that `paths[i]` is both a prefix and a suffix of `paths[j]`. The list can hold up to 10^5 strings with total length up to 5 x 10^5.
A hard online assessment style question in Amazon's style. The brute force is obvious, and what is being tested is whether you can encode two simultaneous conditions into a single trie walk by keying edges on character pairs.
What the Interviewer Expects
- States the O(n^2 L) brute force and why it fails at this scale
- Builds a trie keyed by the pair (s[k], s[n-1-k])
- Processes strings in index order, querying before inserting
- Accumulates counts at terminal nodes along the walk
- Verifies against brute force on small random inputs
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you count pairs where one string is only a prefix (not a suffix)?
- Can you solve it with the Z-function instead of a pair trie?
- How would you return the pairs themselves, and what is the output-size concern?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Count ordered pairs with paths[i] a prefix and a suffix of paths[j]. A string counts as its own prefix and suffix, so identical strings at form a pair....
High-Level Design
Let have length and length . The two conditions are and for all . So define the key sequence of a string as the pairs $(x[k], x[|x|-...