Junior
How long does a solution using the built-in sorted function take? Can a faster solution be devised?
sobes.tech AI
Answer from AI
The built-in sorted function in Python operates in O(n log n) time, where n is the number of elements in the list. This is the optimal time for comparison-based sorting in the general case.
If the problem allows for more specialized algorithms (for example, counting sort if the elements are integers within a limited range), it can achieve O(n) time.
An example of a faster solution for sorting integers within a range:
# Counting sort for numbers from 0 to 100
def counting_sort(arr):
count = [0] * 101
for num in arr:
count[num] += 1
sorted_arr = []
for num, c in enumerate(count):
sorted_arr.extend([num] * c)
return sorted_arr
If the data does not suit such algorithms, then sorted is the optimal choice.