Data Structures Every Programmer Must Know

Learn the essential data structures: arrays, linked lists, stacks, queues, trees, hash maps, and graphs with practical examples.

General Intermediate ๐Ÿ“– 15 min

Arrays

Contiguous memory, O(1) access by index, O(n) insert/delete.

const arr = [1, 2, 3, 4, 5];
arr.push(6);      // O(1) amortized
arr.pop();        // O(1)
arr.splice(2, 1); // O(n) โ€” shifts elements
arr.includes(3);  // O(n) linear search

Stacks (LIFO)

class Stack {
  constructor() { this.items = []; }
  push(item) { this.items.push(item); }
  pop() { return this.items.pop(); }
  peek() { return this.items[this.items.length - 1]; }
  isEmpty() { return this.items.length === 0; }
}

// Use: undo operations, function call stack, bracket matching
function isBalanced(str) {
  const stack = [];
  const pairs = { ')': '(', ']': '[', '}': '{' };
  for (const char of str) {
    if ('([{'.includes(char)) stack.push(char);
    else if (pairs[char] !== stack.pop()) return false;
  }
  return stack.length === 0;
}

Queues (FIFO)

class Queue {
  constructor() { this.items = []; }
  enqueue(item) { this.items.push(item); }
  dequeue() { return this.items.shift(); }
  peek() { return this.items[0]; }
}

// Use: BFS, task scheduling, print queues

Hash Maps

// JavaScript Objects and Maps
const map = new Map();
map.set('name', 'Alice');
map.get('name');  // 'Alice'
map.has('name');  // true
map.delete('name');

// Common pattern: frequency counting
function countChars(str) {
  const freq = {};
  for (const char of str) {
    freq[char] = (freq[char] || 0) + 1;
  }
  return freq;
}

Trees

class TreeNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

// Binary Search Tree
class BST {
  constructor() { this.root = null; }
  
  insert(value) {
    const node = new TreeNode(value);
    if (!this.root) { this.root = node; return; }
    let current = this.root;
    while (true) {
      if (value < current.value) {
        if (!current.left) { current.left = node; return; }
        current = current.left;
      } else {
        if (!current.right) { current.right = node; return; }
        current = current.right;
      }
    }
  }
  
  search(value) {
    let current = this.root;
    while (current) {
      if (value === current.value) return current;
      current = value < current.value ? current.left : current.right;
    }
    return null;
  }
}

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free โ†’