Data Structures & AlgorithmsVery hardProduct company OA
A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros dropped). What is printed?
A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros dropped). What is printed?
def smallest(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(smallest("4205173", 3), smallest("10200", 1), smallest("123456", 2))- A. 205 0200 3456
- B. 173 200 3456
- C. 173 200 1234
- D. 0173 200 1234
Correct answer: C. 173 200 1234
Greedy with a non-decreasing stack: whenever an earlier digit is larger than the next one, removing it lowers the most significant possible position. 4205173, k = 3: drop 4 (2 < 4), drop 2 (0 < 2), keep 0, 5, then drop 5 for 1 → 0173 → 173. 10200, k = 1: drop 1 → 0200 → 200. In an increasing string nothing is popped, so the leftover deletions come off the END → 1234 (dropping from the front gives 3456). O(n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign…
- Longest subarray with sum exactly 5 when the array contains NEGATIVE numbers: a shrink-when-too-big sliding window versus a prefix-sum map…
- Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?…
- A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed? python def…
- Packages must ship in order, one contiguous group per day; binary search on the daily capacity finds the smallest capacity that finishes…
- Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed? python from collections…