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
Stack Life Cycle answer?
Hello @Faizan-Ali-1395131367301898,
Let Tn be a time span of the nth element of the stack. Let us first find out the sum of Tn for n = 1 to n
Stack Lifetime of last element, Tn = Y (Since it is popped as soon
as it is pushed on the stack)
Stack Lifetime of last element, Tn-1 = Tn + 2X + 2Y
(The time needed to push and then
pop nth element plus two pauses Y each).
= 2X + 3Y
Stack Lifetime of last element, Tn-2 = Tn-1 + 2X + 2Y (Using the Same reasoning above)
= 4X + 5Y
.
.
.
Stack Lifetime of 1st element = 2(n-1)X + (2n-1)Y (Generalizing the pattern)
Sum of all the time spans of all the elements = (Σ 2(n-1)X) + (Σ (2n-1)Y)
for n = 1 to n
= 2X(1 + 2 + . . . + n-1) + Y(1 + 3 + 5 + . . . + (2n-1))
Using 2 identities:
- Sum of n natural numbers = (n*(n+1))/2 for the first summation
- Sn = (n/2)(a+l) Sum of AP series with an as first term and l being last for the second summation
Above sum is,
= (2X(n-1)n)/2 + Y(n/2)*(1 + 2n-1)
= n(n(X+Y)-X)
Therefore Average = Sum/n = n(X+Y)-X .
Hope, this would help.
Give a like if you are satisfied.