Sobes.tech
Junior — Middle

What is the time complexity of the linear search algorithm for an element in a dictionary?

sobes.tech AI

Answer from AI

In Python, a dictionary (dict) is implemented based on a hash table, so operations to search for an element by key usually have an amortized time complexity of O(1) — constant time.

However, if we talk about linear search (for example, iterating over all dictionary elements to find by value or condition), the time complexity will be O(n), where n is the number of elements in the dictionary.

Example of linear search for a value in a dictionary:

my_dict = {'a': 1, 'b': 2, 'c': 3}

# Search for key by value 2
for key, value in my_dict.items():
    if value == 2:
        print(f'Found key: {key}')
        break

Here, iterating over all elements is a linear operation.