LeetCode 2549: Count Distinct Numbers on Board Solution

Master LeetCode problem 2549 (Count Distinct Numbers on Board), a easy 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.

2549. Count Distinct Numbers on Board

Problem Explanation

Explanation

To solve this problem, we can simulate the process for 109 days. We start with the number n on the board and iterate through each number already present on the board. For each number x, we check all numbers from 1 to n and if x % i == 1, we add i to a set representing the numbers to be added to the board. After processing all numbers on the board, we add all the numbers from the set to the board. We repeat this process for 109 days and return the count of distinct numbers on the board.

Time Complexity: O(n^2) where n is the input positive integer n. Space Complexity: O(n) to store the numbers on the board.

Solution Code

import java.util.HashSet;
import java.util.Set;

class Solution {
    public int countDistinctNumbers(int n) {
        Set<Integer> board = new HashSet<>();
        board.add(n);

        for (int day = 0; day < 1e9; day++) {
            Set<Integer> newNumbers = new HashSet<>();
            for (int num : board) {
                for (int i = 1; i <= n; i++) {
                    if (num % i == 1) {
                        newNumbers.add(i);
                    }
                }
            }
            board.addAll(newNumbers);
        }

        return board.size();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2549 (Count Distinct Numbers on Board)?

This page provides optimized solutions for LeetCode problem 2549 (Count Distinct Numbers on Board) 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 2549 (Count Distinct Numbers on Board)?

The time complexity for LeetCode 2549 (Count Distinct Numbers on Board) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2549 on DevExCode?

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

Back to LeetCode Solutions