Recursion & Backtracking · Pattern 8 of 9
Digit-by-digit construction
Build each number one digit at a time, where the next digit depends on the last one. You only ever create valid numbers, instead of scanning every number in the range.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Every number of length n that follows a digit rule
- The rule links each digit to the one before it
- The range is huge, but valid numbers are few
The template
int[] numsSameConsecDiff(int n, int k) {
List<Integer> out = new ArrayList<>();
for (int d = 1; d <= 9; d++) build(d, 1, n, k, out); // no leading zero
return out.stream().mapToInt(Integer::intValue).toArray();
}
void build(int num, int len, int n, int k, List<Integer> out) {
if (len == n) { out.add(num); return; }
int last = num % 10;
if (last + k <= 9) build(num * 10 + last + k, len + 1, n, k, out);
if (k > 0 && last - k >= 0) build(num * 10 + last - k, len + 1, n, k, out); // k = 0: one branch
} def nums_same_consec_diff(n, k):
out = []
def build(num, length):
if length == n:
out.append(num)
return
last = num % 10
for nxt in {last + k, last - k}: # a set: k = 0 gives one branch
if 0 <= nxt <= 9:
build(num * 10 + nxt, length + 1)
for d in range(1, 10): # no leading zero
build(d, 1)
return out void build(int num, int len, int n, int k, vector<int>& out) {
if (len == n) { out.push_back(num); return; }
int last = num % 10;
if (last + k <= 9) build(num * 10 + last + k, len + 1, n, k, out);
if (k > 0 && last - k >= 0) build(num * 10 + last - k, len + 1, n, k, out); // k = 0: one branch
}
vector<int> numsSameConsecDiff(int n, int k) {
vector<int> out;
for (int d = 1; d <= 9; d++) build(d, 1, n, k, out); // no leading zero
return out;
} function numsSameConsecDiff(n, k) {
const out = [];
function build(num, len) {
if (len === n) { out.push(num); return; }
const last = num % 10;
if (last + k <= 9) build(num * 10 + last + k, len + 1);
if (k > 0 && last - k >= 0) build(num * 10 + last - k, len + 1); // k = 0: one branch
}
for (let d = 1; d <= 9; d++) build(d, 1); // no leading zero
return out;
} The variations
-
1Each digit follows from the last
Start with each first digit from 1 to 9. The next digit can only be
last + korlast − k, so the tree has at most two branches per level and every leaf is an answer.
Mistakes to avoid
- With
k = 0,last + kandlast - kare the same digit: trying both adds every number twice. - Starting from 0 and producing numbers with a leading zero.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.