Return the Latest Post Tag Matching Both a Prefix and a Suffix
Last updated: November 29, 2026
Quick Overview
Given a list of post tags in upload order, build a structure whose query(prefix, suffix) returns the largest index of a tag that starts with prefix and ends with suffix, or -1 if no tag matches.
Meta
November 29, 20260
0
0 solved
Given a list of post tags in upload order, build a structure whose query(prefix, suffix) returns the largest index of a tag that starts with prefix and ends with suffix, or -1 if no tag matches.
Instagram's tag tooling needs to filter by both ends of a tag, and this question checks whether you can turn a two-sided constraint into a single trie lookup. Interviewers look for the suffix-plus-separator trick and an honest discussion of the memory it costs.
What the Interviewer Expects
- Explain why two separate tries require an expensive intersection
- Insert suffix + '{' + word for every suffix of every word
- Store the latest index at each node so queries are a single walk
- Quantify memory as O(n * k^2)
- Mention the hash-map-of-pairs alternative for short tags
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 support many more queries than tags efficiently?
- What if tags are long (hundreds of characters)?
- How would you return all matching indices, newest first?
- How would you handle tag deletions?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Tags are lowercase, length up to about 10; up to ~10^4 tags; many queries.
query(prefix, suffix)returns the largest matching index; either string may be empty.- Queries should be fast, and...
High-Level Design
For each tag w at index i, and for each suffix s of w (including the empty one), insert the string s + '{' + w into one trie. Every node on that path stores i; because indices increase, la...