1. Home
  2. Explore
  3. Computer Science
  4. Data Structures Introduction

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Data Structures Introduction

Data Structures: Comprehensive Study Notes

What is a Data Structure?

A data structure is a way to store, organize, and manage information so that a programmer can easily access or modify the values within it. Data structures and the algorithms used to interact with them provide the backbone for nearly all programs.

Each data structure is designed for storing information and allowing efficient access and manipulation, but each differs in how it accomplishes this. Common basic structures include arrays and array lists (called lists in Python), but more advanced structures enable features like undo/redo, mapping, autocomplete, and more.

Measuring Efficiency: Big O Notation

To compare data structures quantifiably, we use Big O notation — a time complexity equation that scores how efficiently a data structure performs key tasks. The four criteria used for scoring are:

  • Access a specific element

  • Search for a particular element

  • Insert an element

  • Remove an element

Each criterion is modeled by an equation that takes the size of the data set (an integer nnn) and returns the number of operations needed to complete the task. We always use the worst-case scenario when judging data structures.

Big O notation levels the playing field by measuring operations rather than time, eliminating bias from different hardware speeds.

Common Time Complexity Equations (from most to least efficient)

  1. O(1) — Constant Time
    No matter the size of the data set (nnn), the task completes in a single step. This is the gold standard.
    Example graph: a horizontal line at 1 operation.

  2. O(log n) — Logarithmic Time
    Very fast. As nnn increases, the number of operations increases much more slowly. The larger the data set, the more "bang for your buck."
    Example: binary search.

  3. O(n) — Linear Time
    For every element added, the number of operations increases by the same amount. This is the last "good" efficiency level.
    Example: linear search through an unsorted list.

  4. O(n log n)
    Relatively inefficient. The slope increases as data volume grows.

  5. O(n²) and O(2ⁿ)
    Both are exponential and very inefficient. Should be avoided if possible.

Big O notation is incredibly useful, but it should not be the only factor when choosing a data structure — many structures have special features that make them useful despite seemingly poor efficiency.


Section 1: Basic Data Structures

Arrays

An array is a list of similar values grouped together contiguously in memory. Every item in an array is an element.

Three Attributes of an Array

  • Name — used to reference the array.

  • Type — all elements must be the same type (e.g., all integers, all strings).

  • Size — fixed upon creation; cannot be changed using conventional methods.

Parallel Arrays

Two or more arrays with the same number of elements where each element in one array corresponds to the element at the same index in another array. This allows storing related but different data types (e.g., names in one array, salaries in another).

Instantiating an Array

  1. Populating at creation — used when values are known ahead of time.
    Syntax varies by language but generally: arrayName = [value1, value2, ...]

  2. Setting a size first — used when values will be provided later (e.g., user input).
    Syntax typically: type[] arrayName = new type[size]

Indexing

Elements are accessed by a numerical index, which begins at 0, not 1.
To retrieve an element: arrayName[index]
To change an element: arrayName[index] = newValue

Attempting to access an index outside the array bounds causes an array out of bounds error.

Two-Dimensional Arrays

An array where each element is itself an array (like a matrix). Accessed with two indices: arrayName[row][column].

Time Complexity of Arrays

Operation

Complexity

Reason

Access

O(1)

Contiguous memory allows instant calculation of any element's location using the base address plus index.

Search

O(n)

Worst case: the target element is the last one (linear search).

Insert

O(n)

Worst case: inserting at index 0 requires shifting all elements right.

Delete

O(n)

Worst case: deleting at index 0 requires shifting all elements left.

Advantages and Disadvantages of Arrays

  • Advantages: Constant-time access; simple and built into most languages.

  • Disadvantages: Fixed size; inserting/deleting can be slow; wasted memory if not full.


ArrayLists

An ArrayList is a resizable array backed by an array in memory. Its size expands dynamically as needed.

Initialization

In languages like Java and C#, ArrayLists are separate classes. Common initialization: ArrayList<Type> name = new ArrayList<Type>();
A default capacity (often 10) is set but can be grown dynamically.

Common ArrayList Methods

  1. Add(object) — appends to the end.

  2. Add(index, object) — inserts at a specific index, shifting elements right.

  3. Remove(index) — removes and returns the element at that index.

  4. Remove(object) — removes the first occurrence of the object; returns true/false.

  5. Get(index) — returns the element at that index.

  6. Set(index, object) — replaces the element at that index.

  7. Clear() — removes all elements.

  8. ToArray() — converts the ArrayList to an array.

