Stacks & Queues


Answer & solution
Answer: C (no official key was published)
1. LIFO means m is removed after the n−m elements above it. Between the two specified endpoints lie n−m later pushes and n−m earlier pops, a total of 2(n−m) complete operations.
2. There is one more gap than intervening operations, so life(m)=2(n−m)X+[2(n−m)+1]Y. The push of m and its own pop are excluded by the endpoint definition.
3. Average n−m over m=1,...,n: [0+...+(n−1)]/n=(n−1)/2. Substitution gives (n−1)X+nY=n(X+Y)−X.
4. Hence C. For n=1, life is just Y, confirming the endpoint accounting.
Solution: For item m, there are n−m later pushes and n−m earlier pops between the end of push(m) and the start of its pop. Those 2(n−m) complete intervening operations cost 2(n−m)X and the 2(n−m)+1 gaps cost [2(n−m)+1]Y. Average n−m over m=1,…,n is (n−1)/2, so the mean is (n−1)X+nY=n(X+Y)−X, option C. For n=1 it correctly reduces to the single gap Y.