L6 - Time & Space Complexity-1.2
L6 - Time & Space Complexity-1.2
n0
How To
Operations
Complexity
O (n log n)
O(n)
Elements
What is Space Complexity?
Space Complexity
Topic/Course
of an algorithm is the total space taken by the algorithm
with respect to the input size.
Space complexity includes both Auxiliary space and space used by input.
Ex.1: Each call adds to the call stack ‘n’ Ex 2. There will be roughly O(n) calls to
times. Hence space complexity is O(n). pairSum. However, those calls do not
However, just because you have n calls exist simultaneously on the call
total doesn't mean it takes O(n) space. stack, so you only need O(1) space.
Consider
It is very possible for O(N) code to run faster than 0( 1) code for specific inputs.
Big O just describes the rate of increase.
For this reason, we drop the constants in runtime. An algorithm that one might
have described as 0(2N) is actually O(N).
Topic/Course
Topic/Course
int foo(int n) {
int* arr = new int[n];
for (int i = 0; i < n;
i++) {
arr[i] = i;
}
return arr[n-1];
}
int sum = 0;
for (int i = 0; i < n; i+
+) {
sum += i;
}
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n-1) +
fibonacci(n-2);
}