How ArrayList Achieves O(1) Access

Although the actual data objects may be stored non-contiguously, the ArrayList stores references (pointers) to those objects in a contiguous array of references. Accessing by index returns the reference instantly, which then points to the actual object.

Time Complexity of ArrayLists

Operation

Complexity

Reason

Access

O(1)

Same as array (contiguous references).

Search

O(n)

Worst case: target at end.

Insert

O(n)

Worst case: inserting at beginning requires shifting all references.

Delete

O(n)

Worst case: deleting first element requires shifting all references left.

Array vs. ArrayList Comparison

  • Array has fixed size; ArrayList has dynamic size.

  • Array can store primitives and objects; ArrayList stores only objects (autoboxing partially solves this).

  • Array is built-in with no pre-made methods; ArrayList is a class with many built-in methods.

  • Array uses less memory and is faster; ArrayList requires more space and time due to class overhead.

Use arrays for small tasks with little data modification; use ArrayLists for interactive programs where data changes frequently.


Section 2: Intermediate Data Structures

Random Access vs. Sequential Access

  • Random access data structures — any element can be accessed directly in constant time (e.g., arrays, ArrayLists). Each element is independent.

  • Sequential access data structures — elements can only be accessed in a particular order, each dependent on others (e.g., stacks, queues, linked lists). Also called limited access data structures.

Stacks

A stack is a sequential access data structure that follows the LIFO (Last In, First Out) principle. Elements are added and removed only from the top.

Common Stack Methods

  1. Push(object) — adds an object to the top.

  2. Pop() — removes and returns the top element.

  3. Peek() — returns the top element without removing it.

  4. Contains(object) — returns true/false whether the object exists in the stack (without removing elements).

Time Complexity of Stacks

Operation

Complexity

Reason

Access

O(n)

Must pop all elements above the target to reach it.

Search

O(n)

Worst case: target at bottom, must pop entire stack.

Insert (push)

O(1)

Simply add to top.

Delete (pop)

O(1)

Simply remove from top.

Uses of Stacks

  • Recursion — function calls are pushed onto a call stack; when a base case is reached, calls are popped off.

  • Undo/redo in word processors.

  • Back button in web browsers.

  • Keeping track of active subroutines.


Queues

A queue is a sequential access data structure that follows the FIFO (First In, First Out) principle. Elements are added at the tail (back) and removed from the head (front).

Common Queue Methods

  1. Enqueue(object) — adds an object to the tail.

  2. Dequeue() — removes and returns the object at the head.

  3. Peek() — returns the head object without removing it.

  4. Contains(object) — returns true/false whether the object exists in the queue.

Time Complexity of Queues

Operation

Complexity

Reason

Access

O(n)

Must dequeue all elements in front of target.

Search

O(n)

Worst case: target at tail, must traverse entire queue.

Insert (enqueue)

O(1)

Simply add to tail.

Delete (dequeue)

O(1)

Simply remove from head.

Uses of Queues

  • Job scheduling — the computer determines which tasks to complete first.

  • Printer spooling — determining whose documents print first.

  • Zero shutter lag in cameras (e.g., Google Pixel).

  • Any scenario requiring fair, ordered processing.


Linked Lists

A linked list is a sequential access linear data structure where each element is a separate object called a node. Each node contains two parts:

  • Data — the actual value stored.

  • Pointer (reference) — points to the next node in the list.

The last node (tail) points to null, indicating the end of the list. The first node is the head.

Node Structure

[Data | Pointer] → [Data | Pointer] → [Data | null]

Adding and Removing Nodes

1. Adding to the head

  • Set the new node's pointer to the current head.

  • The new node becomes the head.

2. Removing from the head

  • Set the head's pointer to null, isolating it.

3. Adding to the middle (after a given node)

  • Set the new node's pointer to the node after the insertion point.

  • Set the previous node's pointer to the new node.

4. Removing from the middle

  • Set the previous node's pointer to the node after the one being removed.

  • Set the removed node's pointer to null.

5. Adding to the tail

  • Set the current tail's pointer to the new node.

  • The new node's pointer becomes null.

6. Removing from the tail

  • Set the second-to-last node's pointer to null.

Time Complexity of Linked Lists

Operation

Complexity

Reason

Access

O(n)

Must traverse from head to desired node.

Search

O(n)

Must traverse potentially entire list.

Insert (head or tail)

O(1)

Direct pointer manipulation.

Insert (middle)

O(n)

