Numbers With Same Consecutive Differences — LeetCode 967 Python Solution

MediumBreadth-First SearchBacktracking
Problem
#967
Reading time
3 min

The problem

Given two integers n and k, return an array of all the integers of length n where the difference between every two consecutive digits is k. You may return the answer in any order.

Example

Input
n = 3, k = 7
Output
[181,292,707,818,929]
Explanation
Note that 070 is not a valid number, because it has leading zeroes.

Python solution

Python
class Solution:
    def numsSameConsecDiff(self, n: int, k: int) -> List[int]:
        def dfs(x: int):
            if x >= boundary:
                ans.append(x)
                return
            last = x % 10
            if last + k <= 9:
                dfs(x * 10 + last + k)
            if last - k >= 0 and k != 0:
                dfs(x * 10 + last - k)

        ans = []
        boundary = 10 ** (n - 1)
        for i in range(1, 10):
            dfs(i)
        return ans

Complexity

MeasureComplexity
Time(n \times 2^n \times |\Sigma|), where |\Sigma| represents the set of digits, and in this problem |\Sigma| = 9
SpaceO(2^n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 967. Numbers With Same Consecutive Differences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 967. Numbers With Same Consecutive Differences?
LeetCode 967. Numbers With Same Consecutive Differences is rated Medium on LeetCode.
What is the time complexity of LeetCode 967. Numbers With Same Consecutive Differences?
The Python solution on this page runs in (n \times 2^n \times |\Sigma|), where |\Sigma| represents the set of digits, and in this problem |\Sigma| = 9.
What is the space complexity of LeetCode 967. Numbers With Same Consecutive Differences?
The Python solution on this page uses O(2^n) auxiliary space.
What topics does LeetCode 967. Numbers With Same Consecutive Differences cover?
LeetCode 967. Numbers With Same Consecutive Differences is tagged Breadth-First Search and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview