1. Home
  2. Explore
  3. Computer Science
  4. Image Filters in C

Study methods

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

Image Filters in C

Memory, Pointers, and Data Structures in C

Custom Data Types with Structures

C provides built-in types such as int, char, float, and double, but programs often need to group related values into a single logical unit. A structure, or struct, is a custom data type that combines multiple fields, potentially of different types.

For example, a student can be represented using a name and dormitory:

typedef struct
{
    char *name;
    char *dorm;
}
student;

The typedef gives the structure a convenient type name, student. A structure could also include:

  • Student identification numbers

  • Phone numbers

  • Email addresses

  • Enrollment information

  • Other related attributes

Structures are often declared in header files with a .h extension. A header file can then be included in multiple source files, allowing several programs to share the same custom data type.

Arrays of Structures

Once a structure has been defined, an array can store multiple values of that type:

int enrollment = get_int("Number of students: ");
student students[enrollment];

If enrollment is nnn, the array contains nnn student structures.

Each structure in the array can be accessed with an index:

students[i]

Individual fields inside that structure are accessed using the dot operator:

students[i].name = get_string("Name: ");
students[i].dorm = get_string("Dorm: ");

The expression students[i].name means:

  1. Find the student at index iii.

  2. Enter that student structure.

  3. Access its name field.

The dot operator is necessary because a structure contains fields inside itself. A simple integer or character variable does not require this additional level of access.

Structures and Encapsulation

A structure groups related information together. Instead of maintaining separate arrays for names, dormitories, identification numbers, and email addresses, one array of structures can keep all information about each student together.

This organization reduces the risk of accidentally associating one student's name with another student's dormitory.


Files and Persistent Data

Variables stored in memory disappear when a program terminates. To preserve information between executions, a program must write data to a file.

Opening a File

The fopen function opens a file and returns a pointer representing the opened file:

FILE *file = fopen("students.csv", "w");

The first argument specifies the file's name. The second argument specifies the mode.

Common File Modes

  • "r": Open a file for reading.

  • "w": Open a file for writing. If the file already exists, its previous contents are generally overwritten.

  • Other modes can support appending or combined reading and writing.

The type FILE * is a pointer to information used by the operating system and C library to manage the open file. It is an abstraction: the program does not need to know every internal detail of the file representation.

Checking for Errors

Opening a file can fail for several reasons:

  • The file may not exist when reading is requested.

  • The program may lack permission to access the file.

  • The system may not have enough memory or available resources.

  • The file path may be invalid.

C represents failure to obtain a valid pointer with NULL:

FILE *file = fopen("students.csv", "w");

if (file == NULL)
{
    return 1;
}

NULL represents the absence of a valid address or object.

Writing to a File

fprintf works similarly to printf, but it takes an additional first argument specifying the destination file:

fprintf(file, "%s,%s\n", students[i].name, students[i].dorm);

The format string and placeholders work in the familiar way. The comma creates a simple comma-separated format.

  • printf writes to the screen.

  • fprintf writes to a specified file.

Closing a File

When writing is complete, the program should close the file:

fclose(file);

Closing the file ensures that buffered data is properly written and releases operating-system resources.

CSV Files

A CSV, or comma-separated values file, stores values separated by commas. For example:

Maria,Cabot House
Brian,Winthrop
David,Mather

Spreadsheet programs can interpret each comma-separated value as a separate column.

CSV files are useful for simple data storage, but they become inefficient as the amount of data grows. Searching a large CSV file usually requires examining many rows, leading to linear-time behavior. Larger applications generally use databases, which provide more powerful ways to organize, search, and update data.


Memory Organization

A computer's RAM can be viewed as a large collection of numbered bytes. Each byte has a unique address. A pointer stores one of these addresses.

A running program is divided conceptually into several regions of memory.

Text Segment

The text segment contains the compiled machine instructions of the program. Although it is called “text,” it does not contain ordinary human-readable text. It contains the zeros and ones representing the program's executable instructions.

Initialized and Uninitialized Data

Global variables are stored in regions associated with data:

  • Initialized data contains global variables explicitly given initial values.

  • Uninitialized data contains global variables declared without explicit initial values.

