Linked List vs Array When to Choose Which in DSA C - Complexity Comparison
We want to understand how the time to do tasks changes when using linked lists or arrays.
Which data structure is faster for different operations?
Analyze the time complexity of these two simple operations: accessing an element and inserting at the start.
// Access element at index i in array
int getArrayElement(int arr[], int i) {
return arr[i];
}
// Insert element at start of linked list
void insertAtStart(struct Node** head, int val) {
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = *head;
*head = newNode;
}
The first gets an element by index in an array. The second adds a new node at the start of a linked list.
Look at what repeats or how many steps each operation takes.
- Primary operation: Accessing array element is direct; inserting in linked list changes pointers.
- How many times: Array access is one step; linked list insertion is also one step.
Accessing an array element stays quick no matter how big the array is.
| Input Size (n) | Approx. Operations for Access |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Inserting at the start of a linked list also takes the same small number of steps regardless of size.
| Input Size (n) | Approx. Operations for Insert |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Both operations take constant time, not growing with input size.
Time Complexity: O(1) for both operations
This means the time to do these tasks stays the same no matter how big the data is.
[X] Wrong: "Accessing any element in a linked list is as fast as in an array."
[OK] Correct: Linked lists need to follow nodes one by one to reach an element, so access time grows with size.
Knowing when to use arrays or linked lists shows you understand how data structure choices affect speed.
"What if we tried to insert an element in the middle of the linked list? How would the time complexity change?"
