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 numbers with same consecutive differences in Python
Given a number N (length of digits) and K (absolute difference), we need to find all N-digit numbers where the absolute difference between every two consecutive digits equals K. Numbers cannot have leading zeros except for the single digit 0.
For example, if N = 4 and K = 7, valid numbers include 1818 (|1-8|=7, |8-1|=7, |1-8|=7) and 2929, but 0707 is invalid due to the leading zero.
Algorithm Approach
We use a breadth-first search (BFS) approach with a queue ?
If N = 1, return all single digits [0, 1, 2, ..., 9]
Initialize queue with digits 1-9 (no leading zeros)
For each level (digit position), extend numbers by adding valid next digits
Valid next digits: current_digit ± K (within 0-9 range)
Implementation
from collections import deque
def solve(N, K):
# Special case: single digit numbers
if N == 1:
return list(range(10))
# Initialize queue with 1-9 (avoid leading zeros)
queue = deque(list(range(1, 10)))
# Build N-digit numbers level by level
for level in range(N - 1):
queue_size = len(queue)
# Process all numbers at current level
for _ in range(queue_size):
current_num = queue.popleft()
last_digit = current_num % 10
# Try adding (last_digit - K) as next digit
if last_digit - K >= 0:
new_num = current_num * 10 + (last_digit - K)
queue.append(new_num)
# Try adding (last_digit + K) as next digit
# Avoid duplicates when K = 0
if K > 0 and last_digit + K <= 9:
new_num = current_num * 10 + (last_digit + K)
queue.append(new_num)
return list(queue)
# Test the function
N = 4
K = 7
result = solve(N, K)
print("N =", N, "K =", K)
print("Result:", result)
N = 4 K = 7 Result: [1818, 2929, 7070, 8181, 9292]
How It Works
Let's trace through N = 3, K = 2 ?
from collections import deque
def solve_with_trace(N, K):
if N == 1:
return list(range(10))
queue = deque(list(range(1, 10)))
print(f"Initial queue: {list(queue)}")
for level in range(N - 1):
print(f"\nLevel {level + 1}:")
queue_size = len(queue)
for _ in range(queue_size):
current_num = queue.popleft()
last_digit = current_num % 10
print(f" Processing {current_num}, last digit: {last_digit}")
# Try subtracting K
if last_digit - K >= 0:
new_num = current_num * 10 + (last_digit - K)
queue.append(new_num)
print(f" Added: {new_num}")
# Try adding K
if K > 0 and last_digit + K <= 9:
new_num = current_num * 10 + (last_digit + K)
queue.append(new_num)
print(f" Added: {new_num}")
print(f"Queue after level {level + 1}: {list(queue)}")
return list(queue)
result = solve_with_trace(3, 2)
print(f"\nFinal result: {result}")
Initial queue: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Level 1:
Processing 1, last digit: 1
Added: 13
Processing 2, last digit: 2
Added: 20
Added: 24
Processing 3, last digit: 3
Added: 31
Added: 35
Processing 4, last digit: 4
Added: 42
Added: 46
Processing 5, last digit: 5
Added: 53
Added: 57
Processing 6, last digit: 6
Added: 64
Added: 68
Processing 7, last digit: 7
Added: 75
Added: 79
Processing 8, last digit: 8
Added: 86
Processing 9, last digit: 9
Added: 97
Queue after level 1: [13, 20, 24, 31, 35, 42, 46, 53, 57, 64, 68, 75, 79, 86, 97]
Level 2:
Processing 13, last digit: 3
Added: 131
Added: 135
Processing 20, last digit: 0
Added: 202
Processing 24, last digit: 4
Added: 242
Added: 246
Processing 31, last digit: 1
Added: 313
Processing 35, last digit: 5
Added: 353
Added: 357
Processing 42, last digit: 2
Added: 420
Added: 424
Processing 46, last digit: 6
Added: 464
Added: 468
Processing 53, last digit: 3
Added: 531
Added: 535
Processing 57, last digit: 7
Added: 575
Added: 579
Processing 64, last digit: 4
Added: 642
Added: 646
Processing 68, last digit: 8
Added: 686
Processing 75, last digit: 5
Added: 753
Added: 757
Processing 79, last digit: 9
Added: 797
Processing 86, last digit: 6
Added: 864
Added: 868
Processing 97, last digit: 7
Added: 975
Added: 979
Queue after level 2: [131, 135, 202, 242, 246, 313, 353, 357, 420, 424, 464, 468, 531, 535, 575, 579, 642, 646, 686, 753, 757, 797, 864, 868, 975, 979]
Final result: [131, 135, 202, 242, 246, 313, 353, 357, 420, 424, 464, 468, 531, 535, 575, 579, 642, 646, 686, 753, 757, 797, 864, 868, 975, 979]
Key Points
Time complexity: O(2^N) in worst case when K allows many branches
Space complexity: O(2^N) for the queue storage
The condition
if K > 0prevents duplicate numbers when K = 0BFS ensures we build numbers digit by digit systematically
Conclusion
This BFS approach efficiently generates all valid N-digit numbers with consecutive digit differences of K. The algorithm handles edge cases like single digits and prevents leading zeros by initializing the queue with digits 1-9.
