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?
  1. A. 3333 1299 119 5555
  2. B. 3999 1329 119 5555
  3. C. 3999 1299 119 5555
  4. 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

Exams that ask this topic