Sobes.tech
Junior — Middle

Can you explain what the time complexity of an algorithm means and give an example with O(n)?

sobes.tech AI

Answer from AI

The time complexity of an algorithm is an estimate of the number of operations (or time) that the algorithm performs depending on the size of the input data. It shows how the runtime of the algorithm changes as the volume of data increases.

The notation O(n) means that the algorithm's runtime grows linearly with the input size n. If the data doubles, the algorithm takes approximately twice as long.

An example in Python with linear complexity O(n):

def sum_list(numbers):
    total = 0
    for num in numbers:
        total += num
    return total

In this example, the function iterates through all elements of the list once, so the runtime is proportional to the length of the list.

Thus, time complexity helps evaluate the efficiency of an algorithm and choose the appropriate one for a task.