ProgrammingHardTCS CodeVita · Infosys HackWithInfy
Timsort is the algorithm behind Python's sorted(). For an input that is already in ascending order, what is its running time?
- A. O(log n), because only the first element needs comparing
- B. O(n), because Timsort detects the existing run and does almost no comparisons beyond one pass
- C. O(n log n), the same as the worst case
- D. O(n^2), because the input is sorted
Correct answer: B. O(n), because Timsort detects the existing run and does almost no comparisons beyond one pass
Timsort finds natural runs in one linear pass. A fully sorted input is a single run, so it needs about n - 1 comparisons, which is the best case O(n).
More Python Programming questions
- What is printed? python print(10 17 in range(0, 10 18, 2), 10 17 + 1 in range(0, 10 18, 2))
- What is printed? python def add(x, memo={}): memo[x] = len(memo) return memo print(add(5), add(7))
- What is printed? python print(min('10', '9'), min(10, 9), max('10', '9', key=int))
- What is printed? python i = 'x' = [i for i in range(3)] print(i)
- What is printed? python print([y for x in range(5) if (y := x x) > 5])
- What is printed? python print(bin(10).count('1'), (10).bitcount(), (-10).bitcount())