#967

Numbers With Same Consecutive Differences

Medium
BacktrackingBreadth-First SearchBacktrackingDepth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use a backtracking approach to build valid numbers directly, avoiding the generation of invalid combinations. This is more efficient as it only constructs valid numbers.

⚙️

Algorithm

3 steps
  1. 1Step 1: Start with each digit from 1 to 9 as the first digit.
  2. 2Step 2: Recursively add digits that differ from the last digit by k.
  3. 3Step 3: Stop when the number reaches the desired length n.
solution.py16 lines
1# Full working Python code
2
3def numsSameConsecDiff(n, k):
4    results = []
5    def backtrack(num, length):
6        if length == n:
7            results.append(num)
8            return
9        last_digit = num % 10
10        if last_digit + k < 10:
11            backtrack(num * 10 + (last_digit + k), length + 1)
12        if last_digit - k >= 0:
13            backtrack(num * 10 + (last_digit - k), length + 1)
14    for i in range(1, 10):
15        backtrack(i, 1)
16    return results

Complexity note: The time complexity is O(n) since we only build valid numbers directly without generating invalid combinations.

  • 1The first digit cannot be zero to avoid leading zeros.
  • 2The difference between consecutive digits must equal k.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.