LinkedList usage in C Sharp (C#) - Time & Space Complexity
When using a linked list, it's important to know how the time to do tasks changes as the list grows.
We want to find out how fast operations like adding or searching run when the list gets bigger.
Analyze the time complexity of the following code snippet.
LinkedList<int> list = new LinkedList<int>();
for (int i = 0; i < n; i++)
{
list.AddLast(i); // Add item at the end
}
bool found = false;
foreach (int item in list)
{
if (item == target)
{
found = true;
break;
}
}
This code adds n items to a linked list, then searches for a target value by checking each item one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding items in a loop and searching through the list.
- How many times: Adding runs n times; searching can run up to n times in the worst case.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 adds + up to 10 checks |
| 100 | About 100 adds + up to 100 checks |
| 1000 | About 1000 adds + up to 1000 checks |
Pattern observation: The work grows directly with the number of items; doubling n roughly doubles the work.
Time Complexity: O(n)
This means the time to add and search grows in a straight line with the number of items.
[X] Wrong: "Searching a linked list is as fast as accessing an array element by index."
[OK] Correct: Linked lists do not allow direct access by position, so searching requires checking each item one by one, which takes longer as the list grows.
Understanding how linked lists work and their time costs helps you choose the right tool for the job and explain your choices clearly in interviews.
"What if we changed the search to use a Dictionary instead of a LinkedList? How would the time complexity change?"