Data Structures & AlgorithmsHardProduct Company SDE · greedy stack
Problem: Remove exactly 3 digits from the number '1432219' to make the smallest possible number, keeping the remaining digits in order. Use the monotone-stack code below. What is printed?
Problem: Remove exactly 3 digits from the number '1432219' to make the smallest possible number, keeping the remaining digits in order. Use the monotone-stack code below. What is printed?
def rm(num, k):
st = []
for c in num:
while k and st and st[-1] > c:
st.pop()
k -= 1
st.append(c)
st = st[:len(st) - k] if k else st
return ''.join(st).lstrip('0') or '0'
print(rm('1432219', 3))- A. 1229
- B. 1432
- C. 1291
- D. 1219
Correct answer: D. 1219
The stack removes 4, 3 and then 2 when a smaller digit arrives, leaving 1 2 1 9 after the last removal. Forgetting to strip leading zeros is the other classic slip.
More Coding Interview Problems questions
- Problem: What is the length of the longest palindromic subsequence of 'bbbab'? python def lps(s): n = len(s) dp = [[0] n for in range(n)]…
- Problem: Multiply a chain of matrices with dimensions p = [10, 30, 5, 60] (matrix i is p[i] by p[i+1]). Find the minimum number of scalar…
- Problem: How many ways can 10 be formed as an ordered-free sum of coins 1, 2 and 5 (each coin may be used any number of times, and order…
- Problem: What is the diameter (in edges) of the tree with edges 1-2, 2-3, 2-4, 4-5, 5-6? Use the double BFS code. python from collections…
- Problem: A robot starts at (0, 0) facing north (+y). Commands: F moves one step forward, B one step backward (facing unchanged), L turns…
- Problem: What is the KMP prefix-function array pi for the string 'ababaca'? python s = 'ababaca' pi = [0] len(s) for i in range(1…