DEV Community

Amar Gul
Amar Gul

Posted on

Linked Lists Finally Simple — Why Insert is O(1) When Arrays Are O(n)Uses This Algorithm for .sort()

Most developers understand arrays intuitively.
But Linked Lists feel abstract until you
see them visually.

The Core Problem with Arrays

When you insert in the middle of an array,
every element after the insertion point
must shift one position right.

With 1000 elements that means 999 shifts.
That's O(n) time.

How Linked Lists Solve This

A Linked List node contains two things:

  • The actual data value
  • A pointer to the next node

Insertion only updates 2 pointers:

\`javascript
// Point previous node to new node
prevNode.next = newNode;

// Point new node to next node

newNode.next = nextNode;
`\

That's it. O(1) time regardless of
list size.

The Trade Off

Fast insertion. Slow access.

Arrays: O(1) access by index
Linked Lists: O(n) access — must traverse

Choose based on your use case:

  • Frequent insertion/deletion → Linked List
  • Frequent access by index → Array

Built in React

Three operations animated:

  • Traverse — walks HEAD to TAIL
  • Insert — shows 2 pointer updates
  • Delete — shows pointer reconnection

\`javascript
async function insertMiddle() {
const insertPos = Math.floor(nodes.length / 2);

// Traverse to position
for (let i = 0; i <= insertPos; i++) {
setTraversing(i);
await addDelay(SPEED);
}

// Insert new node
setNodes(prev => {
const updated = [...prev];
updated.splice(insertPos, 0, newNode);
return updated;
});
}
`\

Watch It

What's Next

Binary Search Tree — self organizing
structure that achieves O(log n) for
search, insert and delete simultaneously.

Subscribe to AlgoCanvas:
👉 youtube.com/@AlgoCanvas

Top comments (0)