N Cars On A One-Way Highway
Quote:
(Another interview question)
You have N cars that are all traveling the same direction on an infinitely long one-lane highway. Unfortunately, they are all going different speeds, and cannot pass each other. Eventually the cars will clump up in one or more traffic jams.
In terms of N, what is the expected number of clumps of cars?
Solution (1):
***Please see Solution (2) below as a separate post. It is much simpler and faster!***
It is understood that although the word "jam" is used in the statement of the problem, the cars never come to a stop. What happens is that when a faster-moving car reaches a slower-moving car, then both cars move at the speed of the slower-moving car. Note that the actual speed of the cars is immaterial to the solution; what matters is that given any two distinct cars, one of them moves slower than the other.
We translate the above problem to an equivalent one as follows:
Let X(1), X(2), ...,X(N) be a sequence of random variables over the set {1,2,...,N}, with X(i) different form X(j) if i is different from j. Here X(i) represents the speed of car i, and the set {1,2,...,N} represents the speeds of the cars. We can suppose that the cars, represented by C(1),C(2),...,C(N), are in the order given and move in the East-West (Left To Right) direction. So, if X(N)=1, then there will be exactly one clump, all moving at the speed X(N)=1 of car C(N). If X(N-1)=1, then there will be exactly two clumps, one of which is the right-most car C(N) -- a single-car clump -- having speed greater than 1. The other clump, consisting of (N-1) cars, will be moving behind the car C(N) at the speed X(N-1)=1.
For any k in {1,2,...,N}, the probability P{X(k)=1}=(1/N). If X(k)=1, then all the cars C(1) through C(k) will form a clump and will be moving at the speed X(k)=1. Looking at the cars C(k+1) through C(N), we see that their speeds are all different and any of them can have any of the speeds with equal probability. So, it makes no difference what we assume to be the actual speeds of these cars, what matters is that they be different. So, we may just as well assume the speeds for the cars C(k+1) through C(N) to be {1,2,...,(N-k)}. Also we can rename these cars as A(1),...,A(N-k), so that A(i)=C(k+i) for i in {1,2,...,(N-k)}.
Now let E(N) denote the expected number of clumps of N cars.
It is obvious that E(0)=0.
If X(k)=1, then we get 1 clump consisting of the first k cars (i.e., C(1),...,C(k)). Depending on the value of k, we get on average E(N-k) clumps for the remaining (N-k) cars that are moving ahead of the first k cars.
So,
E(N) = 1 + SUM{(P{X(k)=1})*E(N-k); [k,1,N]}.
Simplifying, we get:
E(N) = 1 + SUM{(1/N)*E(N-k); [k,1,N]},
or
E(N) = 1 + (1/N)*SUM{E(k); [k,1,(N-1)]}.
We can easily show that E(N)=(1/N)+E(N-1), with E(0)=0.
From which we get the Harmonic series E(N)=(1)+(1/2)+(1/3)+...+(1/N).