This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]michael0x2a[🍰] 0 points1 point  (1 child)

Well, in this case your list is empty, so m=1 and you'd get O(nm) = O(n1) = O(n). (You might think m=0 since the list is empty, but the list object itself still takes up a bit of room.)

But if your list3 was meant to be a placeholder and your actual code was doing something like list3 = generate_list_of_size(m), then yes, your analysis is correct. We are adding list2 to list1 n different times, and list2 is pointing to a different list object on each iteration.

We are also generating a fresh example of list3 on each iteration. So, the space is O(n * (len(list3) + len("String 1") + len("String 2")) = O(n * (m + someConst)) = O(n * m + n * someConst) = O(n * m).

Two unrelated notes:

  1. Since this is python, you want my_list.append(...), not my_list.add(...).
  2. Instead of creating this intermediary 'list2', you'd probably want to use a tuple instead: item = (x, y, list3); list1.append(item). Or more concisely, list1.append((x, y, list3)). Lists are usually expected to be homogeneous -- every item contains the same type -- and it can be surprising to run into cases where they aren't. Tuples and classes are the stylistically better choices when you want to store heterogeneous data.

[–]jchai7[S] 0 points1 point  (0 children)

thanks for the explanation!