0

Suppose we have the following function:

def sort_list(list_of_strings):
    """Take a list of strings, sort the letters in each string,
    and then sort the full list. The list is modified in place."""
    for i in range(len(list_of_strings)):
        list_of_strings[i] = ''.join(sorted(list_of_strings[i]))
    list_of_strings.sort()

Would it be correct to say that this has big-O notation of O(n) because the length of time it takes for the function to run depends on the length of list_of_strings?

  • This says that yes, the length of time increases linearly with the size of the list, so it is O(n)? [What is a plain English explanation of "Big O" notation?](https://stackoverflow.com/questions/487258/what-is-a-plain-english-explanation-of-big-o-notation) – JeffUK Nov 29 '20 at 19:51
  • The complexity of this is determined by both the length of `list_of_strings` and the lengths of the items in `list_of_strings` since you are sorting those. In general you can't sort arbitrary things faster than `O(nlogn)` so I think it is misleading to call this function `O(n)`. – Mark Nov 29 '20 at 19:56
  • Since you are actually working on each element of your list, your input size is not simply the number of elements in `list_of_strings`, but the combined *length* of those elements. – chepner Nov 29 '20 at 20:06

1 Answers1

0

Sorting a list of size N takes O(N * log(N)) time (generally, it depends on the exact input and the algorithm used, but Python's builtin sorting functions don't do worse than that).

Doing something in a loop multiplies the runtime, and doing things sequentially means adding the runtime together.

This means, given N = len(list_of_strings) and M = max(len(string) for string in list_of_strings), the runtime for the loop is N * O(M * log(M)) = O(N * M * log(M)), and the bit afterwards is O(N * log(N)), which means the runtime for sort_list is O(N * M * log(M) + N * log(N)).

Jasmijn
  • 9,370
  • 2
  • 29
  • 43