Algorithm complexity (Time and Space)
Algorithm Complexity (Time and Space) Definition: Algorithm complexity, also known as time complexity or space complexity, measures the efficiency of an...
Algorithm Complexity (Time and Space) Definition: Algorithm complexity, also known as time complexity or space complexity, measures the efficiency of an...
Algorithm Complexity (Time and Space)
Definition:
Algorithm complexity, also known as time complexity or space complexity, measures the efficiency of an algorithm in terms of the amount of time or space it takes to complete a task.
Time Complexity:
Constant time (O(1)): The algorithm takes the same amount of time regardless of the input size.
Example: Searching for an element in a sorted array.
Linear time (O(n)): The algorithm takes n units of time to complete.
Example: Traversing a linked list.
Quadratic time (O(n^2)): The algorithm takes n^2 units of time to complete.
Example: Finding the maximum element in a sorted array.
Linear space (O(1)): The algorithm takes constant time to store the intermediate results.
Example: Iterating over an array and calculating the sum.
Quadratic space (O(n^2)): The algorithm takes n^2 units of space to store the intermediate results.
Example: Dynamic programming algorithm to solve a subproblem.
Space Complexity:
Constant space (O(1)): The algorithm uses the same amount of space regardless of the input size.
Example: Checking the value of a single element in a dictionary.
Linear space (O(n)): The algorithm uses n units of space to store the intermediate results.
Example: Traversing a linked list.
Quadratic space (O(n^2)): The algorithm uses n^2 units of space to store the intermediate results.
Example: Sorting an array requires O(n^2) comparisons between elements.
Linear time, constant space (O(n)): The algorithm takes n units of time and uses constant space to store the results.
Example: Implementing binary search with a sorted array.
Key Differences:
Time complexity focuses on the time taken to complete a task, regardless of the input size.
Space complexity focuses on the amount of space used during the algorithm execution.
Examples:
Time complexity: O(1) for searching in a sorted array, O(n) for traversing a linked list.
Space complexity: O(1) for checking the value of a single element, O(n) for iterating over a linked list