Must traverse to insertion point first.

Delete (head or tail)

O(1)

Direct pointer manipulation.

Delete (middle)

O(n)

Must traverse to node before target first.

Uses of Linked Lists

  • Backing other data structures (stacks, queues).

  • Music player queues — each song node contains data and a pointer to the next.

  • Photo viewing software — each image is a node.

Limitation of Singly Linked Lists

Traversal can only go forward — there is no pointer to the previous node. This is solved by the doubly linked list.


Doubly Linked Lists

A doubly linked list is similar to a linked list but each node contains two pointers:

  • Next — points to the next node.

  • Previous (prev) — points to the previous node.

This allows traversal in both directions.

Adding and Removing Nodes (Doubly Linked List)

Adding to the head

  1. Set new node's prev to null.

  2. Set new node's next to current head.

  3. Set current head's prev to new node.

Removing from the head

  1. Set head's next to null.

  2. Set second node's prev to null.

Adding to the middle

  1. Set new node's prev to the node before insertion point.

  2. Set new node's next to the node after insertion point.

  3. Set previous node's next and next node's prev to the new node.

Removing from the middle

  1. Set previous node's next to the node after the target.

  2. Set next node's prev to the node before the target.

  3. Set target's pointers to null.

Adding to the tail

  1. Set current tail's next to new node.

  2. Set new node's prev to current tail.

  3. Set new node's next to null.

Removing from the tail

  1. Set tail's prev to null.

  2. Set second-to-last node's next to null.

Time Complexity of Doubly Linked Lists

Same as singly linked lists: O(n) for access and search; O(1) for insert/delete at head or tail; O(n) for insert/delete in middle.

Uses of Doubly Linked Lists

  • Browser caches (back/forward navigation).

  • Undo/redo functionality.

  • "Open recent" features in applications.

  • Any scenario requiring bidirectional traversal.


Dictionaries (Maps / Associative Arrays)

A dictionary is an abstract data structure that stores data in key-value pairs. Each value is associated with a unique key. Dictionaries use keys for indexing instead of numerical indices.

Key Restrictions

  1. Each key must be unique — no duplicate keys allowed.

  2. Each key can have only one value — but values can be duplicated across different keys.

Keys can be any primitive type (int, string, etc.). Values can be any type, including other dictionaries.

Hash Tables (Mini Lesson)

Most dictionaries are implemented using a hash table. A hash table uses a hash function to map keys to specific index locations in an underlying array. This mapping allows near-constant-time operations.

How a hash function works:

  • Takes a key and the table size as input.

  • Returns an index within the table where the key-value pair should be stored.

Hash collisions occur when two different keys map to the same index. Solutions:

  1. Open addressing — place the colliding key in the next available empty slot.

  2. Closed addressing (chaining) — store colliding keys in a linked list at that index.

Time Complexity of Dictionaries

Operation

Worst Case

Average Case

Access

O(n)

O(1)

Search

O(n)

O(1)

Insert

O(n)

O(1)

Delete

O(n)

O(1)

The average case is O(1) because a good hash function distributes keys evenly. The worst case (all keys hash to the same index) is extremely unlikely with a decent hash function.

Advantages of Dictionaries

  • No numerical index needed; use descriptive keys.

  • Keys and values can be a wide range of types.

  • Hash table implementation allows very fast operations on average.


Section 3: Tree-Based Data Structures

Trees

A tree is an abstract data structure that stores data hierarchically rather than linearly. It consists of nodes (vertices) connected by edges.

Terminology

  • Root node — the topmost node of the tree.

  • Child node — a node connected to a node one level above it (its parent).

  • Parent node — a node with one or more child nodes.

  • Leaf node — a node with no children.

  • Height of a tree — the number of edges on the longest path from root to a leaf.

  • Depth of a node — the number of edges from the node to the root.

Properties

  • Every tree starts with a single root node.

  • Each node can have zero or more children.

  • Nodes with no children are leaves.

  • There is no definitive "end" — multiple leaf nodes may exist.

Common Uses of Trees

  • File system directory structures.

  • Family trees.

  • Corporate organizational charts.

  • Any data with a naturally hierarchical structure.


Binary Search Trees (BST)

A binary search tree is a tree with three restrictions:

  1. Each node can have at most two children.

  2. For any parent node:

    • The left child has a value less than or equal to the parent.

    • The right child has a value greater than or equal to the parent.

  3. No two nodes can contain the same value.

