简体   繁体   中英

Space Complexity with no variables defined

What is the space complexity of this code (it finds out how many negative numbers are in nested lists of integers)? Is it O(1) since no variables are defined, or is it O(n) due to the list comprehensions?

def foo(forest: list[list[int]]) -> int:
    return sum([1 for tree in forest for leaf in tree if leaf<0])

Just to confirm as well, this program has a time complexity of O(n 2 ) right?

Thanks!

First, what is the n here?

I think there are two different variables of importance here, I'll call them M = len(forest) and K = max(len(tree) for tree in forest) .

Then the time complexity would be O(MK).

Next, the list you are constructing has a length of O(MK), so its space complexity is the same as the time complexity.

You can avoid that by using a generator expression instead of a list comprehension, like so:

return sum(1 for tree in forest for leaf in tree if leaf < 0)

This avoids having to store every value, only generating a single value at a time when calculating the sum, so its additional space complexity would be O(1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM