Analysis of potential method with example
Stack operations
Push operation: Time complexity to push an item into a stack is O(1)
Pop operation: Time complexity to pop an item from a stack is O(1)
Multipop operation: Time complexity to pop k item from a stack is min(stack size, k).
Algorithm:
Multipop (S, k)
While not Stack_Empty (S) and k ! = 0
do Pop (S)
k=k – 1
Let us define the potential of a stack as the number of elements in the stack.
So, Φ(D0) = 0 and Φ(Di) ≥ 0.
Amortized cost of Push: According to potential function.
Amortised cost(Ci) = Actual cost(ci ) + change in potential
Ci = ci +Φ(Di)-Φ(Di-1) = 1+n-(n-1) = 2
So, Ci is also O(1)
Amortized cost of Pop: According to potential function:
Amortised cost(Ci) = Actual cost(ci ) + change in potential
Ci = ci +Φ(Di-1)-Φ(Di) = 1+n-1-(n) = 0
So, Ci is also O(1)
Amortized cost of MultiPop: According to potential function:
Amortised cost(Ci) = Actual cost(ci ) + change in potential
Ci = ci +Φ(Di)-Φ(Di-1) = k + s – k – s =0
So, Ci is also O(1)
Now, we have the final result as shown below in the table
Operation |
Amortized cost as per |
---|---|
Push |
O(1) |
Pop |
O(1) |
Multipop |
O(1) |
So, the amortized cost of each operation is O(1) and the total cost of each operation is O(N).
So time complexity of N operations is O(N).
Therefore, it is appropriate to quantify the change in potential as positive for low-cost operations and negative for high-cost operations.