0

when I submit to leetcode, it run case 500/502 but failed, reason: 1808548329. But when I run it on my own mac, it gave the same answer as the accepted one.

my code :

int trailingZeroes(int n) {
    int count = 0;
    int tmp = 0; //check every number in [1, i]
    for (int i = 1; i <= n; i++) {
        tmp = i;
        while (tmp % 5 == 0) {
            count++;
            tmp /= 5;
        }
    }
    return count;
}

and the ac answer:

int trailingZeroes2(int n) {
    return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
}

they run the same result, on my mac:

std::cout << trailingZeroes(1808548329) << std::endl; //452137076
std::cout << trailingZeroes2(1808548329) << std::endl; //452137076

Is the reason that first solution not accepted because of time complexity? (cus' i am running it on my own mac, but it gives the same answer that the ac gave)

how can i calculate the time complexity of the first solution,

is it O(NlogN) ? I am not sure. can u do me a favor? : -)


edited, remove pics.

ch-yk
  • 1
  • 2

1 Answers1

1

Your solution is O(n).

  • The inner loop repeats at least once every 5 items
  • The inner loop repeats at least twice every 25 items
  • ...
  • The inner loop repeats at least k times every 5^k items.

Summing it together gives you that the inner loop runs:

n/5 + n/25 + n/125 + ... + 1 = 
n (1/5 + 1/25 + 1/125 + ... + 1/n)

This is sum of geometric series, which is in O(n)

In addition, the outer loop itself has O(n) iterations, with each constant cost, if ignoring the inner loops, so this remains O(n).


The alternative solution, however runs in O(logn), which is significantly more efficient.

amit
  • 175,853
  • 27
  • 231
  • 333