Data-structures 2

Amortized complexity #definition

Method of assessing algorithms performance based on it over-all complexity,and not just worst edge-cases

Aggregate analysis

Compute total cost over multiple operations and find the averageUseful when operations have predictable, recurring costs (!!)Let’s examine a dynamic array that doubles in size when fullEach insertion is either O(1) or (m) where m is the current number of elements in arrayLet’s aggregate all insertions:Assume array starts with size 1First insertion is 1 itselfSecong insertion is 1 itself+2 for resizing up to 4Third insertion is 1 itselfFourth insertion is 1 itself+4 for resizing up to 8Fifth to seventh insertion are 1 themselvesLet n=2kk=lognTotal number of operations for n insertions is:T(n)=(1+2+4+8+16++n)+n==2logn121+n=2n12nT(n)=O(n),TA(n)=2nn=O(1)Amortized complexity of our insertions is O(1)Although there are heavy operations like the last resizing, that costs O(n) on itself,these operations occur rarely and contribute less to the over-all complexity,than myriads of simple O(1) insertions

Accounting method

Assign pre-paid "credits" to balance cheap and expensive operationsUseful when future operations are clearly predictable and can be "pre-paid"Let’s examine a stack with push,pop and multiPop methodsEach push operation costs O(1) as it is an insertion to an arrayEach pop operation costs O(1) as it is a simple extraction from the end of arrayEach multiPop operation costs O(m) as it is m extractionsLet’s use a trick of overestimating push operation, assume it costs 2 operationsbut store the unused "credit" for future useEach push would then contribute to a +1 credit on the balanceEach pop can then become "free" by using this stored "credit"We can safely assume that when executing pop there will be at least one "credit",or the stack is empty and operation is simply O(1)multiPop then also becomes "free" as it is "pre-paid" for by all the push operationsOver-all cost over n pushes and pops/multiPops is 2nWhich gives us an amortized complexity of O(1)

Potential method

Use a potential function to track stored work and balance costs instead of "credits"Useful when state changes over time and can be modeled using a functionLet’s examine a binary counterEach increment the counter has to flip some number bitsFor 00000001 it’s one bitFor 01111000 it’s four bitsLet us define a work function: w(s)=# of bit flipsLet us define a potential function: Φ(s)=# of 1s in sLet us then define amortized cost of each increment as:f(s)=w(s)+(Φ(s+1)Φ(s))meaning that operations contributing to increase in w will become more expensivewhile operations, that are expensive on its own will be compensated for reducing potentialf(0000)=1+(Φ(0001)Φ(0000))=2f(0001)=2+(Φ(0010)Φ(0001))=2f(0010)=1+(Φ(0011)Φ(0010))=2f(0111)=4+(Φ(1000)Φ(0111))=2f(1111)=4+(Φ(0000)Φ(1111))=0T(n)=i=1nf(si)i=1n2=2nT(n)=O(n)