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

0

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
Monotonic stack
Greedy
Strings
Hash set
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
  • 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 Problems
Sample 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...


Submit Your Answer
Markdown supported