Advantages

  • Searching is logarithmic (O(log n)) in the average case.

  • Insertion, deletion, and access also benefit from the ordered structure.

How Searching Works

  • Start at the root.

  • If the target value is less than the current node, go left.

  • If greater, go right.

  • Repeat until found or a null child is reached.


Tries (Prefix Trees)

A trie is a tree-like data structure where nodes store letters of an alphabet. It is used for fast string retrieval and is especially useful for autocomplete and spellcheck.

Structure

  • The root node is empty.

  • Each node contains an array of references (one for each possible character).

  • Words are formed by traversing down paths.

  • The end of a word is marked by a flag (e.g., a period node).

Example

For the words "dab", "dad", "day", "den", "do":

  • Root points to 'd' node.

  • 'd' node points to 'a' and 'e' nodes.

  • 'a' node points to 'b', 'd', 'y' nodes.

  • 'e' node points to 'n' node.

  • 'n' node points to flag for "den".

How Autocomplete Works

Each character typed eliminates most possible words. The trie narrows down candidates, and popularity data can suggest completions.

How Spellcheck Works

A misspelled word's path is compared to valid trie paths. The closest path (smallest edit distance) suggests the correct word.


Heaps

A heap is a special tree where every parent node is compared to its children in a specific way — either greater than or less than.

Types of Heaps

  1. Min heap — the root contains the smallest value; every parent is smaller than its children.

  2. Max heap — the root contains the largest value; every parent is larger than its children.

Building a Max Heap (Insertion)

  1. Add the new node as the bottom-leftmost available position.

  2. Compare the new node to its parent; if greater, swap.

  3. Repeat recursively until the heap property is restored.

Deleting the Root (Heapify)

  1. Remove the root.

  2. Replace it with the bottom-rightmost node.

  3. "Heapify" — compare the new root to its children; swap with the larger child if needed. Continue down the tree.

Uses of Heaps

  • Heapsort — a sorting algorithm that builds a heap and repeatedly removes the root to produce a sorted list.

  • Priority queues — used for task scheduling; the highest-priority task (root) is processed first.


Graphs

A graph is a nonlinear data structure consisting of a finite set of vertices (nodes) and edges connecting them. Unlike trees, graphs have no specified starting point.

Notation

A graph is typically defined by two sets:

  • V (vertices): a comma-separated list of all nodes.

  • E (edges): a set of ordered pairs describing connections between nodes.

Adjacency

Two vertices are adjacent if there is an edge directly connecting them.

Graph Properties

  1. Directed vs. Undirected

    • Undirected — edges have no direction (e.g., Facebook friendships).

    • Directed — edges have a direction (e.g., Instagram following — one-way).

  2. Cyclic vs. Acyclic

    • Cyclic — there exists a path from at least one node back to itself.

    • Acyclic — no such cycle exists. All undirected graphs are cyclic by nature.

  3. Weighted vs. Unweighted

    • Weighted — each edge has a numerical cost (e.g., distance between locations).

    • Unweighted — edges have no cost.

Common Types of Graphs

  • Undirected cyclic graph with weighted edges — used in Dijkstra's shortest path algorithm (e.g., Google Maps, IP routing, telephone networks).

  • Unweighted cyclic graphs (both directed and undirected) — used for social media follower/following networks (Facebook, Instagram, Twitter).

Uses of Graphs

  • Navigation (maps).

  • Social network analysis.

  • Network routing.

  • Recommendation systems.


Summary

This series covered 12 common data structures across four categories:

  1. Basic: Arrays, ArrayLists

  2. Intermediate: Stacks, Queues, Linked Lists, Doubly Linked Lists, Dictionaries

  3. Tree-Based: Trees, Binary Search Trees, Tries, Heaps

  4. Graphs: Graphs

Key takeaways:

  • Big O notation measures efficiency using worst-case operations.

  • Random access (array/ArrayList) allows O(1) access; sequential access (stack/queue/linked list) restricts access order but can offer O(1) insert/delete at ends.

  • Linked lists use nodes with data and pointers; doubly linked lists add a backward pointer.

  • Dictionaries use key-value pairs and hash tables for average O(1) operations.

  • Trees store hierarchical data; BSTs enforce ordering for O(log n) search.

  • Tries store characters for fast word retrieval (autocomplete, spellcheck).

  • Heaps maintain extreme values at the root (min or max) for priority queues and heapsort.

  • Graphs connect nodes via edges and come in directed/undirected, cyclic/acyclic, and weighted/unweighted forms.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent