Time and Space Complexity _ 2023
Time and Space Complexity _ 2023
● Auxiliary space: The additional space used by the algorithm, e.g., to hold
temporary variables or the space used by the call stack.
Asymptotic Analysis
● Asymptotic analysis evaluates the performance of
algorithms as input size grows, crucial for predicting
efficiency and resource usage.
● Sum all the calculated values and divide the sum by the
total number of inputs
Worst case- (Big O)
● In the worst-case analysis, we calculate the upper bound
on the running time of an algorithm.
=> When analyzing an algorithm, go through the code and identify these
basic operations
Count the operations
● Analyze loops and iterations
● Consider conditional statements
● Look for recursion
● Account for nested operations
● Count function calls
Analyze loops and iterations
for i in range(n):
if is_perfect_square(i):
for j in range(n):
# constant time code here
Look for recursion
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
# Example usage
result = factorial(5)
print(result)
Account for nested operations
def example_code(arr):
for i in range(n):
n = len(arr)
for j in range(i, n):
result = 0
# code for element in arr:
i = 1
while i * i <= n:
result += element
i += 1
return result
Count function calls
def example_function_1(x):
return x*2
def example_function_2(x):
total = 0
for element in arr:
total += example_function_1(element)
return total
def main_algorithm(arr):
result = 0
for _ in range(3):
result += example_function_2(arr)
return result
Express the relationship
Binary Search Tree O(log n)* O(log n)* O(log n)* O(log n)*
n ≤ 10 O(n!)
n ≤ 20 O(2^n)
n ≤ 30 O(n^4)
n ≤ 100 O(n^3)
n ≤ 10^3 O(n^2)
n ≤ 10^6 O(n)
char 1 byte
short 2 bytes
int 4 bytes
long 4 bytes
It depends on the processor involved. For a processor running 4GHz, it would mean
4*10^9 cycles per-second. If each operation take one cycle, it means the computer
can run 10^9 operations per second. (time complexity should be less than 10^9)
Tips - Common Errors
Time Limit Exceeded: The program hadn't terminated in time indicated in the problem
statement
Memory Limit Exceeded: The program tries to consume more memory than is
indicated in the problem statement
Runtime Error (): The program terminated with a non-zero return code (possible
reasons: array out of bound error, division by zero, stack overflow, incorrect pointers
usage, recursion limit exceeded, etc)
Idleness limit exceeded: The program didn't use the CPU time for considerable time
Tips
Pitfalls
● Don’t use the same input size notation for different
inputs
for i in range(len(input_array)):
for j in range(max_value):
total_operations += 1
Time Complexity :
O(length of input_array*max_value)
Pitfalls
● Don’t include the input space in your space analysis; focus on
the auxiliary space unless specified otherwise.
● Note: Always pick the the upper bound that does not
underestimate your algorithm’s performance in your
analysis.
Resources