Show 25 50 100
PDF
11 result(s) in Data Structure Clear

Index

Showing 11 topics
  1. What is a Data Structure
  2. Array
  3. Linked List
  4. Stack
  5. Queue
  6. Hash Table
  7. Binary Tree and Traversals
  8. Binary Search Tree (BST)
  9. Heap and Priority Queue
  10. Graph
  11. Trie
1 Index

A data structure is a way of organising and storing data so it can be used efficiently.

LinearNon-linear
Elements in a sequenceElements in a hierarchy or network
Array, Linked List, Stack, QueueTree, Graph, Heap

Static (fixed size, e.g. array) vs dynamic (grows at run time, e.g. linked list, vector).

Time complexity cheat sheet

StructureAccessSearchInsertDelete
ArrayO(1)O(n)O(n)O(n)
Linked ListO(n)O(n)O(1) at headO(1) at head
Stack / QueueO(n)O(n)O(1)O(1)
Hash Table—O(1) avgO(1) avgO(1) avg
BST (balanced)O(log n)O(log n)O(log n)O(log n)
Heaptop O(1)O(n)O(log n)O(log n)
2 Index

An array stores elements of the same type in contiguous memory. Access by index is O(1); inserting or deleting in the middle needs shifting, O(n).

Index-based access is O(1) because the address can be calculated

Index-based access is O(1) because the address can be calculated

C++ 9 lines
int arr[5] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);   // length = 5

// insert 99 at index 2 (shift right)
int a[6] = {10, 20, 30, 40, 50};
for (int i = 5; i > 2; i--) a[i] = a[i - 1];
a[2] = 99;                              // 10 20 99 30 40 50

int m[2][3] = {{1, 2, 3}, {4, 5, 6}};  // 2D array
3 Index

A linked list is a chain of nodes; each node holds data and a pointer to the next node. Size can grow at run time and insert/delete at the head is O(1), but there is no random access.

head → 10 → 20 → 30 → 40 → NULL

head → 10 → 20 → 30 → 40 → NULL

C++ 27 lines
struct Node {
    int data;
    Node *next;
    Node(int d) : data(d), next(nullptr) {}
};

void insertHead(Node *&head, int x) {
    Node *n = new Node(x);
    n->next = head;
    head = n;
}

void print(Node *head) {
    for (Node *cur = head; cur; cur = cur->next)
        cout << cur->data << " ";
}

Node* reverse(Node *head) {          // very common interview question
    Node *prev = nullptr;
    while (head) {
        Node *next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }
    return prev;
}
  • Singly — next pointer only.
  • Doubly — next and prev pointers.
  • Circular — last node points back to the first.

Q & A

  1. Array vs linked list?
    Array: contiguous, O(1) index access, fixed size, costly insert/delete. Linked list: scattered nodes, O(n) access, dynamic size, O(1) insert/delete when you already have the node.
  2. How to find the middle of a linked list?
    Slow and fast pointers: slow moves 1 step, fast moves 2 steps. When fast reaches the end, slow is at the middle.
  3. How to detect a cycle?
    Floyd's algorithm: the same slow/fast pointers meet inside the loop if there is a cycle.
4 Index

A stack is LIFO (Last In, First Out). Operations: push, pop, top/peek, isEmpty, all O(1).

Uses: function call stack, undo, browser back button, expression evaluation, balanced parentheses, DFS.

Stack removes the newest item, queue removes the oldest

Stack removes the newest item, queue removes the oldest

Balanced parentheses C++ 14 lines
bool isBalanced(string s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '{' || c == '[') st.push(c);
        else {
            if (st.empty()) return false;
            char t = st.top(); st.pop();
            if ((c == ')' && t != '(') || (c == '}' && t != '{') || (c == ']' && t != '['))
                return false;
        }
    }
    return st.empty();
}
// isBalanced("{[()]}") → true,  isBalanced("(]") → false
Stack using an array C++ 3 lines
int st[100], top = -1;
void push(int x) { if (top < 99) st[++top] = x; }      // overflow check
int  pop()       { return top >= 0 ? st[top--] : -1; } // underflow check
5 Index

A queue is FIFO (First In, First Out): insert at the rear (enqueue), remove from the front (dequeue).

  • Circular queue — reuses empty slots at the start: rear = (rear + 1) % size.
  • Deque — insert/remove at both ends.
  • Priority queue — highest priority leaves first (usually a heap).

Uses: CPU scheduling, printer queue, BFS, buffering.

C++ 5 lines
queue<int> q;
q.push(10); q.push(20); q.push(30);
cout << q.front();   // 10
q.pop();             // removes 10
cout << q.size();    // 2
6 Index

