Skip to content

Latest commit

 

History

History

03_data_structures

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

Data Structures - Algorithm Implementations

Implement classic data structures and algorithms from scratch to understand their inner workings.


Project Ideas

1. Dynamic Array (Vector)

Difficulty: Beginner Time: 5-8 hours

Reimplement std::vector from scratch.

Features:

  • Push back/pop back
  • Random access
  • Size and capacity
  • Automatic resizing
  • Iterator support

Key Concepts:

  • Dynamic memory allocation
  • Template programming
  • Iterator pattern
  • Exception safety

2. Linked List

Difficulty: Beginner Time: 5-8 hours

Singly and doubly linked list implementations.

Features:

  • Insert at head/tail/middle
  • Remove by value
  • Reverse list
  • Detect cycles
  • Merge sorted lists

Key Concepts:

  • Pointer manipulation
  • Memory management
  • Recursive algorithms
  • Node structure

3. Stack and Queue

Difficulty: Beginner Time: 3-5 hours

Stack (LIFO) and Queue (FIFO) implementations.

Features:

  • Push/pop/enqueue/dequeue
  • Peek front/top
  • Check empty
  • Size tracking

Key Concepts:

  • Container adapters
  • Template design
  • Encapsulation
  • Interface design

4. Hash Table

Difficulty: Intermediate Time: 10-15 hours

Implement hash map with collision handling.

Features:

  • Insert/remove/lookup
  • Collision resolution (chaining/probing)
  • Dynamic resizing
  • Load factor management
  • Hash functions

Key Concepts:

  • Hash functions
  • Collision handling
  • Load factor
  • Rehashing
  • Array of buckets

5. Binary Search Tree (BST)

Difficulty: Intermediate Time: 10-15 hours

Classic BST with standard operations.

Features:

  • Insert/remove/search
  • Inorder/preorder/postorder traversal
  • Find min/max
  • Check balanced
  • Tree height

Key Concepts:

  • Tree structure
  • Recursive algorithms
  • Node relationships
  • Traversal methods

6. AVL Tree

Difficulty: Intermediate-Advanced Time: 15-20 hours

Self-balancing binary search tree.

Features:

  • BST operations
  • Auto-balancing
  • Rotations (LL, RR, LR, RL)
  • Balance factor tracking
  • Height updates

Key Concepts:

  • Balance factor
  • Tree rotations
  • Recursive updates
  • AVL properties

7. Priority Queue (Heap)

Difficulty: Intermediate Time: 10-15 hours

Binary heap implementation.

Features:

  • Insert/extract min/max
  • Peek at top
  • Build heap from array
  • Heap sort
  • Decrease/increase key

Key Concepts:

  • Complete binary tree
  • Array representation
  • Heapify operations
  • Parent/child relationships

8. Graph Data Structures

Difficulty: Intermediate-Advanced Time: 15-25 hours

Adjacency list and matrix implementations.

Features:

  • Add/remove vertices/edges
  • BFS traversal
  • DFS traversal
  • Shortest path (Dijkstra)
  • Minimum spanning tree (Prim/Kruskal)
  • Topological sort

Key Concepts:

  • Graph representations
  • Traversal algorithms
  • Pathfinding
  • Graph algorithms

9. Trie (Prefix Tree)

Difficulty: Intermediate Time: 10-15 hours

Tree-like structure for strings.

Features:

  • Insert word
  • Search word
  • Search prefix
  • Delete word
  • Auto-complete suggestions
  • Word count

Key Concepts:

  • Prefix matching
  • Trie nodes
  • Character traversal
  • Space efficiency

10. LRU Cache

Difficulty: Intermediate-Advanced Time: 15-20 hours

Least Recently Used cache implementation.

Features:

  • Get/put operations
  • Capacity limit
  • Eviction policy
  • O(1) operations
  • Access tracking

Key Concepts:

  • Hash map + doubly linked list
  • Cache eviction
  • O(1) access
  • Move-to-front

Implementation Template

Generic Data Structure

// data_structure.h
#ifndef DATA_STRUCTURE_H
#define DATA_STRUCTURE_H

#include <memory>
#include <iterator>

template<typename T>
class DataStructure {
public:
    // Types
    using value_type = T;
    using reference = T&;
    using const_reference = const T&;
    using size_type = size_t;

    // Iterator
    class iterator {
        // Iterator implementation
    };

    // Constructors
    DataStructure();
    explicit DataStructure(size_type capacity);
    DataStructure(const DataStructure& other);
    DataStructure(DataStructure&& other) noexcept;
    ~DataStructure();

    // Assignment
    DataStructure& operator=(const DataStructure& other);
    DataStructure& operator=(DataStructure&& other) noexcept;

