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
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Online Assessment
Coding & Algorithms
Hard

0

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
tries
string hashing alternatives
prefix and suffix
counting pairs
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
  • 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 Problems
Sample Answer
Requirements

Count ordered pairs i<ji < j with paths[i] a prefix and a suffix of paths[j]. A string counts as its own prefix and suffix, so identical strings at i<ji < j form a pair....

High-Level Design

Let pp have length mm and ss length n≥mn \ge m. The two conditions are p[k]=s[k]p[k] = s[k] and p[m−1−k]=s[n−1−k]p[m-1-k] = s[n-1-k] for all k<mk < m. So define the key sequence of a string xx as the pairs $(x[k], x[|x|-...


Submit Your Answer
Markdown supported