Data Structures & AlgorithmsVery hardProduct company OA

Problem: Delete repeated letters so each letter appears once, and among all such results return the lexicographically smallest (a subsequence of the input).

Problem: Delete repeated letters so each letter appears once, and among all such results return the lexicographically smallest (a subsequence of the input).
def smallest_unique(s):
    last = {c: i for i, c in enumerate(s)}
    st, seen = [], set()
    for i, c in enumerate(s):
        if c in seen: continue
        while st and st[-1] > c and last[st[-1]] > i:
            seen.discard(st.pop())
        st.append(c); seen.add(c)
    return "".join(st)
print(smallest_unique("dcbadcb"), smallest_unique("bcaacb"), smallest_unique("zyzx"))
What is printed?
  1. A. abcd abc xyz
  2. B. dcba bca zyx
  3. C. adcb acb yzx
  4. D. adcb abc yzx

Correct answer: C. adcb acb yzx

Monotonic stack: pop a larger letter on top if it occurs again later (it can be re-added), then push the current letter if not already used. "dcbadcb": d, c, b are all popped by 'a' (each reappears later), then d, c, b follow → "adcb". "bcaacb": "abc" is impossible because no 'c' follows the last 'b', so "acb". "zyzx": 'y' pops the first 'z' (z reappears), then z is pushed again and 'x' cannot pop it (no z after index 2) → "yzx". Sorting the distinct letters ignores the subsequence constraint. O(n).

More Coding Interview Problems questions

Exams that ask this topic