Smallest Hashtag Using Each Distinct Letter Exactly Once
Last updated: November 29, 2026
Quick Overview
Given a lowercase string, remove duplicate letters so every distinct letter appears exactly once, and return the lexicographically smallest result that is still a subsequence of the input.
Meta
November 29, 20260
0
0 solved
Given a lowercase string, remove duplicate letters so every distinct letter appears exactly once, and return the lexicographically smallest result that is still a subsequence of the input.
Seen in Meta onsites as a harder greedy-plus-stack problem, framed as canonicalizing auto-generated hashtag strings. The interviewer is looking for the 'can I drop this letter because it appears again later' insight and a correct visited set.
What the Interviewer Expects
- Precompute the last index of every letter
- Maintain an increasing stack with a membership set
- Pop a larger top only if it appears again later
- Skip letters already in the stack
- Explain correctness with an exchange argument
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
- What if the alphabet is all of Unicode?
- Return the lexicographically largest such subsequence instead.
- Each letter must appear exactly twice in the output: how does the condition change?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: string s of lowercase letters, length up to 10^4. Output: a subsequence of s containing each distinct letter of s exactly once, minimal in lexicographic order. Every output has the same l...
High-Level Design
Record last[c], the final index of each letter. Scan left to right with a stack holding the answer built so far and a set in_stack. If the current letter is already placed, skip it: placing it lat...