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:
(define (subtract-first-half xs)
(let loop ((front xs) (back (reverse xs)) (hare xs) (out (list)))
(if (or (null? hare) (null? (cdr hare)))
(append (reverse out) front)
(loop (cdr front) (cdr back) (cddr front)
(cons (- (car front) (car back)) out)))))
> (subtract-first-half '(5 4 3 2 1))
(4 2 0 2 1)
> (subtract-first-half '(4 3 2 1))
(3 1 2 1)
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.
(define (trailing-zeros n)
(let loop ((k 5) (z 0))
(if (< n k) z
(loop (* k 5) (+ z (quotient n k))))))
> (trailing-zeros 487)
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.
You can run the program at http://programmingpraxis.codepad.org/G17lhMD3.
Pages: 1 2