1. Home
  2. Explore
  3. Computer Science
  4. Data Structures & Algorithms Basics

Study methods

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

Data Structures & Algorithms Basics

Data Structures and Algorithms - Study Notes


Big O Notation

Big O notation is a mathematical notation used to describe the performance or scalability of an algorithm. It expresses how the runtime (or space) of an algorithm grows as the size of the input increases. The goal is not to measure exact execution time (which varies by machine), but to understand the growth rate — how much slower an algorithm becomes when the input becomes very large.

Why Big O Matters

  • Helps determine if an algorithm will scale well with large data sets.

  • Certain operations become more or less costly depending on the data structure used. For example, accessing an array element by index is fast (O(1)O(1)O(1)), but arrays have fixed size; resizing them is costly (O(n)O(n)O(n)).

  • Technical interviews at major companies (Google, Microsoft, Amazon) often require Big O analysis.

  • Knowing Big O makes you a better developer by enabling you to choose efficient algorithms and data structures.

Common Runtime Complexities

O(1)O(1)O(1) — Constant Time

The algorithm takes the same amount of time regardless of input size. Example: accessing the first element of an array.

public void printFirst(int[] numbers) {
    System.out.println(numbers[0]); // single operation, O(1)
}

Even if there are multiple constant-time operations, the runtime remains O(1)O(1)O(1) because the total time does not depend on nnn.

O(n)O(n)O(n) — Linear Time

Runtime grows linearly and directly with the size of the input. Example: iterating over all items in an array.

public void printAll(int[] numbers) {
    for (int number : numbers) {
        System.out.println(number); // O(n)
    }
}

Dropping constants: If there are two loops (e.g., O(2n)O(2n)O(2n)), we simplify to O(n)O(n)O(n) because constants do not affect growth rate. Similarly, O(n+1)O(n + 1)O(n+1) becomes O(n)O(n)O(n).

O(n2)O(n^2)O(n2) — Quadratic Time

Occurs with nested loops where each iteration runs another full loop. Example: printing all pairs in an array.

public void printCombinations(int[] numbers) {
    for (int first : numbers) {       // O(n)
        for (int second : numbers) {  // O(n)
            System.out.println(first + ", " + second);
        }
    }
}

If an additional linear operation (O(n)O(n)O(n)) is present alongside O(n2)O(n^2)O(n2), we drop the smaller term (nnn) because n2n^2n2 dominates for large nnn. Thus overall complexity is O(n2)O(n^2)O(n2).

A triple nested loop yields O(n3)O(n^3)O(n3).

O(log⁔n)O(\log n)O(logn) — Logarithmic Time

Runtime grows slowly as input size increases. The algorithm reduces the problem size by half in each step (e.g., binary search on a sorted array). For 1 million items, a logarithmic algorithm may need only ~20 comparisons.

Comparison of growth curves:

  • Linear (O(n)O(n)O(n)) grows at constant rate.

  • Logarithmic (O(log⁔n)O(\log n)O(logn)) slows down, making it much more efficient for large inputs.

O(2n)O(2^n)O(2n) — Exponential Time

The opposite of logarithmic: runtime doubles with each additional input. Such algorithms become extremely slow quickly and are not scalable (e.g., naive recursive Fibonacci).

Space Complexity

Big O also describes how much extra memory an algorithm requires relative to input size.

  • O(1)O(1)O(1) space: Only a fixed amount of extra memory (e.g., a loop variable).

  • O(n)O(n)O(n) space: Allocating an array of size nnn as a copy.

  • We only count additional space beyond the input itself.

Key Rule: In Big O analysis, always consider the worst-case scenario. For example, linear search is O(1)O(1)O(1) in the best case (first element), but O(n)O(n)O(n) in the worst case (last element). The worst case dominates.


Arrays

Arrays are the simplest data structure for storing a list of items sequentially in memory. They are built into most programming languages.

How Arrays Work

  • Items are stored in contiguous memory locations.

  • Because of this sequential layout, looking up an item by its index is O(1)O(1)O(1) — the memory address is calculated directly via a formula (base address + index Ɨ element size).

  • In Java and many languages, arrays have a fixed size specified at creation.

Strengths and Weaknesses

Operation

Complexity

Explanation

Lookup by index

O(1)O(1)O(1)

Direct memory address calculation.

Insertion at end (if space available)

O(1)O(1)O(1)

No shifting needed.

Insertion at end (if array full)

O(n)O(n)O(n)

Must resize: allocate new array (usually double the size) and copy all existing items.

Insertion at beginning or middle

O(n)O(n)O(n)

Requires shifting all subsequent elements to the right.

Deletion from end

O(1)O(1)O(1)

Simply remove the last item.

Deletion from beginning or middle

O(n)O(n)O(n)

Must shift all subsequent elements left to fill the gap.

Search for a value

O(n)O(n)O(n)

Linear scan (worst case).

Arrays in Java

  • Declaring an array: int[] numbers = new int[3];

  • Initializing with values: int[] numbers = {10, 20, 30};

  • Accessing: numbers[0]

  • Length: numbers.length (fixed)

  • To print contents: use java.util.Arrays.toString(numbers).

Static nature: Once created, size cannot change. To add more items, you must create a new larger array and copy elements.

Dynamic Array Implementations in Java