A hash table maps keys to values using a hash function that turns a key into an array index. Two keys with the same index cause a collision.

  • Chaining — each slot keeps a list of entries.
  • Open addressing — find another free slot (linear probing, quadratic probing, double hashing).
  • Load factor = items / slots; when it gets high the table is resized (rehashing).

Collision handled by chaining

Collision handled by chaining

Counting frequency with a hash map C++ 4 lines
unordered_map<string, int> freq;
for (string w : {"a", "b", "a", "c", "a"})
    freq[w]++;
cout << freq["a"];   // 3
7 Index

A binary tree is a tree where each node has at most two children. Terms: root, leaf, parent, child, height, depth, level.

  • Full — every node has 0 or 2 children.
  • Complete — all levels full except possibly the last, filled from the left.
  • Perfect — all internal nodes have 2 children and all leaves are at the same level (2h+1 − 1 nodes).
  • Balanced — height is O(log n), e.g. AVL, Red-Black tree.
C++ 22 lines
struct Node {
    int val;
    Node *left, *right;
    Node(int v) : val(v), left(nullptr), right(nullptr) {}
};

void inorder(Node *r)   { if (!r) return; inorder(r->left); cout << r->val << " "; inorder(r->right); }   // L N R
void preorder(Node *r)  { if (!r) return; cout << r->val << " "; preorder(r->left); preorder(r->right); } // N L R
void postorder(Node *r) { if (!r) return; postorder(r->left); postorder(r->right); cout << r->val << " "; } // L R N

int height(Node *r) { return r ? 1 + max(height(r->left), height(r->right)) : 0; }

void levelOrder(Node *root) {          // BFS
    queue<Node*> q;
    if (root) q.push(root);
    while (!q.empty()) {
        Node *cur = q.front(); q.pop();
        cout << cur->val << " ";
        if (cur->left) q.push(cur->left);
        if (cur->right) q.push(cur->right);
    }
}
8 Index

In a BST every left subtree value is smaller and every right subtree value is larger than the node. Inorder traversal gives sorted output. Search/insert/delete are O(log n) when balanced, O(n) when skewed.

A balanced BST with 7 nodes

A balanced BST with 7 nodes

C++ 14 lines
Node* insert(Node *root, int x) {
    if (!root) return new Node(x);
    if (x < root->val) root->left = insert(root->left, x);
    else               root->right = insert(root->right, x);
    return root;
}

bool search(Node *root, int x) {
    while (root) {
        if (x == root->val) return true;
        root = (x < root->val) ? root->left : root->right;
    }
    return false;
}

Delete: leaf → remove; one child → replace with the child; two children → replace with the inorder successor (smallest in the right subtree), then delete that successor.

9 Index

A heap is a complete binary tree stored in an array. Max-heap: parent ≥ children (largest on top). Min-heap: parent ≤ children.

Insert and remove-top are O(log n), reading the top is O(1). Building a heap from n items is O(n). Used in heap sort, Dijkstra, scheduling, top-K problems.

The same heap as a tree and as an array

The same heap as a tree and as an array

C++ 6 lines
priority_queue<int> maxHeap;                              // largest on top
priority_queue<int, vector<int>, greater<int>> minHeap;   // smallest on top

for (int x : {5, 1, 8, 3}) { maxHeap.push(x); minHeap.push(x); }
cout << maxHeap.top();   // 8
cout << minHeap.top();   // 1
10 Index

A graph G = (V, E) is a set of vertices connected by edges. Types: directed / undirected, weighted / unweighted, cyclic / acyclic (DAG), connected / disconnected.

The same graph stored as an adjacency list

The same graph stored as an adjacency list

Adjacency list C++ 8 lines
int V = 5;
vector<vector<int>> adj(V);
auto addEdge = [&](int u, int v) {
    adj[u].push_back(v);
    adj[v].push_back(u);   // remove this line for a directed graph
};
addEdge(0, 1); addEdge(0, 2); addEdge(1, 3);
addEdge(2, 3); addEdge(1, 4); addEdge(3, 4);

BFS and DFS traversal are in the Algorithm category.

11 Index

A trie (prefix tree) stores strings character by character. Insert and search take O(length of word). Used for autocomplete, spell check and prefix search.

C++ 21 lines
struct TrieNode {
    TrieNode *child[26] = {};
    bool isEnd = false;
};

void insert(TrieNode *root, const string &w) {
    for (char c : w) {
        int i = c - 'a';
        if (!root->child[i]) root->child[i] = new TrieNode();
        root = root->child[i];
    }
    root->isEnd = true;
}

bool search(TrieNode *root, const string &w) {
    for (char c : w) {
        root = root->child[c - 'a'];
        if (!root) return false;
    }
    return root->isEnd;
}