Time and Space Complexity — Not so complex
Overview
Time and space complexity are measures used to analyze the efficiency of algorithms. They help us understand how an algorithm’s resource usage grows as the input size increases.
Why Is This Important?
- Performance: Efficient algorithms run faster and use less memory.
- Scalability: Good complexity ensures programs work well with large inputs.
- Optimization: Helps choose the best algorithm for a problem.
- Predictability: Allows estimation of resource needs before deployment.
Time Complexity
Time complexity describes how the runtime of an algorithm increases with input size (n). It is commonly expressed using Big O notation.
Common Time Complexities
- O(1): Constant time (e.g., accessing an array element)
- O(log n): Logarithmic time (e.g., binary search)
- O(n): Linear time (e.g., traversing a list)
- O(n log n): Linearithmic time (e.g., merge sort)
- O(n²): Quadratic time (e.g., bubble sort)
- O(2^n): Exponential time (e.g., recursive Fibonacci)
Example: Linear Search
public boolean linearSearch(int[] arr, int target) {
for (int i : arr) {
if (i == target) {
return true;
}
}
return false;
}
// Time Complexity: O(n)
Example: Binary Search
public boolean binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return true;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
// Time Complexity: O(log n)
Space Complexity
Space complexity measures the amount of memory an algorithm uses as input size grows.
Common Space Complexities
- O(1): Constant space (e.g., variable assignment)
- O(n): Linear space (e.g., storing an array)
- O(n²): Quadratic space (e.g., 2D matrix)
Example: Storing Results
public int[] storeResults(int[] arr) {
int[] results = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
results[i] = arr[i] * 2;
}
return results;
}
// Space Complexity: O(n)
Big O Notation Summary Table
Visual Guide
This table shows how different complexities grow as input size increases
This flowchart visually compares how different Big O complexities grow as input size increases.
Conclusion
Understanding time and space complexity helps you write efficient, scalable, and reliable code. Use Big O notation to compare algorithms and make informed decisions.




Top comments (0)