Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty).
Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty).
def remove_k(num, k):
st = []
for d in num:
while k and st and st[-1] > d:
st.pop(); k -= 1
st.append(d)
st = st[:len(st) - k]
return ''.join(st).lstrip('0') or '0'
print(remove_k("1432219", 3), remove_k("10200", 1), remove_k("12345", 2))What is printed?- A. 1219 0200 123
- B. 1219 200 123
- C. 1229 200 345
- D. 1219 200 345
Correct answer: B. 1219 200 123
Greedy monotonic stack: drop a digit whenever a smaller digit follows it. "1432219" → 1219. "10200" → drop 1 → "0200" → strip zeros → 200. For increasing "12345" nothing is popped, so the leftover k removes digits from the end: 123. O(n).
More Coding Interview Problems questions
- Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs. python st = [] def push(x): st.append((x…
- Problem: Return the first index whose value is ≥ x in a sorted array (n if none). cpp int lowerBound(vector<int>& a, int x) { int lo = 0…
- Problem: Count how many times a value occurs in a sorted array in O(log n). python from bisect import bisectleft, bisectright a = [2, 4…
- Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot. python def search(a, t): lo, hi =…
- Problem: Find the minimum of a rotated sorted array of distinct values. python def findmin(a): lo, hi = 0, len(a) - 1 while lo < hi: mid =…
- Problem: Packages with weights w (in order) must ship within D days; each day the ship carries a contiguous prefix of the remaining…