Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Remove duplicate letters so that each letter appears once and the result is the lexicographically smallest possible subsequence.

Problem: Remove duplicate letters so that each letter appears once and the result is the lexicographically smallest possible subsequence.
def smallest(s):
    last = {c: i for i, c in enumerate(s)}
    st, used = [], set()
    for i, c in enumerate(s):
        if c in used: continue
        while st and c < st[-1] and last[st[-1]] > i:
            used.remove(st.pop())
        st.append(c); used.add(c)
    return "".join(st)
print(smallest("dcbadcb"))
What is printed?
  1. A. adcb
  2. B. abcd
  3. C. dcba
  4. D. acdb

Correct answer: A. adcb

d, c and b are each popped because they occur again later, leaving 'a' at index 3. Then d (index 4) is pushed; c at 5 cannot pop d because d never occurs again, so we get 'adc', and b at 6 cannot pop c either: 'adcb'. 'abcd' is smaller but is not a subsequence that keeps all letters.

More Coding Interview Problems questions

Exams that ask this topic