My understanding is the following:
Time = With the initial not state is just to check if there are no elements in the list a
. This is done in O(1) time. The first loop enumerates the second list b
with the operation append()
which is done in O(1) time therefore the first loop is O(n). The second loop I am confused if the sorting plays a factor since I know the sort method is O(nlogn) time. Within the second loop I am a bit confused about the operations as far as what it is specifically doing which I wanted to ask about although I do understand the fact that if the i-th element in a
is < c it goes into the if statement.
Space = Overall I think it is O(n) as the only additional space needed was the list x
plus the input space and the length of x
grows as a
or b
grows.
Given the following Python code:
a = [3, 1, 2] # input length will be size n
b = [1, 2, 3] # input length will be size n
c = 4
def foo(a, b, c):
res = 0
if not a:
return res
x = []
for i, j in enumerate(b):
x.append((j, i))
for j, i in sorted(x, reverse=True):
if a[i] < c:
res += a[i] * j
c -= a[i]
else:
res += c * j
break
return res
Can someone help go over what the time and space complexity is plus the idea behind it mainly?
space coplexity
? $\endgroup$