0

I'm struggling to figure out what the time complexity for this code would be.

def under_ten(input_list : List[int]) -> List[int]:
    res = []
    for i in input_list:
        if i < 10:
            res.append(i)

    res.sort()
    return res

Since the loop iterates over every element of n, I think the best case should be O(n). What I'm not sure about is how sorting the result list affects the time complexity of the entire function. Is the worst case O(nlogn) (all numbers in n are under 10, so the result list is the same size as the input list)? And what would be the average case?

EDIT: Changed input name from n to input_list and added type hints, sorry if that caused some confusion (added type hints as well).

  • Which sorting algorithm do you use? – Nico Haase Nov 02 '20 at 14:59
  • If `n` is a list, you should not be writing `O(n)`. –  Nov 02 '20 at 15:27
  • Replace the call to `sort` by a simple counting sort, and you get `O(input_list.length)` worst-case complexity. BTW, it's unclear what you mean by `n` in `O(n)` since you haven't defined `n`. – Mo B. Nov 02 '20 at 21:35

2 Answers2

2

Your first observation is correct that iterating the input collection would be an O(N) operation, where N here is the length of the array called n. The running time of the sort operation at the end would depend on how large the res array is. In the worst case scenario, every number in n would be less than 10, and therefore would end up in res. The internal algorithm Python would be using for sort() would likely be either quicksort or mergesort (q.v. this SO question). Both of these algorithms use a divide-and-conquer approach which run in O(N*lgN). So, in the worst case, your under_ten() function would run in O(N*lgN).

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • OP tricked you with weird variable names. n is an iterator or container. Time complexity would depend on N=len(n) But of course you are correct that it would be O(N log N) because of the sort. – Kenny Ostrom Nov 02 '20 at 15:12
  • I'll note that this function could be re-written in O(N*N) by prepending to res, or it could be re-written in O(N) using a non-comparison-based sort, thanks to the limited range of values. – Kenny Ostrom Nov 02 '20 at 15:14
  • The behavior of Quicksort is well-known to be O(N²), whatever the pivot selection strategy. –  Nov 02 '20 at 15:41
0

Let N be the length of the list and K the number of elements smaller than 10.

The complexity is O(N + K log K), assuming that append is done in amortized constant time.

In the worst case, K=N, hence O(N Log N), provided the sort truly has a worst case O(N Log N). Otherwise, it could be O(N²).