Sobes.tech
Middle

What is the algorithmic complexity of search in List and Dictionary? How is the Dictionary implemented internally?

sobes.tech AI

Answer from AI

Algorithmic complexity:

  • Search in List (for example, List<T> in C#) — usually a linear search, complexity O(n), as it involves iterating through elements in order.

  • Search in Dictionary — average complexity O(1), as it uses a hash table.

Device of Dictionary:

Dictionary<TKey, TValue> in C# is implemented based on a hash table. The key is hashed using a hash function, which converts the key into an index of the bucket array. Each bucket contains a linked list or another structure to resolve collisions. When adding or searching for an element:

  1. Calculate the hash of the key.
  2. Determine the bucket by the hash.
  3. Search in the bucket by key (comparison using Equals).

This provides quick access to values by key, assuming good hash distribution.

Example:

var dict = new Dictionary<string, int>();
dict["apple"] = 5;
int value = dict["apple"]; // Fast access