3870 LeetCode problem solution
Another LeetCode problem that can be solved with just one line of code. No number can contain more than one comma. Numbers from 1 to 999 contain 0 commas, while every number from 1000 to n contains exactly 1.
So the total number of commas is simply the number of integers in the range [1000, n]:
n - 1000 + 1 = n - 999
This solution is optimal specifically because of the constraint n <= 105.
Time complexity: O(1)
Space complexity: O(1)
If you want to see how the same problem can require a different solution when the constraints change, compare LeetCode 3870 and 3871 in this post.
LeetCode 3870 C++ solution
class Solution {
public:
int countCommas(int n)
{
return max(0, n - 999);
}
};LeetCode 3870 Java solution
class Solution {
public int countCommas(int n) {
return Math.max(0, n - 999);
}
}LeetCode 3870 JavaScript solution
var countCommas = function(n) {
return Math.max(0, n - 999);
};LeetCode 3870 TypeScript solution
function countCommas(n: number): number {
return Math.max(0, n - 999);
};LeetCode 3870 Python solution
class Solution(object):
def countCommas(self, n):
return max(0, n - 999)