r/AskComputerScience • u/LLeoparden • Apr 01 '26
Algorithms course exam inquiry
So i had this algorithm exam and there was this question and i really dont understand the answer
Just for clarification I already had this exam and the picture is from the answers that was sent to us after, i am not trying to cheat or anything like that (subreddit rules)
Even chatgbt and claude dont give me a good answer when i asked them
Here is the question
So basically in the 4th part of the question (whats the worstcase complexity of the entire code)
My thought process is that either the while loop runs completely or the second recursion works (in the last line of the left part),
Why?, if the while loop runs completely then the I is at 0 or 1 which would satisfy the condition at the start of the function (n<2) making it return
By that logic
The time of the while code is T(n)=2T(N/2) + O(n^3)
The power 3 is:
N for the for loop
N for the while loop
And N for the check in array
By using masters its n vs n^3
so it should be n^3
Thats my explanation
Can you pls tell me where i went wrong cuz i don’t understand at all
Thanks in advance
View all comments
Show parent comment
1
u/PiVMaSTeR Apr 01 '26
Why does I need to be less than 2 by the end of the for loop? Consider A = [10k , 10k + 1, ...., 10k + 10k*n]. A is definitely of size O(n), but the lowest I will go at the root call is 10k - 1. The bottom half of the recursive call will run for a bit still.
Also note that even if I is not in A, you will still need Theta(n^2) for the for-loop and the check to see if I is in A for every recursive call.
Hence, the recurrence is really T(n) = 4 * T(n/2) + Theta(n^2). It's easiest to reason with I = N. By case 2 of the master theorem you end up with T(n) = Theta(n^2 log(n)).