Three Interview Questions

May 13, 2014

The first question (insert new node 40 in sorted linked list, given node 50) is a trick question. No, it is not possible to insert the node. You need a pointer to node 30 to perform the insertion, but there is no way to get a pointer to node 30 given only a pointer to node 50. This is a simple question to ensure the candidate understands linked lists.

The second question (subtract a linked list end to end) is tedious, but not hard. We use the tortoise-and-hare algorithm to find the middle:

Another good question; the tortoise-and-hare algorithm should be familiar to all competent programmers.

The third question (number of trailing zeros in a factorial) is easy if you know the math and impossible if you don’t. We write numbers base 10, so there are as many trailing zeros as there are factors of 10 in the factorial of n, and since 10 = 2 * 5 and there are more factors of 2 than of 5 in any factorial, the number of trailing zeros will be the number of factors of 5. To find that, for each power of 5 up n add the number of times it divides n. For instance, if n = 487, there are ⌊487/5⌋ = 97 factors of 5, ⌊487/25⌋ = 19 factors of 52, and ⌊487/125⌋ = 3 factors of 53.

I don’t like this interview question. If you know the math, or if you have studied a book of programming interview questions, it’s easy; you can write the program as fast as you can type. If you don’t know the math, you will flail about looking for a solution, getting more and more nervous as time passes. In either case, the interviewer will learn nothing about your programming skills.

@informatimago –
Your factorial algorithm was interesting – building on top of it- if we just divide n by 5 – that seems to work although I did not test for very large numbers…
factorial(4) – will have 0 zeros (4/5)
factorial(10) – will have 2 zeros (10/5)
factorial(24) – will have 4 zeros (24/5)
factorial(25) – will have 5 zeros (25/5) and so on…

For number 3, counting factors in each iteration of a factorial is asymptotically less efficient than counting representation of progressively larger powers of the factor in n. Implemented in Python the faster solution looks as follows:

Vivek is correct. For the second problem, all we have to do is divide by 5. The reasoning is that the prime factors of 10 are 2 and 5. For n!, every 5th value of n will give us a factor of 5. Every second value of n will give us a factor of 2, so we’ll have plenty of factors of 2 (i.e. in the prime factorization of n!, we’ll always have at least as many factors of 2 as we do factors of 5). So every 5th value of n!, we’ll add another 0 to the end of the number.