Leetcode 2549. Count Distinct Numbers on Board
A number n
is printed on a board. Every second, n
is replaced by a number on the board plus the count of distinct numbers already appearing on the board. Return the number shown on the board after it stops changing.
n
?
n
?
n
when it stops changing.n
?
n
≤ 10^9).n
, thus the time complexity will depend on how fast n
reaches a stable state.n
increments.#include <iostream>
#include <unordered_set>
int countDistinctNumbersOnBoard(int n) {
std::unordered_set<int> distinctNumbers;
int previous = -1;
// Loop until the number stops changing
while (true) {
distinctNumbers.insert(n); // Add current number to set
int newNumber = n + distinctNumbers.size(); // Compute new number
if (newNumber == n) {
// If number stops changing, exit loop
break;
}
n = newNumber; // Update current number
}
return n; // Return stable number on board
}
int main() {
int n;
std::cin >> n; // Read initial number
std::cout << countDistinctNumbersOnBoard(n) << std::endl; // Output result
return 0;
}
This code takes an initial value n
and applies the described transformation until the number stops changing, which happens when adding the count of unique numbers doesn’t alter the current value. The final stable value is then returned.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?