LeetCode 2549: Count Distinct Numbers on Board
Problem Description
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.
Solutions
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();
}
}
Loading editor...