L1 Time and Space Complexity concept 1
L1 Time and Space Complexity concept 1
Time complexity
Space complexity
asymptotic notation
What is Time Complexity?
• Definition: Time Complexity quantifies the amount of time an algorithm takes to
complete as a function of the size of its input.
• Why is it important?
• • Helps compare algorithm efficiency.
• • Predicts scalability for large inputs.
• Time Complexity Sequence
• Basic Time Complexities in Ascending Order (Best to Worst):
• 1. O(1): Constant Time – Fastest
• 2. O(log n): Logarithmic Time
• 3. O(n): Linear Time
• 4. O(n log n): Log-linear Time
• 5. O(n^2): Quadratic Time
• 6. O(2^n): Exponential Time
• 7. O(n!): Factorial Time – Slowest
• Example:
Types of Time Complexity?
•Definitions:
• Best Case: The scenario where the algorithm performs the least number of operations.
• Worst Case: The scenario where the algorithm performs the maximum number of operations.
o Example: Searching for an element in an array, and it is the last element or not present.
• Average Case: The scenario where the algorithm performs an average number of operations over all possible
inputs.
o Example: Searching for an element in an array where the element is equally likely to be at any
position.
Why Are These Important?
Helps understand algorithm behavior under different conditions.
•Analyze Each Operation: Determine how many times each statement in the algorithm executes.
•Keep the Dominant Term: Focus on the term that grows the fastest as input size increases.
its input.
Key Components:
•Variable Part: Memory dependent on input size (e.g., arrays, recursion stack).
Why is it important?
•Fixed Memory Usage: Account for variables, constants, and program instructions.
•Dynamic Memory Usage: Evaluate memory required by data structures and recursive calls.
•Include Recursion Stack: For recursive algorithms, add the space used by function calls.
•Why is it useful?
Standardizes complexity analysis.
Real-World Example
Problem: Searching for an element in a sorted array.
Binary Search Algorithm
o Time Complexity: O(log n)
o Space Complexity: O(1)
Recursive Binary Search Algorithm
o Time Complexity: O(log n)
o Space Complexity: O(log n) (due to recursion stack)
Thank
s