Find The Time Complexity of The Following Code Calculator
Determine the time complexity of code segments with our interactive calculator. This tool helps you analyze algorithm efficiency by examining loops, nested structures, and recursive calls. Learn how to identify Big-O notation through practical examples and step-by-step guidance.
How to Use This Calculator
To find the time complexity of your code:
- Paste your code snippet into the input box
- Select the programming language (currently supports JavaScript, Python, and Java)
- Click "Calculate" to analyze the code
- Review the time complexity result and detailed breakdown
This calculator analyzes basic control structures. For complex algorithms, manual analysis may be needed.
Time Complexity Basics
Time complexity describes how an algorithm's runtime grows with input size. It's expressed using Big-O notation:
O(log n) - Logarithmic time
O(n) - Linear time
O(n log n) - Linearithmic time
O(n²) - Quadratic time
O(2ⁿ) - Exponential time
The most dominant term determines the complexity. For example, a function with both O(n) and O(n²) operations is O(n²).
Common Code Patterns
Single Loop
Code with a single loop through an array is typically O(n).
// O(1) operations
}
Nested Loops
Nested loops multiply their complexities. Two O(n) loops become O(n²).
for (let j = 0; j < n; j++) {
// O(1) operations
}
}
Binary Search
Divide-and-conquer algorithms like binary search are O(log n).
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
Worked Examples
Example 1: Linear Search
This simple search algorithm has O(n) time complexity.
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}
Example 2: Bubble Sort
This sorting algorithm has O(n²) time complexity due to nested loops.
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
}
}
}
return arr;
}