✅ What is Time Complexity?
Time Complexity is the measure of how the execution time of an algorithm grows relative to the input size (n).
It tells us how fast an algorithm is.
๐น Common Time Complexities:
Big-O Notation | Name | Description |
---|---|---|
O(1) | Constant Time | Time doesn't grow with input size |
O(log n) | Logarithmic | Time grows slowly as input increases |
O(n) | Linear | Time grows directly with input |
O(n log n) | Linearithmic | Time grows faster than linear but less than quadratic |
O(n²) | Quadratic | Time grows with the square of input size |
O(2โฟ) | Exponential | Time doubles with each addition to input size |
O(n!) | Factorial | Time grows extremely fast (used in permutations etc.) |
๐ง Example in Python (Time Complexity O(n)):
Here, the function iterates once over the array → O(n) time.
✅ What is Space Complexity?
Space Complexity refers to the amount of memory used by an algorithm as a function of the input size.
It includes both temporary variables and recursive stack space.
๐น Common Space Complexities:
Big-O Notation | Description |
---|---|
O(1) | Uses constant space |
O(n) | Uses space proportional to input |
O(n²) | Uses space for matrices or nested structures |
๐ง Example in Python (Space Complexity O(n)):
Here, the function creates a new list of the same size → O(n) space.
๐ Key Differences: Time vs Space Complexity
Feature | Time Complexity | Space Complexity |
---|---|---|
Definition | Measures execution time growth | Measures memory usage growth |
Concerned with | CPU usage | Memory/RAM usage |
Example Metric | Loops, recursion, function calls | Variables, data structures, call stack |
Goal | Optimize speed | Optimize memory usage |
Common Trade-off | More speed can cost more memory (vice versa) | Use memoization: faster but more space |
๐ How to Analyze Time and Space Complexity in Python?
๐น Step-by-Step:
Count the Loops – Each nested loop adds a layer to time complexity.
Check Recursive Depth – For recursion, count calls and stack usage.
Track Memory Allocation – New lists, sets, dicts use memory.
Ignore Constants – Big-O ignores low-level constants.
๐งช Examples with Both Time and Space Complexity
✅ Example 1: Linear Search
Time Complexity: O(n) → worst case checks every element.
Space Complexity: O(1) → no extra space.
✅ Example 2: Merge Sort (Recursive)
Time Complexity: O(n log n)
Space Complexity: O(n) → due to the result and recursion stack.
✅ Example 3: Fibonacci (Recursive vs Dynamic)
❌ Naive Recursion:
Time: O(2โฟ), Space: O(n)
✅ Memoization (Dynamic Programming):
Time: O(n), Space: O(n)
๐งพ Summary Table
Algorithm | Time Complexity | Space Complexity |
---|---|---|
Linear Search | O(n) | O(1) |
Binary Search | O(log n) | O(1) |
Bubble Sort | O(n²) | O(1) |
Merge Sort | O(n log n) | O(n) |
Quick Sort | O(n log n) avg | O(log n) |
Fibonacci (Rec) | O(2โฟ) | O(n) |
Fibonacci (Memo) | O(n) | O(n) |
No comments:
Post a Comment