Consider a recursive function that calculates the factorial of a number n. What is the space complexity of this function in terms of n?
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
Think about how many times the function calls itself before reaching the base case and what happens to memory during these calls.
The recursive factorial function calls itself n times before reaching the base case. Each call adds a new frame to the call stack, so the space used grows linearly with n, resulting in O(n) space complexity.
Which statement correctly compares the space complexity of an iterative algorithm and its recursive counterpart that solve the same problem?
Consider what happens in memory when a recursive function calls itself multiple times.
Recursive algorithms use additional space for each call on the call stack, which can lead to higher space usage compared to iterative algorithms that reuse the same variables and do not add call stack frames.
Given the following pseudocode, what is the space complexity in terms of n?
result = [] for i in range(n): temp = [] for j in range(n): temp.append(i * j) result.append(temp)
Consider how many elements are stored in total in the 'result' list after the loops finish.
The outer loop runs n times, and each time it creates a list 'temp' of size n. These n lists are stored inside 'result', so total space is proportional to n * n = nΒ².
Which data structure generally uses the least space to store n elements?
Think about the overhead each data structure has beyond just storing the elements.
Arrays store elements contiguously in memory without extra pointers, so they use the least space per element. Linked lists and trees require extra pointers, and hash tables need additional space for hashing and handling collisions.
Consider a function that takes an integer n and creates a list of all prime numbers less than n. What is the expected space complexity of this function?
def primes_less_than(n): primes = [] for num in range(2, n): is_prime = True for i in range(2, int(num**0.5) + 1): if num % i == 0: is_prime = False break if is_prime: primes.append(num) return primes
Recall the prime number theorem which estimates the number of primes less than a number n.
The prime number theorem states that the number of primes less than n is approximately n / log n. Since the function stores all these primes in a list, the space complexity is O(n / log n).