Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Life Span

Question:

Let S be a stack of size n >= 1. Starting with the empty stack, suppose we push the first n natural numbers in sequence, and then perform n pop operations.

Assume that Push and Pop operation take X seconds each, and Y seconds elapse between the end of one such stack operation and the start of the next operation.

For m >= 1, define the stack-life of m as the time elapsed from the end of Push(m) to the start of the pop operation that removes m from S. The average stack-life of an element of this stack is

(A) n(X+ Y)
(B) 3Y + 2X
(C) n(X + Y)-X
(D) Y + 2X

Question taken from this Link

My Approach:

For n elements Push takes X time, hence for m elements Push takes m/n*X    
For n elements Pop takes X time, hence for m elements Push takes m/n*X    
Interval Time is m/n*Y
Stack Life = End of Push(m) to start of Pop(m) = Interval Time = m/n*Y
Average Stack Life = (m/n*Y) / m = Y/n

None of the answers are matching. Please guide me the correct way to achieve my objective.

like image 222
user3409814 Avatar asked Jun 28 '14 08:06

user3409814


2 Answers

Here is my approach:

Stack lifetime of nth element -> Y
For (n-1)th -> 2X+2Y + stack lifetime of nth element = 2X + 3Y
For (n-2)th -> 2X+2Y + stack lifetime of (n-1)th element = 4X + 5Y
..
..
For 1st -> 2(n-1)X + (2n-1)Y

Sum of all life spans= (Σ 2(n-1)X) + (Σ (2n-1)Y) for n = 1 to n

Calculate sum by the above summation from 1 to n, You will get:

Sum = n(n(X+Y)-X)
Therefore Average = Sum/n = n(X+Y)-X .  Hence Option (c)

This question has been asked here : http://geeksquiz.com/data-structures-stack-question-7/

like image 171
Ayush Avatar answered Nov 24 '22 19:11

Ayush


Here is mine: 
PUSH Operations:
1. After Push(m) i.e., from Push(m+1) till Push(n) --> there are (n-m) Push operations(ops) => (n-m)X ops

2. After Push(m) to the Push(m+1) --> there is one Y ops ==> till Push(n) ==> (n-m)Y ops

--> Time taken to finish Push(n) after Push(m) ==> (n-m)(X+Y)

POP Operations:
1. After Push(n) to the Pop(n) --> there is one Y ops ==> till Pop(m) ==> (n-m+1)Y ops (this is one extra Y after Pop(m+1) and reach Pop(m))

2. From Push(n) till Push(m+1) --> there are (n-m) Push operations(ops) => (n-m)X ops

--> Time taken to finish Pop(m+1) from Push(n) ==> (n-m)(X+Y)+Y

Overall Time for any arbitrary m, T(m) ==> 2(n-m)(X+Y) + Y

To obtain the average: Sum(T(m)), for all m: 1->n
==> Sum{ 2(n-m)(X+Y) + Y } over m: 1->n
==> 2(X+Y){(n-1) + (n-2) + .... + 0 }+ (Y + Y ... n-times)
==> 2(n(n-1)/2)(X+Y) + nY = n(n-1)(X+Y) + nY
Average: Above sum / n
==> (n-1)(X+Y) + Y = n(X+Y)-X
like image 44
Raj Avatar answered Nov 24 '22 21:11

Raj