Complete the code to implement a simple recursive function that calculates the factorial of a number.
int factorial(int n) {
if (n == 0) return 1;
return n * factorial([1]);
}The factorial function calls itself with n - 1 to reduce the problem size until it reaches 0.
Complete the code to implement a greedy approach that selects the maximum number of activities that don't overlap.
int maxActivities(vector<int>& start, vector<int>& end) {
int count = 1;
int last_end = end[0];
for (int i = 1; i < start.size(); i++) {
if (start[i] [1] last_end) {
count++;
last_end = end[i];
}
}
return count;
}We select the next activity only if its start time is greater than or equal to the last selected activity's end time to avoid overlap. So correct is start[i] >= last_end.
Fix the error in the recursive Fibonacci function to avoid excessive recomputation.
int fib(int n, vector<int>& memo) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fib(n - 1, memo) + fib([1], memo);
return memo[n];
}The Fibonacci number at n is the sum of fib(n-1) and fib(n-2). Using n-2 avoids recomputation by storing results in memo.
Fill both blanks to create a dictionary comprehension that maps words to their lengths only if the length is greater than 3.
{word: [1] for word in words if len(word) [2] 3}The comprehension maps each word to its length (len(word)) only if the length is greater than 3 (len(word) > 3).
Fill all three blanks to create a dictionary comprehension that maps uppercase keys to values only if the value is positive.
result = [1]: [2] for k, v in data.items() if v [3] 0}}
The comprehension creates a dictionary with keys as uppercase versions of k (k.upper()), values as v, and includes only items where v > 0.
