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
Program to find all contiguously increasing numbers in start end range in Python
Suppose we have two numbers start and end, we have to find a sorted list of integers such that every number e in range [start, end] both inclusive and the digits of e are contiguously increasing. An example of continuously increasing number is 5678, but 169 is not.
So, if the input is like start = 10 end = 150, then the output will be [12, 23, 34, 45, 56, 67, 78, 89, 123]
Algorithm
To solve this, we will follow these steps ?
- s := all 9 digits as a string "123456789"
- a := a new list
- for i in range 0 to 8, do
- for j in range i + 1 to 9, do
- x := (substring of s from index i to j-1) as number
- if start <= x <= end, then
- insert x into results
- for j in range i + 1 to 9, do
- sort the results and return
Example
Let us see the following implementation to get better understanding ?
def solve(start, end):
s = "123456789"
results = []
for i in range(9):
for j in range(i + 1, 10):
x = int(s[i:j])
if start <= x <= end:
results.append(x)
return sorted(results)
start = 10
end = 150
print(solve(start, end))
The output of the above code is ?
[12, 23, 34, 45, 56, 67, 78, 89, 123]
How It Works
The algorithm generates all possible contiguous substrings from "123456789". For each substring, it converts to an integer and checks if it falls within the given range. The nested loops ensure we get all consecutive digit combinations like 12, 123, 1234, 23, 234, etc.
Alternative Approach
Here's another approach that directly generates contiguous increasing numbers ?
def find_contiguous_numbers(start, end):
results = []
# Generate all possible contiguous increasing numbers
for first_digit in range(1, 10): # Start from 1 to 9
num_str = str(first_digit)
current_num = first_digit
# Keep adding next consecutive digits
for next_digit in range(first_digit + 1, 10):
num_str += str(next_digit)
current_num = int(num_str)
if start <= current_num <= end:
results.append(current_num)
elif current_num > end:
break # No need to continue if we exceed the range
return sorted(results)
start = 10
end = 150
print(find_contiguous_numbers(start, end))
The output of the above code is ?
[12, 23, 34, 45, 56, 67, 78, 89, 123]
Conclusion
Both approaches generate all possible contiguously increasing numbers within a given range. The first method uses string slicing while the second builds numbers digit by digit, both achieving O(1) time complexity since there are only a fixed number of such sequences possible (maximum 36 combinations).