The compiler and operating system organize these regions separately.

Environment Variables

Environment variables store information supplied by the surrounding operating system or execution environment. Examples include:

  • Usernames

  • Passwords

  • Configuration values

  • Server settings

They are especially useful when information should not be hard-coded directly into a program.

Stack

The stack stores information associated with currently executing function calls. Each time a function is called, it receives a stack frame containing items such as:

  • Parameters

  • Local variables

  • Local arrays

  • Information needed to return to the calling function

If main calls swap, a new stack frame is created for swap above or alongside the frame for main. If swap calls another function, another frame is created.

When a function returns, its stack frame is no longer considered active. The physical bytes remain in RAM, but the memory can be reused by another function.

Heap

The heap is used for dynamically allocated memory. Memory allocated from the heap can remain available after the function that requested it finishes, provided that the program eventually releases it.

The heap is useful when:

  • The required amount of memory is not known in advance.

  • Memory must persist beyond the lifetime of a function.

  • A data structure must grow or shrink dynamically.

Stack memory is usually short-lived and associated with function execution. Heap memory is explicitly requested and released by the program.


Pointers

A pointer is a variable that stores the address of another value.

int *p;

This declaration means that p is a pointer to an int. It does not allocate an integer for p to point to. It allocates space for an address.

Address-of Operator

The address-of operator, &, obtains the address of a variable:

int x = 1;
int *p = &x;

Here:

  • x stores the value 111.

  • &x represents the address of x.

  • p stores that address.

Dereference Operator

The dereference operator, *, follows a pointer to access the value at the stored address:

*p = 2;

This changes the value stored at the address in p. Since p points to x, the statement changes x from 111 to 222.

The symbol * has different meanings depending on context:

int *p;

Here it declares p as a pointer to an integer.

*p

Here it follows the pointer and accesses the integer at that address.

Swapping Values with Pointers

Passing ordinary variables to a function passes copies of their values:

