LeetCode 793: Preimage Size of Factorial Zeroes Function Solution
Master LeetCode problem 793 (Preimage Size of Factorial Zeroes Function), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
793. Preimage Size of Factorial Zeroes Function
Problem Explanation
Explanation:
To solve this problem, we need to find the number of non-negative integers x such that the factorial of x has k trailing zeroes. We can observe that the number of trailing zeroes in x! will increase whenever x is a multiple of 5, as each multiple of 5 introduces one trailing zero. Moreover, multiples of 25 introduce an additional trailing zero, multiples of 125 introduce two additional trailing zeroes, and so on.
Based on this observation, we can use binary search to find the range of values for x that satisfy f(x) = k. We can then calculate the number of values within this range.
Algorithm:
- Define a function
trailingZeroesto count the number of trailing zeroes in a number. - Implement a binary search algorithm to find the lower and upper bounds for x such that f(x) = k.
- Calculate the number of values within this range.
- Return the count as the result.
Time Complexity:
The time complexity of this algorithm is O(log(k)).
Space Complexity:
The space complexity is O(1). :
Solution Code
class Solution {
public int preimageSizeFZF(int k) {
return (int)(binarySearch(k) - binarySearch(k - 1));
}
private long binarySearch(int k) {
long low = 0, high = 5L * (long)k;
while (low <= high) {
long mid = low + (high - low) / 2;
int zeros = trailingZeroes(mid);
if (zeros == k) return mid;
else if (zeros < k) low = mid + 1;
else high = mid - 1;
}
return -1;
}
private int trailingZeroes(long num) {
int count = 0;
while (num > 0) {
count += num / 5;
num /= 5;
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 793 (Preimage Size of Factorial Zeroes Function)?
This page provides optimized solutions for LeetCode problem 793 (Preimage Size of Factorial Zeroes Function) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 793 (Preimage Size of Factorial Zeroes Function)?
The time complexity for LeetCode 793 (Preimage Size of Factorial Zeroes Function) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 793 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 793 in Java, C++, or Python.