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
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

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
trie
prefix and suffix search
string encoding
precomputation
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 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 Problems
Sample 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...


Submit Your Answer
Markdown supported