void swap(int a, int b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

This function changes a and b inside its own stack frame, but it does not change the original variables in main.

If main contains x and y, the function's a and b are separate variables. Changing them does not change x and y.

Pointers allow a function to modify the original variables:

void swap(int *a, int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

The function is called by passing addresses:

swap(&x, &y);

The sequence is:

  1. &x and &y provide the addresses of the original variables.

  2. The parameters a and b store those addresses.

  3. *a and *b access the original values.

  4. Assignments through those pointers modify the original variables.

Pointers act like maps to memory locations. Copying a pointer copies the address, not the data at that address.

Pointer Aliasing

If two pointers contain the same address, they refer to the same memory:

int *x = malloc(sizeof(int));
int *y = x;

Both x and y now point to the same integer. Therefore:

*y = 13;

also changes the value observed through *x.

Assigning one pointer to another does not allocate a new object or copy the pointed-to value. It only copies the address.


Dynamic Memory Allocation

The malloc function allocates a requested number of bytes from the heap:

int *x = malloc(sizeof(int));

The result is the address of the allocated memory. That address is stored in x.

sizeof(int) determines the number of bytes needed for an integer on the current system.

Uninitialized Allocated Memory

Memory returned by malloc is not automatically initialized. It contains whatever bit pattern happened to be present previously. Such contents are called garbage values.

A pointer declared without initialization is especially dangerous:

int *y;
*y = 13;

The pointer y contains an unpredictable address. Dereferencing it attempts to access an unknown memory location.

Segmentation Faults

A segmentation fault occurs when a program accesses memory it is not permitted to use. Common causes include:

  • Dereferencing an uninitialized pointer

  • Dereferencing NULL

  • Accessing memory after it has been freed

  • Writing beyond the boundary of an allocated array

  • Using an invalid address

A pointer variable may contain a number that resembles an address, but that does not make the address valid.

calloc

calloc allocates memory and initializes every byte to zero:

int *x = calloc(10, sizeof(int));

This allocates space for 10 integers and clears the allocated memory. It is useful when zero-initialized memory is desired without manually setting each element.

realloc

realloc changes the size of an existing heap allocation:

numbers = realloc(numbers, new_size);

It can:

  • Expand an allocation in place when possible.

  • Allocate a new, larger region elsewhere.

  • Copy the old contents to the new region.

  • Release the old region when necessary.

  • Return the address of the resized allocation.

If the original pointer is NULL, realloc behaves similarly to an allocation of the requested size.

Because allocation can fail, the result should be checked:

int *tmp = realloc(numbers, new_size);

if (tmp == NULL)
{
    free(numbers);
    return 1;
}

numbers = tmp;

free

Memory allocated with malloc, calloc, or realloc should eventually be released:

free(x);

The operating system tracks the size of the allocation, so the program does not need to provide the size when calling free.

Failing to release allocated memory causes a memory leak. A memory leak can gradually consume available memory, slowing down a program or causing it to run out of memory.


Stack and Heap Errors

Garbage Values

When a function's stack frame disappears, its bytes are not erased. A later function may receive the same physical memory containing old bit patterns.

Therefore, an uninitialized local variable may contain values left behind by previous function calls. These are garbage values.

C generally does not clear every newly reused stack byte because doing so would consume additional time and provide little benefit.

Stack Overflow

A stack overflow occurs when the stack grows beyond the memory available for it. This can happen through:

  • Excessively deep recursion

  • Calling functions indefinitely

  • Creating unusually large local arrays

  • Accumulating too many active stack frames

The stack can grow toward the heap. If it grows far enough, it may collide with other memory regions.

Heap Overflow

A heap overflow occurs when a program uses more heap memory than it has safely allocated or available. It can involve:

  • Writing beyond the end of a heap allocation

  • Allocating excessive amounts of memory

  • Causing the heap to grow into another memory region

Buffer Overflows

A buffer is a region of memory used to store data. An array or string is a buffer.

A buffer overflow occurs when a program writes more data into a buffer than the buffer can hold. The excess data overwrites adjacent memory.

For an array of 12 bytes, valid indices are:

0,1,2,…,110,1,2,\ldots,110,1,2,…,11

Writing to index 121212 is already outside the buffer.


Buffer Overflow Exploits

Consider a function that creates a 12-byte local array and copies user input into it:

void foo(char *bar)
{
    char c[12];
    memcpy(c, bar, strlen(bar));
}

If the input is short enough, the copy is safe. However, if the input contains more than 12 bytes, memcpy writes beyond the boundary of c.

Stack Layout

A stack frame can contain:

  • Function parameters

  • Local variables

  • Local arrays

  • A return address

The return address tells the processor where execution should continue after the function finishes.

If user input is copied beyond the end of a local array, it may overwrite:

  1. The array itself

  2. Nearby local variables

  3. Other stack information

  4. The function's return address

Exploitation

An attacker may construct input containing carefully chosen bytes. Since characters are represented as numbers, and numbers are represented as bits, input can contain bit patterns that resemble machine instructions.

If the attacker overwrites the return address, the function may return to attacker-controlled data instead of returning to its legitimate caller. This can cause unauthorized code to execute.

Potential consequences include:

  • Deleting files

  • Sending messages or spam

  • Modifying data

  • Granting unauthorized access

  • Taking control of the program

This is called a buffer overflow exploit.

The underlying vulnerability is the failure to verify that the amount of copied data fits within the destination buffer.

Prevention

Programs should:

  • Check input lengths.

  • Ensure array indices remain within valid bounds.

  • Allocate sufficient memory.

  • Avoid copying more bytes than a destination can hold.

  • Initialize pointers before dereferencing them.

  • Free allocated memory correctly.

  • Use debugging and memory-analysis tools.


Memory Debugging with Valgrind

Valgrind is a tool that detects memory-related errors. It can identify issues such as:

  • Invalid reads

  • Invalid writes

  • Buffer overflows

  • Use of uninitialized memory

  • Memory leaks

  • Improperly freed memory

For a program named memory, it can be run with:

valgrind ./memory

Invalid Writes

Suppose a program allocates space for 10 integers:

int *x = malloc(10 * sizeof(int));

The valid indices are 000 through 999. This statement is invalid:

x[10] = 0;

Valgrind may report an “invalid write of size 4.” The size 444 commonly corresponds to the number of bytes in an int on the system. The message indicates that the program tried to write one integer beyond the allocated block.

Memory Leaks

If a program allocates 40 bytes but never frees them, Valgrind can report that 40 bytes are “definitely lost.”

The correction is to release the allocation:

free(x);

A successful Valgrind summary should indicate that all allocated blocks were freed and that no leaks remain.

Hexadecimal Addresses

Valgrind and debuggers often display memory addresses in hexadecimal notation, such as:

0x7ffd1234

Hexadecimal is a base-16 number system. It provides a compact way to represent binary values and memory addresses.


Rubber Duck Debugging

Rubber duck debugging is a technique in which a programmer explains code aloud to an inanimate object or another person.

The programmer describes:

  1. What the code is intended to do.

  2. What each statement actually does.

  3. What values variables contain.

  4. How control flows through the program.

  5. Where the observed behavior differs from the expected behavior.

Explaining the code forces its logic into explicit language. This often reveals contradictions, incorrect assumptions, or overlooked edge cases.

The technique does not require a literal rubber duck. Any object, person, or even an imagined audience can serve as the listener.


Arrays and Their Limitations

An array stores elements in a contiguous block of memory. If an array contains six values, the values occupy consecutive locations.

Fixed Capacity

If an array is created with capacity 666, it cannot safely store a seventh element without additional work.

The program must either:

  • Overwrite an existing value, which loses data.

  • Write beyond the array, causing a buffer overflow.

  • Allocate a larger array and copy the old values.

Resizing an Array Manually

To grow an array from size nnn to size n+1n+1n+1, a program can:

  1. Allocate a new array with capacity n+1n+1n+1.

  2. Copy all nnn existing elements.

  3. Add the new element.

  4. Free the old array.

  5. Use the new array.

The copying operation takes linear time:

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

This process also temporarily requires space for both the old and new arrays.

Memory Fragmentation

A computer may have plenty of total free memory but lack one sufficiently large contiguous region. This situation is called memory fragmentation.

For example, free memory might be divided into several small gaps separated by allocated regions. An array requiring one large contiguous block cannot use those separate gaps, even if their total size is large enough.


Linked Lists

A linked list stores elements in separate nodes connected by pointers.

A node containing an integer might be defined as:

typedef struct node
{
    int number;
    struct node *next;
}
node;

Each node contains:

  • A data value, such as an integer.

  • A pointer to the next node.

The final node's next pointer is NULL.

Structure of a Linked List

Unlike an array, linked-list nodes do not need to be adjacent in memory. They can be located anywhere in the heap. The next pointers connect them logically.

A separate pointer identifies the beginning of the list:

node *first = NULL;

The list is accessed through the address of its first node. Without this pointer, the rest of the nodes would be difficult or impossible to find.

Inserting a Node

To insert a new node:

  1. Allocate memory for the node.

  2. Store the new value.

  3. Set the new node's next pointer.

  4. Update another node's pointer to connect the new node into the list.

For an unsorted list, insertion at the beginning can be performed in constant time:

new_node->next = first;
first = new_node;

Only a fixed number of pointer assignments are required, regardless of the list's length.

Thus, insertion at the beginning takes:

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

Sorted Insertion

If the linked list must remain sorted, the program must walk through the list until it finds the correct location.

The traversal may examine many nodes, so sorted insertion generally takes:

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

The source of the time cost is the search for the correct insertion point, not the pointer updates themselves.

After finding the correct location, the pointers must be rearranged carefully:

  • The preceding node's next pointer must point to the new node.

  • The new node's next pointer must point to the following node.

Failing to update either pointer can disconnect part of the list or leave the new node inaccessible, causing a memory leak.

Linked-List Traversal

A linked list cannot use ordinary array indexing efficiently. Expressions such as list[3] are not appropriate because nodes are not necessarily adjacent.

Instead, traversal follows pointers one node at a time:

for (node *ptr = first; ptr != NULL; ptr = ptr->next)
{
    // Use ptr->number
}

The traversal continues until the pointer becomes NULL.

The Arrow Operator

When accessing a field through a pointer to a structure, C uses the arrow operator:

ptr->number

This is equivalent to:

(*ptr).number

The arrow operator means:

  1. Follow the pointer.

  2. Access the specified structure field.

The dot operator is used for a structure itself:

student.name

The arrow operator is used for a pointer to a structure:

student_ptr->name

Freeing a Linked List

A linked list must be freed one node at a time. The program must save the next node before freeing the current one:

node *ptr = first;

while (ptr != NULL)
{
    node *next = ptr->next;
    free(ptr);
    ptr = next;
}

The next pointer must be saved first because freeing the current node makes its contents unavailable for reliable use.

Linked-List Trade-Offs

Advantages

  • Can grow or shrink dynamically.

  • Does not require contiguous memory.

  • Insertion and deletion can be efficient once the correct location is known.

  • Does not require a predetermined capacity.

Disadvantages

  • Each node requires additional memory for a pointer.

  • Nodes cannot be accessed directly by index.

  • Searching takes linear time.

  • Pointer manipulation is more complex.

  • Memory allocation and freeing introduce additional responsibilities.

  • Poor pointer management can cause leaks or disconnected nodes.


Dynamic Arrays

A dynamic array begins with a pointer rather than a fixed-size array:

int *numbers = NULL;
int size = 0;
int capacity = 0;

Here:

  • numbers points to the allocated data, if any.

  • size records how many elements are currently stored.

  • capacity records how many elements fit in the current allocation.

When size == capacity, the program must allocate more space before adding another element.

Using realloc, it can resize the allocation:

capacity++;
int *tmp = realloc(numbers, capacity * sizeof(int));

if (tmp == NULL)
{
    free(numbers);
    return 1;
}

numbers = tmp;
numbers[size] = value;
size++;

Growing by one element at a time is correct but inefficient because repeated resizing and copying can lead to many linear-time operations. Practical dynamic-array implementations often increase capacity by a larger factor, such as doubling it, to reduce the number of reallocations.


Abstract Data Types and APIs

A data structure describes how data is organized and what operations it supports. Its internal implementation can vary.

For example, a stack is defined conceptually by:

  • push: add an item.

  • pop: remove an item.

  • Last-in, first-out behavior.

A stack could be implemented using:

  • A fixed-size array.

  • A dynamically resized array.

  • A linked list.

The users of the stack do not need to know which implementation is used if they interact through a documented interface.

An API, or application programming interface, specifies how other code can use a component. It exposes operations while hiding implementation details.

This separation provides abstraction:

  • The implementation can change.

  • The calling code can remain unchanged.

  • Users need to understand the operations and guarantees, not every internal detail.


Stacks

A stack is a last-in, first-out data structure, abbreviated LIFO.

The last item inserted is the first item removed.

Stack Operations

  • Push: Add an item to the top.

  • Pop: Remove the item from the top.

A stack of cafeteria trays illustrates this behavior. A newly cleaned tray is placed on top, and the next person generally takes the top tray.

Array-Based Stack

A stack can be represented using a structure containing:

typedef struct
{
    int numbers[CAPACITY];
    int size;
}
stack;

The size field tracks how many elements are currently stored. The program must ensure:

0≤size≤capacity0 \leq \text{size} \leq \text{capacity}0≤size≤capacity

A fixed-size implementation is simple but cannot grow beyond its predetermined capacity.

Dynamic Stack

A stack can instead use dynamically allocated memory. When it becomes full, the underlying array can be resized with realloc.

This removes the fixed-capacity limitation but introduces memory-management complexity and resizing costs.

Other Uses of Stacks

Stacks are useful whenever the most recently encountered item must be processed first. Examples include:

  • Function-call management.

  • Undo operations.

  • Expression evaluation.

  • Matching nested symbols.

  • Parsing nested HTML elements.

Nested HTML structures can be analyzed using a stack because the most recently opened element is generally the first element that must be closed.


Queues

A queue is a first-in, first-out data structure, abbreviated FIFO.

The first item inserted is the first item removed.

A line of customers waiting for service illustrates queue behavior. The person who arrives first should generally be served first.

Queue Operations

Common operations include:

  • Enqueue: Add an item to the back.

  • Dequeue: Remove an item from the front.

The exact names may vary, but the FIFO behavior defines the data structure.

Array-Based Queues

A queue implemented with an array needs to track more than just its size and capacity. It must also track the position of the front element.

If each removal required shifting every remaining element forward, each dequeue operation could take linear time. Tracking the front allows the program to advance a pointer or index instead of physically moving all data.

A circular-array implementation can reuse freed positions at the beginning of the array.

Queue Trade-Offs

Queues are useful when fairness or arrival order matters. Examples include:

  • Print jobs.

  • Network requests.

  • Customers waiting for service.

  • Tasks waiting for processing.

  • Data buffering.

Using a stack when a queue is required reverses the intended order and causes the newest item to be processed first.


Trees

A tree is a data structure composed of nodes connected by links. It resembles a family tree, although computer-science trees are often drawn with the root at the top and descendants below.

Tree Terminology

  • Root: The first or topmost node.

  • Parent: A node directly above another node.

  • Child: A node directly below another node.

  • Leaf: A node with no children.

  • Subtree: A node together with all of its descendants.

Unlike a linked list, a tree can branch. A node may have multiple children.


Binary Trees and Binary Search Trees

A binary tree is a tree in which each node has at most two children:

  • A left child.

  • A right child.

A binary search tree adds an ordering rule:

  • Every value in the left subtree is smaller than the node's value.

  • Every value in the right subtree is larger than the node's value.

This property applies recursively to every node and subtree.

A node might be defined as:

typedef struct node
{
    int number;
    struct node *left;
    struct node *right;
}
node;

A leaf has:

left == NULL
right == NULL

Searching a Binary Search Tree

To search for a value nnn:

  1. If the tree is NULL, the value is absent.

  2. If nnn equals the current node's value, the value is found.

  3. If nnn is smaller, search the left subtree.

  4. If nnn is larger, search the right subtree.

A recursive implementation is:

bool search(node *tree, int n)
{
    if (tree == NULL)
    {
        return false;
    }
    else if (n < tree->number)
    {
        return search(tree->left, n);
    }
    else if (n > tree->number)
    {
        return search(tree->right, n);
    }
    else
    {
        return true;
    }
}

The recursive call receives a subtree rather than necessarily the entire tree. A subtree is itself a tree, so the same function can be applied repeatedly.

Running Time

For a balanced binary search tree, each comparison eliminates approximately half of the remaining possibilities. Search therefore takes:

O(log⁡n)O(\log n)O(logn)

where nnn is the number of nodes.

However, a binary search tree can become unbalanced. If values are inserted in an unfortunate order, the tree may degenerate into a structure resembling a linked list. In that case, searching can take:

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

Balancing is therefore important when logarithmic performance is required.


Hashing

Hashing maps an input value to a smaller identifier called a hash value. A hash function determines the destination for each input.

For example, a hash function might assign a student's last name to a bucket based on its first letter:

  • Names beginning with A go to bucket 0.

  • Names beginning with B go to bucket 1.

  • Names beginning with C go to bucket 2.

Hashing is also used when sorting playing cards into piles according to suit or organizing exams by the first letter of a student's last name.

The general process is:

  1. Take an input.

  2. Apply a hash function.

  3. Obtain a bucket index.

  4. Store or search for the item in that bucket.

A good hash function distributes values as uniformly as possible.


Hash Tables

A hash table combines an array with a hash function. The array contains buckets, and the hash function determines which bucket receives each value.

For example, an array with 26 buckets could store names based on their first letters.

Collisions

A collision occurs when two different inputs produce the same hash value.

For example, both Alice and another person whose name begins with A may hash to bucket 0.

A hash table must have a collision-resolution strategy.

Linear Probing

With linear probing, the program searches sequentially for the next available position:

  1. Try the hashed position.

  2. If it is occupied, check the next position.

  3. Continue until an empty position is found.

  4. Wrap around if necessary.

Linear probing uses space efficiently because values are stored directly in the table. However, collisions can cause long clusters. Searching may eventually require examining many positions.

In the worst case, lookup becomes:

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

Separate Chaining

With separate chaining, each array bucket points to a linked list.

The hash table is therefore an array of linked lists:

node *table[BUCKETS];

Each bucket can contain multiple values. When a collision occurs, the new value is added to that bucket's linked list.

Advantages include:

  • The table does not need one empty array slot for every item.

  • Each bucket can grow as needed.

  • Collisions are handled without moving existing values.

  • The structure can store more items than the number of buckets.

If the hash function distributes values uniformly, each linked list is relatively short. With mmm buckets and nnn stored items, the average chain length is approximately:

nm\frac{n}{m}mn​

Expected lookup is therefore close to O(1)O(1)O(1) when the number of buckets is large relative to the number of stored items and the hash function is effective. In the worst case, if every item lands in one bucket, lookup becomes O(n)O(n)O(n).

Asymptotic and Practical Performance

A hash table may still be classified as O(n)O(n)O(n) in certain analyses, depending on the assumptions and implementation. However, dividing data into many approximately equal buckets can greatly reduce real-world search time.

A structure that examines one thirty-first of the data on average may have the same broad asymptotic category under some conditions, but it can still be substantially faster in practice.


Tries

A trie is a tree-like data structure designed for storing strings. The name comes from the word “retrieval.”

Each node contains an array of pointers, typically one pointer for each possible character. For the English alphabet, a node might contain 26 pointers.

Storing a Word

To store the word MAXWELL:

  1. Use the M pointer from the root.

  2. From that node, use the A pointer.

  3. Continue through X, W, E, L, and L.

  4. Mark the final node to indicate that a complete word ends there.

The characters are represented implicitly by the path through the tree. The nodes themselves need not store the characters explicitly if the position of each pointer identifies the character.

A special marker indicates that a valid word ends at a particular node. This is important because one word may be a prefix of another. For example, a trie must distinguish between a stored word such as CAR and a longer word such as CART.

Lookup Time

Searching for a word depends primarily on the word's length, not on the total number of words stored.

If a word has length LLL, lookup takes approximately:

O(L)O(L)O(L)

For a fixed practical maximum word length, this can be considered effectively constant time:

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

Even if the dictionary grows from one million words to one billion words, searching for a particular word still follows only the characters in that word.

Trie Trade-Offs

Advantages

  • Very fast lookup for strings.

  • Lookup time depends on word length rather than dictionary size.

  • Naturally supports prefix searches and autocomplete.

  • Does not require words to be stored in alphabetical order.

Disadvantages

  • Uses substantial memory.

  • Every node may contain many pointers.

  • Sparse data can leave many pointers as NULL.

  • Implementation is more complex than an array or simple linked list.

A trie exchanges memory efficiency for lookup speed.


Data-Structure Trade-Offs

No single data structure is best for every problem. Design decisions involve several competing resources.

Time

How quickly can the program:

  • Search?

  • Insert?

  • Delete?

  • Traverse?

  • Resize?

Space

How much memory is required for:

  • Data values?

  • Pointers?

  • Empty buckets?

  • Temporary copies during resizing?

Programmer Effort

More sophisticated structures require:

  • More code.

  • More pointer manipulation.

  • More testing.

  • More opportunities for memory errors.

  • More maintenance.

Flexibility

Dynamic structures can grow and shrink, while fixed arrays are simpler but limited by their capacity.

Common Comparisons

  • Array: Fast indexing, contiguous memory, fixed or costly resizing.

  • Linked list: Dynamic size, easy pointer-based insertion, slow indexing and extra pointer memory.

  • Stack: LIFO access through push and pop.

  • Queue: FIFO access through enqueue and dequeue.

  • Binary search tree: Ordered search, potentially O(log⁡n)O(\log n)O(logn) when balanced.

  • Hash table: Very fast expected lookup with a good hash function.

  • Trie: Lookup based on string length, but high memory usage.


Technical Debt

Technical debt is the future cost created by choosing a quick, poorly designed, or incomplete solution instead of a robust one.

A shortcut may save time immediately, but it can later cause:

  • More difficult maintenance.

  • Slower execution.

  • Repeated debugging.

  • Increased risk of bugs.

  • More expensive redesign.

  • Difficulty adding new features.

For example, repeatedly resizing an array by one element may be easy to write, but it can lead to unnecessary copying. Similarly, poorly managed pointers may create memory leaks or corrupt data.

Good software design balances immediate development time with long-term correctness, performance, clarity, and maintainability.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent