The Wayback Machine - https://web.archive.org/web/20241005054912/https://www.geeksforgeeks.org/introduction-to-amortized-analysis/
Open In App

Introduction to Amortized Analysis

Last Updated : 23 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Amortized Analysis is used for algorithms where an occasional operation is very slow, but most of the other operations are faster. In Amortized Analysis, we analyze a sequence of operations and guarantee a worst-case average time that is lower than the worst-case time of a particularly expensive operation. 
The example data structures whose operations are analyzed using Amortized Analysis are Hash Tables, Disjoint Sets, and Splay Trees. 

Amortized analysis is a technique used in computer science to analyze the average-case time complexity of algorithms that perform a sequence of operations, where some operations may be more expensive than others. The idea is to spread the cost of these expensive operations over multiple operations, so that the average cost of each operation is constant or less.

For example, consider the dynamic array data structure that can grow or shrink dynamically as elements are added or removed. The cost of growing the array is proportional to the size of the array, which can be expensive. However, if we amortize the cost of growing the array over several insertions, the average cost of each insertion becomes constant or less.

Amortized analysis provides a useful way to analyze algorithms that perform a sequence of operations where some operations are more expensive than others, as it provides a guaranteed upper bound on the average time complexity of each operation, rather than the worst-case time complexity.

Amortized analysis is a method used in computer science to analyze the average performance of an algorithm over multiple operations. Instead of analyzing the worst-case time complexity of an algorithm, which gives an upper bound on the running time of a single operation, amortized analysis provides an average-case analysis of the algorithm by considering the cost of several operations performed over time.

The key idea behind amortized analysis is to spread the cost of an expensive operation over several operations. For example, consider a dynamic array data structure that is resized when it runs out of space. The cost of resizing the array is expensive, but it can be amortized over several insertions into the array, so that the average time complexity of an insertion operation is constant.

Amortized analysis is useful for designing efficient algorithms for data structures such as dynamic arrays, priority queues, and disjoint-set data structures. It provides a guarantee that the average-case time complexity of an operation is constant, even if some operations may be expensive.

Let us consider an example of simple hash table insertions. How do we decide on table size? There is a trade-off between space and time, if we make hash-table size big, search time becomes low, but the space required becomes high. 

 

Dynamic Table



The solution to this trade-off problem is to use Dynamic Table (or Arrays). The idea is to increase the size of the table whenever it becomes full. Following are the steps to follow when the table becomes full. 
1) Allocate memory for larger table size, typically twice the old table. 
2) Copy the contents of the old table to a new table. 
3) Free the old table. 

If the table has space available, we simply insert a new item in the available space. 

What is the time complexity of n insertions using the above scheme? 
If we use simple analysis, the worst-case cost of insertion is O(n). Therefore, the worst-case cost of n inserts is n * O(n) which is O(n2). This analysis gives an upper bound, but not a tight upper bound for n insertions as all insertions don’t take Θ(n) time. 

 

AmortizedAnalysis



So using Amortized Analysis, we could prove that the Dynamic Table scheme has O(1) insertion time which is a great result used in hashing. Also, the concept of the dynamic table is used in vectors in C++ and ArrayList in Java. 

Following are a few important notes. 
1) Amortized cost of a sequence of operations can be seen as expenses of a salaried person. The average monthly expense of the person is less than or equal to the salary, but the person can spend more money in a particular month by buying a car or something. In other months, he or she saves money for the expensive month. 

2) The above Amortized Analysis was done for Dynamic Array example is called Aggregate Method. There are two more powerful ways to do Amortized analysis called Accounting Method and Potential Method. We will be discussing the other two methods in separate posts. 

3) The amortized analysis doesn’t involve probability. There is also another different notion of average-case running time where algorithms use randomization to make them faster and the expected running time is faster than the worst-case running time. These algorithms are analyzed using Randomized Analysis. Examples of these algorithms are Randomized Quick Sort, Quick Select and Hashing. We will soon be covering Randomized analysis in a different post. 

Amortized analysis of insertion in Red-Black Tree 

Let us discuss the Amortized Analysis of Red-Black Tree operations (Insertion) using the Potential Method. 

To perform the amortized analysis of the Red-Black Tree Insertion operation, we use the Potential(or Physicist’s) method. For the potential method, we define a potential function [Tex]\phi            [/Tex]that maps a data structure to a non-negative real value. An operation can result in a change of this potential. 

Let us define the potential function [Tex]\phi            [/Tex]in the following manner: 
[Tex]\begin{equation} g(n)=\begin{cases} 0, & \text{if n is red}.\\ 1, & \text{if n is black with no red children}. \\ 0, & \text{if n is black with one red child}.\\ 2, & \text{if n is black and has two red children }.\\ \end{cases} \end{equation}            [/Tex]
where n is a node of Red-Black Tree 

Potential function [Tex]\phi            [/Tex]= [Tex]\sum_{} g(n)            [/Tex],over all nodes of the red black tree. 

Further, we define the amortized time of an operation as: 

Amortized time= c + [Tex]\Delta\phi            [/Tex](h) 

[Tex]\Delta\phi            [/Tex](h)= [Tex]\phi            [/Tex](h’) – [Tex]\phi            [/Tex](h) 
where h and h’ are the states of the Red-Black Tree before and after the operation respectively 
c is the actual cost of the operation 

The change in potential should be positive for low-cost operations and negative for high-cost operations. 

A new node is inserted on a leaf of a red-black tree. We have the leaves of a red-black tree of any one of the following types: 
 



The insertions and their amortized analysis can be represented as: 
(1) 

Amortized Insertion



This insertion is performed by first recoloring the parent and the other sibling(red). Then the grandparent and uncle of that leaf node are considered for further recoloring which leads to the amortized cost to be -1(when the grandparent of the leaf node is red), -2 (when uncle of the leaf is black and the grandparent is black) or +1 (when uncle of the leaf is red and grandparent is black). The insertion can be shown as: 
 

Amortized Insertion



(2) 
 

Amortized Insertion



In this insertion, the node is inserted without any changes as the black depth of the leaves remains the same. This is the case when the leaf may have a black sibling or does not have any sibling (since we consider the color of the color of null node to be black). 

So, the amortized cost of this insertion is 0. 

(3) 
 

Amortized Insertion



In this insertion, we cannot recolor the leaf node, its parent, and the sibling such that the black depth stays the same as before. So, we need to perform a Left- Left rotation. 

After rotation, there are no changes when the grandparent of g(the inserted node) is black. Also, for the case of the Red Grandparent of g(the inserted node), we do not have any changes. So, the insertion is completed with amortized cost= +2. The insertion has been depicted below: 
 

Amortized Insertion



After calculating these particular amortized costs at the leaf site of a red-black tree we can discuss the nature of the total amortized cost of insertion in a red-black tree. Since this may happen that two red nodes may have a parent-child relationship till the root of the red-black tree. 

So in the extreme(or corner) case, we reduce the number of black nodes with two red children by 1, and we at most increase the number of black nodes with no red children by 1, leaving a net loss of at most 1 to the potential function. Since one unit of potential pays for each operation therefore 

[Tex]\Delta\phi            [/Tex](h) [Tex]\leq            [/Tex]n 
where n is the total number of nodes 

In computer science and algorithms, amortized analysis is a technique used to estimate the average time complexity of an algorithm over a sequence of operations, rather than the worst-case complexity of individual operations. It allows us to make more accurate predictions about the overall efficiency of an algorithm, especially in cases where some operations may take longer than others.

  1. The basic idea behind amortized analysis is to distribute the cost of expensive operations over a sequence of less expensive operations. For example, suppose we have an algorithm that occasionally performs a very expensive operation that takes O(n) time, but most of the time performs an operation that takes only O(1) time. In worst-case analysis, we would say that the algorithm takes O(n) time, but in amortized analysis, we can distribute the cost of the expensive operation over a sequence of n operations, resulting in an average cost of O(1) per operation.
  2. There are several techniques for performing amortized analysis, including aggregate analysis, accounting method, and potential method. In aggregate analysis, we compute the total cost of a sequence of operations and divide it by the number of operations to get the average cost per operation. In the accounting method, we assign credits to each operation and use them to pay for expensive operations. In the potential method, we assign a potential value to the data structure being operated on and use it to measure the amount of work done by each operation.

Amortized analysis is a powerful tool for analyzing the performance of algorithms over a sequence of operations. It allows us to make more accurate predictions about the average case complexity of an algorithm and can help us identify cases where an algorithm may perform poorly in practice, even if its worst-case complexity is low.

Advantages of amortized analysis:

  1. More accurate predictions: Amortized analysis provides a more accurate prediction of the average-case complexity of an algorithm over a sequence of operations, rather than just the worst-case complexity of individual operations.
  2. Provides insight into algorithm behavior: By analyzing the amortized cost of an algorithm, we can gain insight into how it behaves over a longer period of time and how it handles different types of inputs.
  3. Helps in algorithm design: Amortized analysis can be used as a tool for designing algorithms that are efficient over a sequence of operations.
    Useful in dynamic data structures: Amortized analysis is particularly useful in dynamic data structures like heaps, stacks, and queues, where the cost of an operation may depend on the current state of the data structure.


Disadvantages of amortized analysis:

  1. Complexity: Amortized analysis can be complex, especially when multiple operations are involved, making it difficult to implement and understand.
  2. Limited applicability: Amortized analysis may not be suitable for all types of algorithms, especially those with highly unpredictable behavior or those that depend on external factors like network latency or I/O operations.
  3. Lack of precision: Although amortized analysis provides a more accurate prediction of average-case complexity than worst-case analysis, it may not always provide a precise estimate of the actual performance of an algorithm, especially in cases where there is high variance in the cost of operations.

    Thus, the total amortized cost of insertion in the Red-Black Tree is O(n). 

    For any doubts regarding insertions in a red-black tree, you may refer to Insertions in Red-Black Tree. 
     

For more details, please refer: Design and Analysis of Algorithms.


 



Previous Article
Next Article

Similar Reads

Amortized analysis for increment in counter
Amortized analysis refers to determining the time-averaged running time for a sequence (not an individual) operation. It is different from average case analysis because here, we don't assume that the data arranged in average (not very bad) fashion like we do for average case analysis for quick sort. That is, amortized analysis is worst case analysi
4 min read
Difference between average case and amortized analysis
Average case analysis is a type of algorithm analysis that takes into account the distribution of inputs that an algorithm is likely to encounter in practice. In contrast to worst-case analysis, which considers the performance of an algorithm on the input that causes it to take the longest time to execute, the average-case analysis assumes that the
3 min read
Potential Method in Amortized Analysis
What is Amortization? Consider that you are a company owner and that you require a vehicle. The automobile is priced at €10, 000. You'll have to spend €10, 000 if you decide to purchase it this year. But you want to keep driving the automobile for the next ten years. An additional €1, 000 is needed to operate the automobile for a year.There are two
6 min read
Accounting Method | Amortized Analysis
Amortized analysis is a method used to analyze the performance of algorithms that perform a sequence of operations, where each individual operation may be fast, but the sequence of operations may be slow as a whole. It is used to determine the average cost per operation, allowing for a more accurate comparison of algorithms that perform different n
4 min read
RFM Analysis Analysis Using Python
In this article, we are going to see Recency, Frequency, Monetary value analysis using Python. But first, let us understand the RFM analysis briefly. What is RFM analysis? RFM stands for recency, frequency, monetary value. In business analytics, we often use this concept to divide customers into different segments, like high-value customers, medium
3 min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
Asymptotic Notation and Analysis (Based on input size) in Complexity Analysis of Algorithms
Asymptotic Analysis is defined as the big idea that handles the above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don't measure the actual running time). We calculate, how the time (or space) taken by an algorithm increases with the input size. Asymptotic notation is
8 min read
Randomized Algorithms | Set 1 (Introduction and Analysis)
What is a Randomized Algorithm? An algorithm that uses random numbers to decide what to do next anywhere in its logic is called a Randomized Algorithm. For example, in Randomized Quick Sort, we use a random number to pick the next pivot (or we randomly shuffle the array). And in Karger's algorithm, we randomly pick an edge. How to analyse Randomize
6 min read
Analysis and applications Karger’s algorithm for Minimum Cut
We have introduced and discussed below Karger's algorithm in set 1. 1) Initialize contracted graph CG as copy of original graph 2) While there are more than 2 vertices. a) Pick a random edge (u, v) in the contracted graph. b) Merge (or contract) u and v into a single vertex (update the contracted graph). c) Remove self-loops 3) Return cut represent
4 min read
Analysis of test data using K-Means Clustering in Python
This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library. Pre-requisites: Numpy, OpenCV, matplot-lib Let's first visualize test data with Multiple Features using matplot-lib tool. # importing required tools import numpy as np from matplotlib import pyplot as plt # creating two test data X = np.ra
2 min read
Time Complexity Analysis | Tower Of Hanoi (Recursion)
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk ca
2 min read
Guidelines for asymptotic analysis
In this article, the focus is on learning some rules that can help to determine the running time of an algorithm. Asymptotic analysis refers to computing the running time of any operation in mathematical units of computation. In Asymptotic Analysis, the performance of an algorithm in terms of input size (we don’t measure the actual running time) is
4 min read
Algorithms Sample Questions | Set 3 | Time Order Analysis
Question 1: What is the asymptotic boundary of T(n)? [Tex] T(n) = \sum_{i=2}^{n} log_{i}n = log_{2}n + log_{3}n + \ldots + log_{n}n [/Tex] θ( n*log(n) ) θ( n2 ) θ( n ) θ( n*log2(n) ) θ( n2*log2(n) ) Answer: 3 Explanation: To find appropriate upper and lower boundaries, an approach which first comes to mind is to expand
10 min read
Difference between Posteriori and Priori analysis
Prerequisite - Analysis of Algorithms Algorithm is a combination or sequence of finite-state to solve a given problem. If the problem is having more than one solution or algorithm then the best one is decided by the analysis based on two factors. CPU Time (Time Complexity)Main memory space (Space Complexity) Time complexity of an algorithm can be c
2 min read
Boundary Value Analysis : Nature of Roots of a Quadratic equation
Consider a problem for the determination of the nature of the roots of a quadratic equation where the inputs are 3 variables (a, b, c) and their values may be from the interval [0, 100]. The output may be one of the following depending on the values of the variables: Not a quadratic equation,Real roots,Imaginary roots,Equal roots Our objective is t
12 min read
Complexity analysis of various operations of Binary Min Heap
A Min Heap is a Complete Binary Tree in which the children nodes have a higher value (lesser priority) than the parent nodes, i.e., any path from the root to the leaf nodes, has an ascending order of elements. In the case of a binary tree, the root is considered to be at height 0, its children nodes are considered to be at height 1, and so on. Each
3 min read
Tukey-Kramer Test for Post Hoc Analysis
If in ANOVA test we come to a conclusion that we have to reject our null hypothesis(H0) and then we know that some treatment or factor level means are different and we wish to find them then we proceed to do post hoc analysis with Tukey's test to find which pair is different. This method is a multiple comparison method. About: Used to tell about po
2 min read
GE Stock Price Analysis Using R Language
Stock analysis is a technique used by investors and traders to make purchasing and selling choices. Investors and traders strive to obtain an advantage in the markets by making educated judgments by researching and analyzing previous and current data. In this article, we will analyze the 'GE Stock Price' dataset using the R Programming Language. Th
5 min read
Step Count Method for Time Complexity Analysis
What is Time Complexity? Time Complexity is the amount of time taken by the algorithm to run. It measures the time taken to execute each statement of code in an algorithm. Time Complexity can be calculated by using Two types of methods. They are: Step Count MethodAsymptotic Notation. Here, we will discuss the Step Count Method. What is Step Count M
4 min read
Time and Space complexity analysis of Selection Sort
The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already sorted. (where n is the number of integers in an
2 min read
Time and Space Complexity Analysis of Tree Traversal Algorithms
Let us discuss the Time and Space complexity of different Tree Traversal techniques, such as Inorder Traversal, Preorder Traversal, Postorder Traversal, etc. Time Complexity of Tree Traversal AlgorithmsLet us see different corner cases: Complexity function T(n) — for all problems where tree traversal is involved — can be defined as: T(n) = T(k) + T
2 min read
Time and Space Complexity analysis of Stack operations
What is Stack?Stack is a linear data structure that follows a particular order in which the elements are inserted and deleted. A stack follows the principle of last in first out(LIFO) which means that the last element inserted into the stack should be removed first. Consider an example of plates stacked over one another in the canteen. The plate wh
15+ min read
Kahn's Algorithm vs DFS Approach: A Comparative Analysis
Topological sorting is a common problem in computer science that involves arranging the vertices of a directed acyclic graph (DAG) in a linear order such that for every directed edge (u, v), vertex u comes before vertex v in the ordering. Two important methods to solve are: Kahn's AlgorithmDepth-First Search (DFS) AlgorithmLet us take the following
13 min read
Why the Analysis of Algorithm is important?
In this article, we will discuss why algorithm and its analysis is important? In the analysis of the algorithm, it generally focused on CPU (time) usage, Memory usage, Disk usage, and Network usage. All are important, but the most concern is about the CPU time. Be careful to differentiate between: Performance: How much time/memory/disk/etc. is used
2 min read
Analysis of Algorithms | Big - Θ (Big Theta) Notation
In the analysis of algorithms, asymptotic notations are used to evaluate the performance of an algorithm, in its best cases and worst cases. This article will discuss Big - Theta notations represented by a Greek letter (Θ). Definition: Let g and f be the function from the set of natural numbers to itself. The function f is said to be Θ(g), if there
6 min read
Bellman-Ford vs Floyd-Warshall's algorithm: A Comparative Analysis
Bellman-Ford Algorithm:The Bellman-Ford algorithm is a single-source shortest-path algorithm that works by iteratively relaxing edges in the graph until the shortest path to all vertices is found. It is especially useful for graphs with negative edge weights, as it can detect negative cycles and return a suitable error message. Floyd-Warshall Algor
15+ min read
Analysis of Different Methods to find Prime Number in Python
If you participate in competitive programming, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem setter. Here, we will discuss how to optimize your function which checks for the Prime number in the given set of ranges, and will also calculate the timings to execute them. Going by defin
7 min read
Analysis of different sorting techniques
In this article, we will discuss important properties of different sorting techniques including their complexity, stability and memory constraints. Before understanding this article, you should understand basics of different sorting techniques (See : Sorting Techniques). Time complexity Analysis - We have discussed the best, average and worst case
5 min read
Time and Space Complexity Analysis of Queue operations
What is Queue?Queue is a linear data structure that follows FIFO approach (First In First Out). One can imagine a queue as a line of people waiting in sequential order which starts from the beginning of the line. It is an ordered list in which insertions are done at one end which is known as the rear and deletions are done from the other end known
15+ min read
Time and Space Complexity Analysis of Prim's Algorithm
The time complexity of Prim's algorithm is O(V2) using an adjacency matrix and O((V +E) log V) using an adjacency list, where V is the number of vertices and E is the number of edges in the graph. The space complexity is O(V+E) for the priority queue and O(V2) for the adjacency matrix representation. The algorithm's time complexity depends on the d
3 min read