    // Capacity
    size_type size() const noexcept;
    size_type capacity() const noexcept;
    bool empty() const noexcept;

    // Element access
    reference operator[](size_type index);
    const_reference operator[](size_type index) const;
    reference at(size_type index);
    const_reference at(size_type index) const;
    reference front();
    const_reference front() const;
    reference back();
    const_reference back() const;

    // Modifiers
    void push_back(const value_type& value);
    void push_back(value_type&& value);
    void pop_back();
    void clear() noexcept;

    // Iterators
    iterator begin() noexcept;
    iterator end() noexcept;

    // Comparison
    bool operator==(const DataStructure& other) const;
    bool operator!=(const DataStructure& other) const;

private:
    // Implementation details
    std::unique_ptr<T[]> data_;
    size_type size_;
    size_type capacity_;
};

#endif // DATA_STRUCTURE_H

Algorithm Implementations

Sorting Algorithms

// Bubble Sort
template<typename T>
void bubbleSort(T* arr, size_t n) {
    for (size_t i = 0; i < n - 1; ++i) {
        for (size_t j = 0; j < n - i - 1; ++j) {
            if (arr[j] > arr[j + 1]) {
                std::swap(arr[j], arr[j + 1]);
            }
        }
    }
}

// Quick Sort
template<typename T>
void quickSort(T* arr, int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

// Merge Sort
template<typename T>
void mergeSort(T* arr, int left, int right) {
    if (left < right) {
        int mid = left + (right - left) / 2;
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }
}

Search Algorithms

// Binary Search
template<typename T>
int binarySearch(const T* arr, size_t n, const T& target) {
    int left = 0;
    int right = n - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == target) {
            return mid;
        }
        if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return -1; // Not found
}

// Linear Search
template<typename T>
int linearSearch(const T* arr, size_t n, const T& target) {
    for (size_t i = 0; i < n; ++i) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}

Testing Data Structures

Unit Test Template

#include <cassert>
#include <iostream>

void testDataStructure() {
    // Test construction
    DataStructure<int> ds;
    assert(ds.empty());
    assert(ds.size() == 0);

    // Test insertion
    ds.push_back(1);
    ds.push_back(2);
    ds.push_back(3);
    assert(ds.size() == 3);
    assert(!ds.empty());

    // Test access
    assert(ds[0] == 1);
    assert(ds.front() == 1);
    assert(ds.back() == 3);

    // Test bounds checking
    bool caught = false;
    try {
        ds.at(10);
    } catch (const std::out_of_range&) {
        caught = true;
    }
    assert(caught);

    // Test copy
    DataStructure<int> copy = ds;
    assert(copy == ds);

    // Test move
    DataStructure<int> moved = std::move(ds);
    assert(moved.size() == 3);
    assert(ds.size() == 0);

    std::cout << "All tests passed!\n";
}

int main() {
    testDataStructure();
    return 0;
}

Performance Analysis

Complexity Reference

Data Structure Insert Delete Search Space
Dynamic Array O(1)* O(n) O(1) O(n)
Linked List O(1)* O(n) O(n) O(n)
Hash Table O(1) avg O(1) avg O(1) avg O(n)
BST O(h) O(h) O(h) O(n)
AVL Tree O(log n) O(log n) O(log n) O(n)
Heap O(log n) O(log n) O(1) O(n)

*amortized

Profiling Template

#include <chrono>

template<typename Func, typename... Args>
auto profile(const std::string& name, Func func, Args&&... args) {
    auto start = std::chrono::high_resolution_clock::now();
    auto result = func(std::forward<Args>(args)...);
    auto end = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    std::cout << name << " took " << duration.count() << " microseconds\n";

    return result;
}

// Usage
auto result = profile("Binary Search", binarySearch<int>, arr, n, target);

Project Checklist

For each data structure:

Core Implementation

  • Basic structure (node, data members)
  • Constructors/destructor
  • Copy/move operations
  • Core operations (insert, remove, find)
  • Iterator support

Advanced Features

  • Const correctness
  • Exception safety
  • Allocator support
  • STL-compatible interface

Testing

  • Unit tests for all operations
  • Edge cases (empty, single element)
  • Performance benchmarks
  • Comparison with STL

Documentation

  • API documentation
  • Usage examples
  • Complexity analysis
  • Visual diagrams

Learning Path

  1. Start simple - Dynamic array, linked list
  2. Build up - Stack, queue, hash table
  3. Trees - BST, AVL, trie
  4. Graphs - Adjacency structures, algorithms
  5. Advanced - Skip lists, B-trees, bloom filters

Ready to implement? Pick a data structure and start coding! 🏗️