Reference: How to Calculate Time complexity algorithm

I found a good article related to How to calculate time complexity of any algorithm or program

The most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:

statement;

Is constant. The running time of the statement will not change in relation to N.

for ( i = 0; i < N; i++ )
     statement;

Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.

for ( i = 0; i < N; i++ ) {
  for ( j = 0; j < N; j++ )
    statement;
}

Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.

while ( low <= high ) {
  mid = ( low + high ) / 2;
  if ( target < list[mid] )
    high = mid - 1;
  else if ( target > list[mid] )
    low = mid + 1;
  else break;
}

Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.

void quicksort ( int list[], int left, int right )
{
  int pivot = partition ( list, left, right );
  quicksort ( list, left, pivot - 1 );
  quicksort ( list, pivot + 1, right );
}

Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.

In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( ) where is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).

Note that none of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course. ;)

Edit:

Now the Question is how did the log n get into the equation:

  1. For each step, you invoke the algorithm recursively on the first and second half.
  2. Thus - the total number of steps needed, is the number of times it will take to reach from n to 1 if you devide the problem by 2 each step.

The equation is: n / 2^k = 1. Since 2^logn = n, we get k = logn. So the number of iterations the algorithm requires is O(logn), which will make the algorithm O(nlogn)

Also, big O notation gives us easy to calculate - platform independent approximation on how will the algorithm behave asymptotically (at infinity), which can divide the "family" of algorithm into subsets of their complexity, and let us compare easily between them.

You can also check out this Question for more reading: Time complexity of the program using recurrence equation

Answer from Vinayak Pahalwan on Stack Overflow
Top answer
1 of 2
37

Reference: How to Calculate Time complexity algorithm

I found a good article related to How to calculate time complexity of any algorithm or program

The most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:

statement;

Is constant. The running time of the statement will not change in relation to N.

for ( i = 0; i < N; i++ )
     statement;

Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.

for ( i = 0; i < N; i++ ) {
  for ( j = 0; j < N; j++ )
    statement;
}

Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.

while ( low <= high ) {
  mid = ( low + high ) / 2;
  if ( target < list[mid] )
    high = mid - 1;
  else if ( target > list[mid] )
    low = mid + 1;
  else break;
}

Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.

void quicksort ( int list[], int left, int right )
{
  int pivot = partition ( list, left, right );
  quicksort ( list, left, pivot - 1 );
  quicksort ( list, pivot + 1, right );
}

Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.

In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( ) where is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).

Note that none of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course. ;)

Edit:

Now the Question is how did the log n get into the equation:

  1. For each step, you invoke the algorithm recursively on the first and second half.
  2. Thus - the total number of steps needed, is the number of times it will take to reach from n to 1 if you devide the problem by 2 each step.

The equation is: n / 2^k = 1. Since 2^logn = n, we get k = logn. So the number of iterations the algorithm requires is O(logn), which will make the algorithm O(nlogn)

Also, big O notation gives us easy to calculate - platform independent approximation on how will the algorithm behave asymptotically (at infinity), which can divide the "family" of algorithm into subsets of their complexity, and let us compare easily between them.

You can also check out this Question for more reading: Time complexity of the program using recurrence equation

2 of 2
2

You should also read about Amortized Analysis to fully understand the notions of time complexity. Amortized analysis is used to have a worst-case bound for the performance of an algorithm by considering all the operations.

The link to the Wikipedia article is given below,

http://en.wikipedia.org/wiki/Amortized_analysis

🌐
GeeksforGeeks
geeksforgeeks.org › dsa › understanding-time-complexity-simple-examples
Time Complexity with Simple Examples - GeeksforGeeks
Instead of measuring actual time required in executing each statement in the code, Time Complexity considers how many times each statement executes. We measure rate of growth over time with respect to the inputs taken during the program execution.
Published   February 26, 2026
Discussions

