Data Structures & AlgorithmsVery hardProduct company OA

A monotonic stack removes duplicate letters so that each letter appears exactly once and the result is the lexicographically SMALLEST possible subsequence. What is the result for 'dbcabdc'?

  1. A. abdc
  2. B. abcd
  3. C. bcad
  4. D. dbca

Correct answer: A. abdc

Pop a larger letter on top only if it appears again later. d is pushed; b pops d (d reappears at 5); c is pushed → [b, c]; a pops c and b (both reappear) → [a]; then b and d are pushed → [a, b, d]; the final c cannot pop d because no d comes later → 'abdc'. 'abcd' is impossible: after the last d (index 5) only c follows, so d must come before the final c.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic