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.

1 variation · 1 problem

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

Digit-by-Digit Construction
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
}

The variations

  1. 1Each digit follows from the last

    Start with each first digit from 1 to 9. The next digit can only be last + k or last − k, so the tree has at most two branches per level and every leaf is an answer.

Mistakes to avoid

  • With k = 0, last + k and last - k are the same digit: trying both adds every number twice.
  • Starting from 0 and producing numbers with a leading zero.
Next: Meet in the middle: two half-sized searches →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.