Analyzing time complexity of Java methods
Their time complexities are almost always specified in the Javadoc documentation you can find online, for example here's ArrayList docs: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html You can find Java source code on github. For example, here's the addAll method of an ArrayList: https://github.com/openjdk/jdk/blob/fe0544f8a7db5bf0e93313e16b54b31bcdff946a/src/java.base/share/classes/java/util/ArrayList.java#L669 You can also access these locally if your JDK came with sources or by installing java-{VERSION}-openjdk-src package (RHEL/Fedora) if it didn't. Or just open up your IDE, call the method and then use the "Go to Definition" funcitonality, it'll probably first show the decompiled version, but I think IntelliJ also offers to download sources automatically. More on reddit.com
🌐 r/learnprogramming
12
1
August 23, 2022
How to Figure out the Time Complexity of my code?
Write down how many operations it does in terms of input size and cross out everything apart from the most dominating part. More on reddit.com
🌐 r/learnprogramming
7
3
June 7, 2022
What is the time complexity of this Java program? - Computer Science Stack Exchange
The upper bound (worst - case senario) is when there are 1 or 0 positive numbers in the array because the algorithm will terminate only when i is equal to the number of elements of the array. In this case the time complexity is O(n^2) because there is a nested loop. More on cs.stackexchange.com
🌐 cs.stackexchange.com
April 11, 2022
java - What are the time complexities of various data structures? - Stack Overflow
I am trying to list time complexities of operations of common data structures like Arrays, Binary Search Tree, Heap, Linked List, etc. and especially I am referring to Java. They are very common, b... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What are the main classifications of time complexity in Java big O notation?
The main classifications include: 1. O(1): Constant time complexity 2. O(n): Linear time complexity 3. O(n²): Quadratic time complexity
🌐
finalroundai.com
finalroundai.com › blog › java-big-o-notation-tutorial-understanding-time-complexity-in-depth
Java Big O Notation Tutorial: Understanding Time Complexity in Depth
What are some examples of algorithms with quadratic complexity?
Algorithms that exhibit quadratic complexity, O(n²), typically involve nested iterations, such as bubble sort and selection sort.
🌐
finalroundai.com
finalroundai.com › blog › java-big-o-notation-tutorial-understanding-time-complexity-in-depth
Java Big O Notation Tutorial: Understanding Time Complexity in Depth
What does O(n log n) represent in algorithm complexity?
O(n log n) represents linearithmic duration, commonly seen in efficient sorting methods, where the operation merges linear growth with logarithmic factors.
🌐
finalroundai.com
finalroundai.com › blog › java-big-o-notation-tutorial-understanding-time-complexity-in-depth
Java Big O Notation Tutorial: Understanding Time Complexity in Depth
🌐
Baeldung
baeldung.com › home › java › java collections › time complexity of java collections
Time Complexity of Java Collections | Baeldung
September 24, 2025 - Usually, when we talk about time complexity, we refer to Big-O notation. Simply put, the notation describes how the time to perform the algorithm grows with the input size. Useful write-ups are available to learn more about Big-O notation theory and practical Java examples.
🌐
Reddit
reddit.com › r/learnprogramming › analyzing time complexity of java methods
r/learnprogramming on Reddit: Analyzing time complexity of Java methods
August 23, 2022 -

Hello everyone!

Does Oracle have any websites where I could find out what the time complexity of a method is? I know sometimes they have that information in the API; for example, java.util.ArrayList has the following info:

"The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation."

However, I couldn't find that info for any other classes. Where can I find it? If there are other classes that bring that up that you know, please let me know which. Also, how do I have access to the source code of the language? I need to make a study on the complexity of Java methods using the Big O notation and, in order to do that, I would need access to the source code of the methods and it would also be of great help if they had documentation about the complexity of Java methods, so I can demonstrate and "prove" it for my assignment.

