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?- A. abcd abc xyz
- B. dcba bca zyx
- C. adcb acb yzx
- 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
- Problem: A game board has scores a[0..n−1]; from cell i you may jump forward 1..k cells. Starting at 0 and ending at n − 1, maximise the…
- Problem: A council of two parties, R and D, votes in rounds in seat order. On their turn a member bans the next opposing member who has…
- Problem: People stand in a line facing right with distinct heights. Person i can see person j > i if everyone strictly between them is…
- Problem: An employee's day is 'tiring' if they worked more than 8 hours. Find the longest run of consecutive days in which tiring days…
- Problem: A sorted list of ticket prices is searched with Python's bisect module. python from bisect import bisectleft, bisectright a =…
- Problem: Orders (name, priority) are sorted by priority only, using Python's sorted with a key. python orders = [("ravi", 3), ("asha", 1)…