You are given a positive integer n, that is initially placed on a board. Every day, for 109 days, you perform the following procedure:
x present on the board, find all numbers 1 <= i <= n such that x % i == 1.Return the number of distinct integers present on the board after 109 days have elapsed.
Note:
% stands for the modulo operation. For example, 14 % 3 is 2.
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 <= 100This approach works by reverse engineering the board filling process. Given a number n, we find the numbers that can potentially go on the board. These numbers are such that x % i == 1 for each previously existing number x on the board. Through observation, you'll notice that once a number is included on the board, it allows for smaller numbers to be generated. By understanding the modulo behavior, we can establish that the smallest sequence achievable sorts to n, n-1, ..., 2 after limitless days.
The C solution uses a simple function that takes n as an input and returns n-1. This solution works because the process fills out all possible numbers such that 1 <= i < n. For n=5, these are 2, 3, 4.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1)
Space Complexity: O(1)
In this approach, we simulate the process of adding numbers to the board for small values of n to identify a pattern. By listing the numbers that result from x % i == 1, it becomes evident that the upper bound determines the potential set of numbers you can derive. This results in numbers from 2 to n eventually appearing on the board over time.
This C implementation uses a simulation to justify a similar conclusion. By observing patterns from smaller simulations, it simplifies this to the return statement n - 1.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2) -- for full simulation
Effective Complexity: O(1) -- after inference
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Reverse Calculation Method | Time Complexity: O(1) |
| Simulation and Observation | Time Complexity: O(n^2) -- for full simulation |
Count Number of Teams - Leetcode 1395 - Python • NeetCodeIO • 14,668 views views
Watch 9 more video solutions →Practice Count Distinct Numbers on Board with our built-in code editor and test cases.
Practice on FleetCode