Java provides two built-in dynamic arrays in java.util:

  • Vector: Grows by 100% of its size when full; all methods are synchronized (thread-safe).

  • ArrayList: Grows by 50% of its size; methods are not synchronized (better performance for single-threaded use). More commonly used.

Building a Dynamic Array from Scratch (Exercise)

A custom Array class that automatically grows and shrinks:

  • Fields:

    • private int[] items (underlying fixed array)

    • private int count (number of actual items stored)

  • Constructor: Takes initial capacity, allocates items of that size, sets count = 0.

  • insert(int item) method:

    • If array is full (count == items.length), resize: create new array of size count * 2, copy existing items, then set items = newItems.

    • Place the new item at index count and increment count.

  • removeAt(int index) method:

    • Validate index (throw IllegalArgumentException if out of range).

    • Shift items left: for (int i = index; i < count - 1; i++) items[i] = items[i+1];

    • Decrement count.

  • indexOf(int item) method:

    • Linear scan from 0 to count-1, return index if found; else return -1.

    • Complexity: O(n)O(n)O(n) worst case.

  • print() method: Loop from 0 to count and print each item.

Edge cases to handle: Empty array, index out of bounds, resizing when full.


Linked Lists

Linked lists solve many limitations of arrays: they can grow and shrink automatically without the cost of resizing. They consist of a sequence of nodes, where each node contains a value and a reference (pointer) to the next node.

Structure

  • Head: The first node in the list.

  • Tail: The last node (its next pointer is null).

  • Nodes are not necessarily stored contiguously in memory; each node must explicitly store the address of the next node.

Time Complexities

Operation

Complexity

Explanation

Search for a value

O(n)O(n)O(n)

Must traverse from head to tail.

Lookup by index

O(n)O(n)O(n)

Same as search; no direct index access.

Insert at beginning

O(1)O(1)O(1)

Create new node, point its next to current head, update head.

Insert at end

O(1)O(1)O(1)

Create new node, point tail's next to it, update tail. (Requires maintaining a tail reference.)

Insert in the middle (after a known node)

O(1)O(1)O(1) to update links, but finding the node is O(n)O(n)O(n).

Overall O(n)O(n)O(n).

Delete from beginning

O(1)O(1)O(1)

Point head to the second node. Also set the old head's next to null for garbage collection.

Delete from end

O(n)O(n)O(n)

Must traverse to find the second-to-last node (previous node of tail). Update tail and break link.

Delete from middle

O(n)O(n)O(n)

Traverse to find the node and its predecessor, then relink.

Java's LinkedList

  • java.util.LinkedList<E> provides a doubly linked list (each node has references to both next and previous).

  • Common methods:

    • addLast(E e) — adds at end

    • addFirst(E e) — adds at beginning

    • removeLast() / removeFirst()

    • remove(int index)

    • contains(Object o) — O(n)O(n)O(n) search

    • indexOf(Object o) — O(n)O(n)O(n) search

    • size()

    • toArray() — converts to array

Building a Linked List from Scratch (Exercise)

Create a custom LinkedList class with an inner Node class.

Node Class (private inner class)

private class Node {
    private int value;
    private Node next;

    public Node(int value) {
        this.value = value;
    }
}

LinkedList Class

Fields: private Node first; (head), private Node last; (tail).

addLast(int item)

  1. Create a new Node with the given value.

  2. If list is empty (first == null), set both first and last to the new node.

  3. Else: set last.next = newNode, then set last = newNode.

addFirst(int item)

  1. Create a new Node.

  2. If empty, set both first and last to it.

  3. Else: set newNode.next = first, then set first = newNode.

indexOf(int item)

  1. Traverse from first with a current pointer and an index counter.

  2. For each node, if current.value == item, return index.

  3. If reaches end, return -1. Complexity: O(n)O(n)O(n).

contains(int item)

  • Simply return indexOf(item) != -1.

removeFirst()

  1. If list is empty, throw NoSuchElementException.

  2. If only one node ( first == last ), set both first and last to null.

  3. Else:

    • Store second = first.next.

    • Remove link: first.next = null.

    • Update first = second.

removeLast()

  1. If empty, throw exception.

  2. If single node, set first = last = null.

  3. Else:

    • Find the previous node of the last node. Use a helper method getPrevious(Node node) that traverses the list until current.next == node.

    • Set last = previous.

    • Remove link: last.next = null.

Helper method getPrevious(Node node) returns the node before the given node, or null if no such node.

Edge cases: Empty list, single element list. Always check and throw appropriate exceptions (NoSuchElementException for illegal operation on empty list).


Summary of Key Differences: Arrays vs Linked Lists

  • Memory layout: Arrays are contiguous; linked lists are scattered (nodes linked by pointers).

  • Size flexibility: Arrays have fixed size (dynamic arrays by copying); linked lists grow/shrink naturally.

  • Index lookup: Arrays O(1)O(1)O(1); linked lists O(n)O(n)O(n).

  • Insertion/deletion at ends: Linked lists O(1)O(1)O(1) (if tail maintained); arrays O(n)O(n)O(n) due to shifting or resizing.

  • Insertion/deletion in middle: Both O(n)O(n)O(n) (linked list requires traversal to find position).

  • Memory overhead: Linked lists need extra memory for the next pointer per element.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent