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?- A. adcb
- B. abcd
- C. dcba
- 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
- Problem: Report the running median of a stream using a max-heap (lower half) and a min-heap (upper half). python import heapq def…
- Which statement about selecting the k-th smallest of n unsorted numbers is correct?
- Problem: Find the smallest divisor d such that Σ ceil(a[i] / d) ≤ threshold. python def smallestdiv(a, t): lo, hi = 1, max(a) while lo <…
- Problem: Buses i take time[i] minutes per trip and run independently and repeatedly. Find the minimum time for all buses together to…
- Problem: Use bisect to count how many readings lie in the closed range [2, 7]. python from bisect import bisectleft, bisectright a = [1…
- Problem: Vertical order traversal: group nodes by column (left child c − 1, right child c + 1); inside a column sort by row, then by…