Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to find number not greater than n where all digits are non-decreasing in python
Given a number n, we need to find the largest number smaller or equal to n where all digits are in non-decreasing order (each digit is greater than or equal to the previous digit).
For example, if the input is n = 221, the output will be 199 because 199 has digits in non-decreasing order (1 ? 9 ? 9) and is the largest such number ? 221.
Algorithm
The approach works by scanning digits from right to left and fixing any decreasing sequences ?
- Convert the number into a list of digits
- Scan from right to left to find decreasing digit pairs
- When a decreasing pair is found, reduce the left digit by 1
- Set all digits to the right of the violation to 9
- Convert back to number and return
Example
class Solution:
def solve(self, n):
digits = [int(x) for x in str(n)]
bound = None
for i in range(len(digits) - 1, 0, -1):
if digits[i] < digits[i - 1]:
bound = i
digits[i - 1] -= 1
if bound:
for i in range(bound, len(digits)):
digits[i] = 9
return int("".join(map(str, digits)))
# Test the solution
ob = Solution()
n = 221
result = ob.solve(n)
print(f"Input: {n}")
print(f"Output: {result}")
Input: 221 Output: 199
How It Works
Let's trace through the example with n = 221 ?
def solve_with_trace(n):
digits = [int(x) for x in str(n)]
print(f"Initial digits: {digits}")
bound = None
for i in range(len(digits) - 1, 0, -1):
print(f"Comparing digits[{i}] = {digits[i]} with digits[{i-1}] = {digits[i-1]}")
if digits[i] < digits[i - 1]:
bound = i
digits[i - 1] -= 1
print(f"Found decreasing pair! Bound set to {bound}, reduced digits[{i-1}] to {digits[i-1]}")
if bound:
for j in range(bound, len(digits)):
digits[j] = 9
print(f"Set all digits from position {bound} onwards to 9: {digits}")
return int("".join(map(str, digits)))
result = solve_with_trace(221)
print(f"Final result: {result}")
Initial digits: [2, 2, 1] Comparing digits[2] = 1 with digits[1] = 2 Found decreasing pair! Bound set to 2, reduced digits[1] to 1 Set all digits from position 2 onwards to 9: [2, 1, 9] Comparing digits[1] = 1 with digits[0] = 2 Found decreasing pair! Bound set to 1, reduced digits[0] to 1 Set all digits from position 1 onwards to 9: [1, 9, 9] Final result: 199
Additional Examples
ob = Solution()
test_cases = [123, 321, 111, 987, 1000]
for num in test_cases:
result = ob.solve(num)
print(f"n = {num} ? {result}")
n = 123 ? 123 n = 321 ? 299 n = 111 ? 111 n = 987 ? 899 n = 1000 ? 999
Conclusion
This algorithm efficiently finds the largest non-decreasing number ? n by scanning right-to-left and fixing violations. When a decreasing pair is found, we reduce the left digit and maximize all following digits with 9s.
Advertisements
