Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the largest number ≤ n whose digits are non-decreasing from left to right.
Problem: Return the largest number ≤ n whose digits are non-decreasing from left to right.
def mono(n):
d = list(str(n)); mark = len(d)
for i in range(len(d) - 1, 0, -1):
if d[i - 1] > d[i]:
d[i - 1] = str(int(d[i - 1]) - 1); mark = i
for i in range(mark, len(d)): d[i] = "9"
return int("".join(d))
print(mono(4321), mono(1332), mono(120), mono(5555))What is printed?- A. 3333 1299 119 5555
- B. 3999 1329 119 5555
- C. 3999 1299 119 5555
- D. 3999 1299 99 5555
Correct answer: C. 3999 1299 119 5555
Scan from the right; at each descent decrement the left digit and remember the position, then turn everything after the leftmost such position into 9s. 1332: the 3 > 2 descent makes 1322… then the earlier 3 > 2 makes 1222…, mark = 2 → 1299 (stopping after one fix would give 1329, which is not monotone). 120 → 119; 4321 → 3999. O(d).
More Coding Interview Problems questions
- Problem: A string has '(', ')' and '', where '' may act as '(', ')' or nothing. Is it balanceable? Track the range [lo, hi] of possible…
- Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most ops operations, minimise the largest bag…
- Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move. python moves = [] def hanoi(n, a, b, c): if n ==…
- Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by…
- Problem: Generate all distinct subsets of a multiset of coupon values (skip equal values at the same recursion depth). python def…
- Problem: Produce the 3-bit Gray code sequence (consecutive codes differ in exactly one bit) with the formula g = i XOR (i >> 1). python…