Array vs Linked List

This article is a complementary resource to the DSA with C++ course.

Array vs Linked List

Both array and linked list are widely used data structures. However, there are situations in which one is preferable over the other.

In this article, we'll explore the differences between an array and a linked list and discuss the optimal use cases for both.


Array

An array is a collection of data of the same type. For example, consider a collection of marks scored by students. Each score is an integer, meaning it's an array of marks.

An Array
An Array

Advantages of Arrays

The main advantage of an array is its fast lookup and insertion. Through indexing, we can access and insert (update) elements in an array in constant time, O(1).

Disadvantages of Arrays

Arrays have fixed sizes. So, they're not very useful in scenarios where we don't know the exact number of elements involved:

  • If we set a very small size, we cannot include all the elements in our array.
  • If we set a very large size, we waste lots of memory.

Linked List

A linked list is a linear data structure where elements, known as nodes, are stored in a sequence.

Each node contains two parts:

  1. Data
  2. Pointer to the next node in the sequence.
A Linked List
A Linked List

Advantages of Linked Lists

The main advantage of a linked list is its dynamic size.

Unlike arrays, linked lists can grow and shrink in size as needed, making them ideal for scenarios where the number of elements is unknown or changes frequently.

Disadvantages of Linked Lists

One of the problems with linked lists is they do not allow for direct access to elements.

To access an element, you must traverse the list from the head node, which has a linear time complexity, O(n).


Takeaway

Now that we know the pros and cons of both data structures, let's discuss when each should be used.

When to Use Arrays:

  1. When the number of elements is known in advance.
  2. When faster lookup is required.

When to Use Linked Lists:

  1. When the number of elements is dynamic and can change frequently.