Count Distinct Numbers on Board Problem
#2549
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2549.
You are given a positive integer n, that is initially placed on a board. Every day, for 10^9 days, you perform the following procedure:
- For each number
xpresent on the board, find all numbers1 <= i <= nsuch thatx % i == 1. - Then, place those numbers on the board.
Return the number of distinct integers present on the board after 10^9 days have elapsed.
Note:
- Once a number is placed on the board, it will remain on it until the end.
%stands for the modulo operation. For example,14 % 3is2.
Example 1:
Input: n = 5
Output: 4
Explanation: Initially, 5 is present on the board.
The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1.
After that day, 3 will be added to the board because 4 % 3 == 1.
At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5.
Example 2:
Input: n = 3
Output: 2
Explanation:
Since 3 % 2 == 1, 2 will be added to the board.
After a billion days, the only two distinct numbers on the board are 2 and 3.
Constraints:
1 <= n <= 100
Solution
Approach: Observation
For n >= 3, n % (n - 1) == 1, so on the first day n - 1 joins n. The same step applies to n - 1, then n - 2, and so on, so the board ends up with every number from 2 to n, which is n - 1 numbers.
The case n = 1 is special: nothing can be added and the board holds just 1, so the answer is max(1, n - 1).
Complexity: O(1) time and O(1) space.
class Solution:
def distinctIntegers(self, n: int) -> int:
return max(1, n - 1)