LeetCode 967: Numbers With Same Consecutive Differences Solution

Master LeetCode problem 967 (Numbers With Same Consecutive Differences), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

967. Numbers With Same Consecutive Differences

Problem Explanation

Explanation

To solve this problem, we can use a breadth-first search (BFS) approach. We start with single digit numbers (1 to 9) and then iteratively append a digit to the right of each number based on the given difference k. We continue this process until we reach the desired length n. We maintain a queue to store the current numbers being processed.

Algorithm

  1. Initialize a queue with single digit numbers from 1 to 9.
  2. While the length of the numbers in the queue is less than n, do the following:
    • Pop a number from the queue.
    • Get the last digit of the number.
    • Generate new numbers by adding/subtracting k to the last digit (if the result is between 0 and 9).
    • Append the new numbers to the queue.
  3. Return the numbers in the queue.

Time Complexity

The time complexity of this algorithm is O(2^N) where N is the given length of the numbers.

Space Complexity

The space complexity of this algorithm is O(2^N) as well, as we store the generated numbers in a queue.

Solution Code

import java.util.*;

class Solution {
    public int[] numsSameConsecDiff(int n, int k) {
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 1; i <= 9; i++) {
            queue.offer(i);
        }

        while (queue.peek().toString().length() < n) {
            int num = queue.poll();
            int lastDigit = num % 10;
            if (lastDigit + k <= 9) {
                queue.offer(num * 10 + lastDigit + k);
            }
            if (lastDigit - k >= 0 && k != 0) {
                queue.offer(num * 10 + lastDigit - k);
            }
        }

        return queue.stream().mapToInt(Integer::intValue).toArray();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 967 (Numbers With Same Consecutive Differences)?

This page provides optimized solutions for LeetCode problem 967 (Numbers With Same Consecutive Differences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 967 (Numbers With Same Consecutive Differences)?

The time complexity for LeetCode 967 (Numbers With Same Consecutive Differences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 967 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 967 in Java, C++, or Python.

Back to LeetCode Solutions