🌐
Medium
sumeetpanchal-21.medium.com › exploring-java-code-samples-understanding-time-complexity-and-outputs-cad12e57ac4b
Exploring Java Code Samples: Understanding Time Complexity and Outputs | by Sumeet Panchal | Medium
February 4, 2024 - The time complexity is O(square-root(n)​). To calculate the output, we iterate through each value of i until s exceeds n, where s represents the sum of consecutive integers starting from 1.
🌐
Javatpoint
javatpoint.com › post › time-complexity
Time Complexity - Javatpoint
Time Complexity with if-else, switch case, for loop, while loop, do-while, break, continue, goto, arrays, functions, pointers, collections, LinkedList, etc.
Find elsewhere
🌐
W3Schools
w3schools.com › dsa › dsa_timecomplexity_theory.php
DSA Time Complexity
When talking about "operations" here, "one operation" might take one or several CPU cycles, and it really is just a word helping us to abstract, so that we can understand what time complexity is, and so that we can find the time complexity for different algorithms.
🌐
FinalRoundAI
finalroundai.com › blog › java-big-o-notation-tutorial-understanding-time-complexity-in-depth
Java Big O Notation Tutorial: Understanding Time Complexity in Depth
February 24, 2025 - O(n!): Factorial time – increases factorially, commonly linked with intricate recursive processes that produce permutations. Comprehending these complexities is crucial for assessing and choosing the most suitable methods for specific tasks, particularly in relation to java big o notation, as emphasized by the quote:
🌐
Geekster
blog.geekster.in › home › exploring time complexity in java -what is it?
Time Complexity In Java - Types And Benefits
September 7, 2023 - In this case, the time taken is directly proportional to the number of elements in the array (n). So the time complexity is O(n). An algorithm is said to have a quadratic time complexity when the time it takes to complete its execution is ...
🌐
Interview Cake
interviewcake.com › article › java › big-o-notation-time-and-space-complexity
Big O Notation | Interview Cake
So sometimes n is an actual number that's an input to our method, and other times n is the number of items in an input array (or an input map, or an input object, etc.). This is why big O notation rules. When you're calculating the big O complexity of something, you just throw out the constants.
🌐
GitHub
gist.github.com › psayre23 › c30a821239f4818b0709
Runtime Complexity of Java Collections - Gist - GitHub
shouldn't the worst time complexity for ArrayList add() operation be O(n) as in the worst case the element might need to be inserted in the middle.
🌐
Medium
medium.com › @AlexanderObregon › logarithmic-time-complexity-in-java-a-simple-explanation-for-beginners-8c40aec24919
Logarithmic Time Complexity in Java — A Simple Explanation for Beginners
April 29, 2024 - One of the most critical skills ... complexity, part of the Big O notation, is a concept used to describe how the run time of an algorithm changes as the size of the input grows....
🌐
Reddit
reddit.com › r/learnprogramming › how to figure out the time complexity of my code?
r/learnprogramming on Reddit: How to Figure out the Time Complexity of my code?
June 7, 2022 -

I started doing LeetCode problems, and on this problem https://leetcode.com/problems/two-sum/

There's the following note ..

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

I was wondering, how do I know the time complexity for the code I have written?

🌐
Stack Exchange
cs.stackexchange.com › questions › 150581 › what-is-the-time-complexity-of-this-java-program
What is the time complexity of this Java program? - Computer Science Stack Exchange
April 11, 2022 - The upper bound (worst - case senario) is when there are 1 or 0 positive numbers in the array because the algorithm will terminate only when i is equal to the number of elements of the array. In this case the time complexity is O(n^2) because there is a nested loop.
🌐
DEV Community
dev.to › jhonifaber › choosing-the-right-java-collection-5750
Java Collections: From Lists to Maps with Time Complexity in Mind - DEV Community
August 7, 2025 - When you need to ensure no duplicates in your collection, use a Set. Time Complexity (HashSet):
🌐
Codecademy
codecademy.com › learn › java-algorithms › modules › apcs-algorithmic-complexity › cheatsheet
Java: Algorithms: Algorithmic Complexity Cheatsheet | Codecademy
We compute the big-Ω by counting how many iterations an algorithm will take in the best-case scenario based on an input of N. For example, a Bubble Sort algorithm has a running time of Ω(N) because in the best case scenario the list is already sorted, and the bubble sort will terminate after the first iteration. ... Learn the basics of recursion and how to implement and analyze important algorithms in Java.
Top answer
1 of 2
289

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traversing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traversing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traversing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traversing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)
2 of 2
0

Baeldung pointed out some time complexities for the ArrayList, LinkedList, and CopyOnWriteArrayList here: https://www.baeldung.com/java-collections-complexity and for Map implementations here: https://www.baeldung.com/java-hashmap

He also added benchmarks to highlight differences among the implementations.

🌐
InterviewBit
interviewbit.com › courses › programming › time-complexity › how-to-calculate-time-complexity
How to Calculate Time Complexity?
Therefore the time complexity of the first fragment would be O(n), as the loop would run n times, the time complexity of the statements inside the loop is O(1).
🌐
NareshIT
nareshit.com › blogs › time-space-complexity-java-data-structures-nareshit
Time & Space Complexity in Java Data Structures | NareshIT
Time O(n), extra space O(n).” ... Being able to talk about complexity fluently makes you look like a serious, prepared candidate. ... Logarithmic behavior often comes from halving (binary search, heaps, trees).