Computer Memory and Arrays
Memory, Arrays, and Data Structures
Memory as an Array
Computer memory can be understood conceptually as a long sequence of small storage locations. Each location holds a basic unit of data, such as a byte, and each location has a sequential numerical label called an address.
The computer provides two fundamental operations for interacting with memory:
Write: Store data at a particular address.
Read: Retrieve data from a particular address.
This is exactly the behavior of an array:
An array contains elements arranged in order.
Each element has an index.
Data can be written to or read from a particular index.
Therefore, a memory address is essentially an index into the array that represents memory. Memory addresses are often displayed in hexadecimal because computer memories are very large, but an address is still fundamentally just a number identifying a position.
At the lowest level, every program ultimately relies on reading data from and writing data to indexed locations in an array of memory.
Everything that runs on a computer is built on top of these two operations. More advanced programming constructs and data structures do not escape the underlying array; instead, they organize the data and calculate which array index should be accessed.
Arrangements of Data in an Array
A One-Element Array
If memory contains only one element, there is no choice about where to store a piece of data. The data must be placed at index 0.
For example, if the single element stores one English character, that character occupies the only available location.
Multiple Elements and Possible Orders
Once an array contains multiple elements, the elements can be arranged in different orders.
Two distinct elements can be arranged in 2 possible orders.
Three distinct elements can be arranged in 3!=6 possible orders.
Four distinct elements can be arranged in 4!=24 possible orders.
The number of possible arrangements for n distinct elements is given by the factorial:
As the number of elements increases, the number of possible arrangements grows extremely rapidly. For example, an array containing one million distinct elements has:
possible arrangements.
Different arrangements make different operations efficient or inefficient. The organization of the data is therefore a central part of how quickly it can be accessed.
Why Data Ordering Matters
Searching Unsorted Data
Suppose an array contains one million random English characters, and the task is to determine whether the character Z appears anywhere in the array.
With only ordinary array operations available, the general solution is:
Start at index 0.
Read the character at that index.
Compare it with
Z.Move to the next index if it is not a match.
Continue until
Zis found or the end of the array is reached.
In the worst case, every element must be examined. If the array contains no Z, the entire array must be searched.
This approach is necessary because the random arrangement provides no information about where a particular character might be located.
Searching Sorted Data
Now suppose the same array is sorted in ascending alphabetical order.
To determine whether Z is present, it is sufficient to inspect the final element:
If the final element is
Z, thenZis present.If the final element comes before
Z, thenZis absent.If the final element comes after
Z, then the specific interpretation depends on the ordering and possible character range, but the sorted arrangement still provides substantial information for narrowing the search.
The important idea is that sorting organizes data to make particular searches easier. A sorted array supports efficient searching because the ordering provides information about the locations of possible values.
Finding the Most Frequent Character
Finding whether Z exists is easy in a character array sorted alphabetically, but finding the most frequent character is a different problem.
If the characters are alphabetically sorted, the most frequent character may appear anywhere in the array. A search may need to inspect the entire array or count the lengths of groups of repeated characters.
However, another arrangement could place characters in descending order of frequency:
The most frequent character appears first.
The next most frequent character appears second.
Less frequent characters appear later.
Under that arrangement, the most frequent character can be found immediately by reading the first element.
This illustrates a major principle:
An array arrangement is optimized for particular access patterns, not for every possible operation simultaneously.
An arrangement that is excellent for one question may be poor for another.
What a Data Structure Is
A data structure is a strategy for organizing elements in an underlying array and using logic to access, insert, remove, or modify those elements.
Every data structure has two major components.
1. The Arrangement of Elements
The first component is the ordering or organization of elements in the underlying array.
Examples include:
Elements sorted by their own values.
Elements sorted by a field such as a user ID.
Elements connected through stored indexes.
Elements grouped according to hash values.
Nodes arranged according to parent-child relationships.
2. The Operations Used to Access the Data
The second component is the logic used to perform operations such as:
Finding a particular element.
Inserting a new element.
Removing an existing element.
Traversing elements in a particular order.
Following relationships between elements.
Different data structures use different arrangements and operations to exploit different strengths of the underlying array.
Data structures do not eliminate the limitations of arrays. They reorganize data and add access logic so that particular operations become more efficient.
Sorted Arrays
A sorted array stores elements in an order determined by some value or property.
For simple characters, the elements may be sorted according to their character values. For more complex objects, the sorting criterion may be one field within the object.
For example, a collection of user objects could be sorted by:
User ID.
User name.
Account creation date.
Geographic location.
The objects themselves may contain many fields, but the array only needs to be ordered according to the field relevant to the intended search.
Multiple Index Arrays
A collection may need to support searches using several different properties. For example, users may need to be located efficiently by both their ID and their name.
One solution is to maintain:
An array containing the actual user objects.
An index array sorted by user ID.
Another index array sorted by user name.
The index arrays do not contain duplicate user objects. Instead, they contain indexes pointing to the locations of the actual objects.
This creates a data structure composed of multiple arrays:
The data array stores the actual objects.
One index array provides an ordering by user ID.
Another index array provides an ordering by user name.
The data array itself may or may not be sorted.
Indexes as Pointers
An index into an array functions like a pointer: it tells the program where to find the desired data.
A useful analogy is a library:
Each physical book exists in only one location.
A library user may want to search by title, author, or genre.
The library does not need three copies of every book.
Instead, its catalog contains different indexes that direct the user to the book’s actual shelf location.
Similarly, an index array allows multiple search arrangements without duplicating the underlying objects.
Array Lists
An array list is an ordered collection that uses an array internally while providing operations that ordinary fixed-size arrays do not directly provide.
It generally supports:
Reading an element at an index.
Writing an element at an index.
Adding an element to the end.
Removing an element from an arbitrary position.
Inserting an element at an arbitrary position.
Capacity and Size
A normal array has a fixed length. An array list appears to grow because it separates two values:
Capacity: The number of elements that the backing array can hold.
Size or count: The number of elements currently stored in the list.
The backing array usually has greater capacity than the list’s current size.
For example:
Backing array capacity: 10
Current list size: 4
The list contains four active elements, while six additional positions remain available.
Adding to the End
When an element is added to the end of an array list:
The list uses its current count as the index for the new element.
The new value is written into the backing array.
The count increases by one.
If the current size is n, the new element is placed at index n, and the size becomes n+1.
This operation is efficient when unused capacity is available.
If the backing array becomes full, the array list must obtain a larger array and copy the existing elements into it. That resizing process is more expensive, but it does not occur on every addition.
Removing an Element
Removing an element from the middle of an array list creates a gap. Because the list is ordered, the elements after the removed element must be shifted backward.
For example, removing the element at index 2 requires:
Moving the element from index 3 to index 2.
Moving the element from index 4 to index 3.
Continuing until the final active element has shifted backward.
The operation requires reading and rewriting every subsequent element. Removing the final element is much easier because no later elements need to move.
Removing from the middle of an array list can be slow because the list must preserve its ordering by shifting later elements backward.
Inserting an Element
Inserting an element into the middle of an array list creates the opposite problem. Existing elements must be shifted forward to make room.
For insertion at index i:
Elements from the end down to index i are shifted one position forward.
The new element is written at index i.
The list size increases by one.
Inserting at the end is efficient because no later elements need to move. Inserting at the beginning is expensive because every existing element may need to be shifted.
The Importance of Understanding Implementation
A programming language may provide a convenient list abstraction, but the underlying implementation still determines the performance of its operations.
A programmer might assume that insertion and removal are automatically fast because the language provides built-in list functions. However, if the list is backed by an array, inserting or removing from the middle requires copying elements.
The performance depends on:
The number of elements.
The location of the insertion or removal.
Whether the backing array has sufficient capacity.
The expected pattern of access.
No data structure is universally optimal. Every ordering and representation has strengths and weaknesses.
Stacks
A stack is a restricted form of an array list in which elements can be added and removed only at one end.
The accessible end is called the top.
A stack follows the last-in, first-out principle, abbreviated as LIFO:
The most recently added element is the first one removed.
Older elements remain inaccessible until newer elements are removed.
A physical stack of blocks illustrates this behavior. To reach a block near the bottom, all blocks above it must be removed first.
Implementing a Stack with an Array
A stack can be implemented using:
A backing array with a fixed capacity.
A count that records the number of active elements.
The active elements occupy the beginning of the array, and the final active element is the top of the stack.
Pushing an Element
Adding an element to a stack is called pushing.
To push a new element:
Write it at the index equal to the current count.
Increase the count by one.
If the stack currently contains n elements, the new element is written at index n.
Popping an Element
Removing the top element is called popping.
To pop an element:
Read the element at the final active position if its value is needed.
Decrease the count by one.
No other elements need to be copied because there are no elements after the top element.
Popping is therefore an especially efficient form of removal.
Stack Operations as Special Cases
The fast operations of a stack are special cases of array-list operations:
Pushing is equivalent to inserting at the end.
Popping is equivalent to removing from the end.
Because no elements follow the end of the array list, no shifting is required.
Stack Applications: Undo and Redo
Stacks are useful when the most recent action must be handled first.
A text editor can implement undo functionality using a stack:
Each user change is pushed onto an undo stack.
When the user presses undo, the most recent change is popped.
That change is reversed.
Redo can be implemented with a second stack:
Undone changes are pushed onto a redo stack.
Pressing redo pops a change from the redo stack and reapplies it.
If the user makes a new change after undoing, the redo stack is cleared because the previous redo history is no longer valid.
Stacks are appropriate whenever operations must be reversed in the opposite order from which they were performed.
Queues
A queue is similar to a stack but supports removal from the opposite end.
A queue follows the first-in, first-out principle, abbreviated as FIFO:
The earliest added element is the first one removed.
New elements enter at the back.
Existing elements leave from the front.
A real-world line or queue illustrates this behavior.
Queue Applications
Queues are useful when tasks should be processed in the order they arrive.
A web server can place incoming requests into a queue:
New requests are added to the back.
The server processes requests from the front.
Responses are sent in approximately the same order as the requests arrived.
If a stack were used instead, newer requests would continually be processed before older ones. Under heavy load, an old request could remain at the bottom for a very long time or potentially never be processed.
A queue provides a more reasonable and predictable response order.
Implementing a Queue with an Array
A naive array implementation might remove the first element by shifting every other element backward. This would be expensive because each removal could require copying many elements.
A more efficient approach uses two indexes:
Start index: The location of the first active queue element.
End index: The location where the next element will be added or the position marking the end of the active range.
The queue also tracks its capacity.
Dequeue Operation
Removing the first element from a queue is called dequeueing.
Instead of copying all later elements backward, the queue simply:
Treats the element at the start index as removed.
Increases the start index by one.
Considers the next array position to be the new front.
The old element remains physically present in the array, but it is no longer considered part of the queue.
This avoids copying and makes removal efficient.
The Dead-Space Problem
Repeated dequeue operations cause the start index to move forward. The beginning of the array gradually becomes unused space.
Eventually, the end index may reach the array’s capacity even though there is free space at the beginning. Without a solution, the queue would appear full or overflow its backing array.
Circular Queues and the Modulo Operator
A circular queue solves the dead-space problem by treating the array as if its end connects back to its beginning.
When an index reaches the array’s capacity, it wraps around to index 0.
This is implemented using the modulo operator. If the array capacity is C, an index i is converted into a valid array position with:
The result is always in the range:
For example, with an array capacity of 5:
0mod5=0
1mod5=1
4mod5=4
5mod5=0
6mod5=1
Thus, indexes form a repeating sequence:
As elements are added at the back and removed from the front, the active queue wraps around the array like the movement of a snake in a grid.
A circular queue uses a fixed-size array efficiently by reusing positions that become free at the beginning.
This approach avoids reallocating, resizing, or copying the entire queue as it progresses through the array.
Linked Lists
A linked list stores elements in a logical order by linking each element to the next one rather than relying on the physical order of the underlying array.
Each linked-list element commonly contains:
The actual stored data.
An index identifying the next element in the list.
A special value such as −1 can indicate that there is no next element.
Building a Linked List
Suppose the underlying array is initially empty.
The first user object is placed at array index 0.
A second user object is added at another array position.
The first object stores the array index of the second object in its
nextfield.
The two objects may not occupy consecutive positions in the array, but the stored link defines their logical order.
For example:
User 1 is stored at array index 0.
User 3 is stored at array index 1.
User 1’s
nextfield points to index 1.
The linked-list order is therefore User 1 followed by User 3.
Inserting into a Linked List
Suppose User 2 must be inserted between User 1 and User 3.
In an array list, elements after User 1 would need to be shifted forward to make space.
In a linked list:
User 2 is added to any available position in the underlying array.
User 1’s
nextfield is updated to point to User 2.User 2’s
nextfield is set to point to User 3.
No existing elements need to be moved.
Removing from a Linked List
To remove User 3 after User 2:
User 2’s
nextfield is changed to −1.The list now ends at User 2.
The removed element’s storage may remain in the underlying array until it is reused or reclaimed, but it is no longer part of the logical linked list.
Strengths of Linked Lists
Linked lists are efficient for insertion and removal when a direct reference or index to a neighboring element is already available.
Insertion can be performed by changing a small number of links.
Removal can be performed by changing a predecessor’s link.
Existing elements do not need to be shifted.
Weaknesses of Linked Lists
Linked lists lose efficient random access.
In an array, the element at position n can be accessed directly using index n. In a linked list, the physical array index does not necessarily match the logical position.
To find the element at logical position 300,000, a simple linked-list implementation may need to:
Start at the first element.
Follow the
nextlink.Repeat this process 300,000 times.
Linked lists also tend to iterate more slowly than arrays because their elements may be scattered throughout memory. This produces less predictable memory access and poorer cache performance.
Linked lists exchange fast insertion and removal for slow positional access and less efficient iteration.
Because of these trade-offs, linked lists are relatively uncommon for ordinary ordered collections, but they are valuable as building blocks for more complex structures.
Linked Lists, Pointers, and the Heap
A linked list does not always visibly use array indexes. In many programming languages, nodes are created using operations such as:
newmallocReferences
Pointers
In such implementations, each node stores a pointer or reference to the next node instead of an explicit array index.
At the lowest level, however, a pointer is essentially an address or index into memory. The memory itself can still be viewed as a large array.
When a program dynamically allocates an object, it interacts with a memory-management structure commonly called the heap. The heap manages regions of the larger memory array and provides dynamically allocated objects to the program.
The heap must support many different allocation patterns, so its implementation is highly general. As a result:
Dynamically allocating each linked-list node separately may involve additional overhead.
Nodes may be scattered throughout memory.
Access may have worse cache behavior than a linked list stored compactly inside one manually managed array.
A custom array-based representation can sometimes improve performance by controlling placement and using integer indexes rather than individually allocated nodes.
Hashmaps
A hashmap, also called a dictionary, stores data so that it can be looked up using a key that is not necessarily a numerical array index.
Examples of keys include:
Strings.
Usernames.
Product codes.
Email addresses.
Identifiers.
For example, a hashmap might associate flower names with prices:
Key: flower name.
Value: flower price.
Hash Functions
Because the underlying storage is still an array, a hashmap must convert an arbitrary key into an array index.
A hash function performs this conversion:
A good hash function spreads keys relatively evenly across a large numerical range. The output may be as large as the range of a 32-bit or 64-bit integer.
That output is usually too large to use directly as an array index, so it is reduced using the modulo operator.
If the backing array has length C and the hash function produces h, the array index is:
This maps the hash value into the valid index range:
The process is therefore:
Apply the hash function to the key.
Compute the result modulo the array length.
Use the resulting number as the candidate array index.
Hash Collisions
A collision occurs when two different keys produce the same array index.
For example:
Although the keys differ, both map to the same position.
A hashmap must use a collision-resolution strategy.
Collision Resolution with One Array
One approach stores all entries in a single array.
When a collision occurs:
The hashmap checks the candidate position.
If the position contains the desired key, the value is found.
If the position contains a different key, the hashmap checks the next position.
This continues until the key is found or an empty position is reached.
Each entry must store identifying information, such as the original key, because the hash index alone does not prove that the entry is the requested one.
This method is often called probing or open addressing.
Clustering
A disadvantage is the formation of clusters: long consecutive runs of occupied array positions.
When clusters form:
Searches may need to inspect many positions.
Insertions may need to scan through long runs.
Performance becomes worse as the array fills.
The original hash value may point to the beginning of a cluster, requiring a long sequence of comparisons before the correct key or an empty location is found.
Collision Resolution with Two Arrays
Another approach uses two arrays:
A primary array stores the first entry associated with each hash position.
A second array stores entries that collide with existing entries.
Each collision entry stores:
The key and associated value.
An index pointing to the next collision entry.
The collision entries form a linked list.
To search:
Hash the key.
Use the hash result to locate the first entry in the primary array.
Compare its key with the requested key.
Follow the linked-list links through the collision array if necessary.
Stop when the key is found or the chain ends.
This avoids long consecutive clusters in the primary array.
Multiple Linked Lists in One Array
A particularly useful property of linked lists is that several independent linked lists can be interleaved within one underlying array.
The entries belonging to one collision chain do not need to be stored consecutively. Each entry points to the next relevant entry, so unrelated entries can appear between them physically.
This allows the second array to hold many separate collision chains without allocating a separate array list for each hash bucket.
Using array lists for each collision bucket would require:
One separate list for every bucket.
Many individual allocations.
Capacity planning for each list.
Resizing when the distribution of collisions is not known in advance.
A shared collision array with linked indexes avoids much of this overhead.
Linked lists are useful in hashmaps because their elements can be distributed throughout one shared array while links preserve the structure of each separate collision chain.
Trees
A tree is a data structure that represents hierarchical relationships between elements.
Trees are useful when elements are organized according to relationships such as:
User-interface containers and their child controls.
File systems and folders.
Organizational structures.
Categories and subcategories.
Syntax structures in programming languages.
In a user interface, an element may be positioned relative to its parent rather than directly relative to the screen. When the parent moves, its children move automatically as part of the hierarchy.
Tree Terminology
Each element in a tree is called a node.
The relationship between nodes has a direction:
The node higher in the relationship is the parent.
The node lower in the relationship is the child.
Tree relationships have these properties:
A parent may have multiple children.
Each child has only one parent.
Relationships generally proceed from the top of the hierarchy downward.
The node at the top is commonly called the root.
The one-parent restriction is what distinguishes a tree from a more general graph.
Implementing a Tree with Arrays
A tree can be implemented using two arrays and linked-list-style indexes.
First Array: Nodes
The first array stores all tree nodes.
Each node contains:
Its data.
An index pointing to the first child relationship in the second array.
Second Array: Child Relationships
The second array stores relationships between parents and children.
Each relationship contains:
The index of the child node in the first array.
The index of the next child relationship in the second array.
The child relationships for a particular parent form a linked list.
Traversing a Tree
Suppose a user interface contains:
A root dropdown.
A menu item called “New.”
Two children under that menu item: text and an icon.
To reach the icon:
Start at the root node.
Follow its child index into the relationship array.
Follow the relationship’s node index back into the node array to reach the first child.
Follow that child’s child index into the relationship array.
Skip the first child relationship by following its
nextlink.Follow the second relationship’s node index back into the node array to reach the icon.
The node array stores the objects, while the relationship array stores the links among them.
There are many possible array-based tree representations:
Some pack the entire tree into one array.
Some use multiple arrays.
Some use specialized layouts optimized for large trees.
The best representation depends on the expected data and access patterns.
Graphs
A graph is a more general relationship structure than a tree.
A graph consists of:
Nodes, also called vertices.
Edges, which represent relationships between nodes.
Trees as Constrained Graphs
A tree can be viewed as a restricted graph.
A tree requires:
Relationships to proceed in a hierarchical direction.
Each child to have only one parent.
No arbitrary connections between unrelated branches.
A graph relaxes these restrictions. In a graph:
A node can have multiple incoming relationships.
A node can have multiple outgoing relationships.
Relationships may connect nodes in many directions.
A node can have multiple parents.
The progression can be understood as follows:
A linked list allows one previous and one next relationship.
A tree allows one parent and multiple child relationships.
A graph allows multiple relationships in both directions.
Graph Implementation with Arrays
Graphs can usually be implemented with the same two-array approach used for trees:
The first array stores the nodes.
The second array stores the edges.
Each node stores an index pointing to its first edge.
Each edge stores the index of the connected node and the index of the next edge in the chain.
The main difference between a tree and a graph is not necessarily the physical arrangement of the arrays. It is the meaning of the relationships and the operations performed on them.
Traversing in Both Directions
A tree generally needs to be traversed from parent to child. A graph may need to be traversed in any direction.
To make an edge accessible from both connected nodes, the representation may store a duplicate relationship or vertex reference. This allows traversal from either endpoint.
Some specialized graph types use different layouts, but two arrays—one for nodes and one for edges—are sufficient for many general graph implementations.
Pathfinding
A well-known graph application is A, pronounced “A-star.”
A is a pathfinding algorithm that searches for an efficient or shortest route between two points. It is widely used in video games to calculate routes such as:
A character moving from its current position to a target.
A vehicle navigating a road network.
An agent moving through a maze or map.
The graph represents possible locations and connections:
Nodes represent locations.
Edges represent possible movements between locations.
Edge information may include movement cost or distance.
The algorithm then evaluates possible paths to find a suitable route.
Choosing a Data Structure
The correct data structure depends on the actual data and the expected access pattern.
Arrays and Array Lists
Arrays and array lists are suitable when:
Direct indexed access is important.
Elements are often read by position.
Data is commonly appended to the end.
Memory locality and fast iteration matter.
They are less suitable when frequent insertion or removal occurs near the beginning or middle.
Stacks
Stacks are suitable when:
Only the most recently added item needs to be accessed.
Operations follow last-in, first-out behavior.
Undoing or reversing actions is required.
Insertions and removals occur only at the end.
Queues
Queues are suitable when:
Items must be processed in arrival order.
The oldest waiting item should be handled first.
Requests or tasks need fair sequential processing.
Circular queues are especially useful when a fixed-size array should be reused without shifting elements.
Linked Lists
Linked lists are suitable when:
Elements must be inserted or removed frequently.
A direct reference to a neighboring element is available.
The collection’s logical order differs from physical memory order.
The structure will serve as a component inside another data structure.
They are less suitable when:
Fast indexed access is required.
Sequential iteration performance is critical.
Cache-friendly memory access is important.
Hashmaps
Hashmaps are suitable when:
Values need to be retrieved by arbitrary keys.
Direct numerical indexes are unavailable or inconvenient.
Fast average-case lookup is more important than preserving a natural order.
Their effectiveness depends on:
The quality of the hash function.
The backing-array capacity.
The collision-resolution strategy.
The distribution of keys.
Trees and Graphs
Trees are suitable when:
Data has a strict hierarchy.
Each item has one parent.
Parent-child relationships are central.
Graphs are suitable when:
Items can have multiple relationships.
Connections may exist in multiple directions.
Arbitrary networks or routes must be represented.
Pathfinding or relationship traversal is required.
Central Principles
Every data access strategy ultimately reduces to calculating an index into an array of memory.
The main principles are:
Memory behaves like an array: It supports reading and writing at addresses.
Data arrangement matters: Different orders make different operations efficient.
Data structures combine organization and logic: They define how elements are arranged and how operations locate them.
Efficiency depends on access patterns: A structure is effective only when its strengths match the operations the program performs.
Indexes can represent relationships: Linked lists, trees, graphs, and hashmaps can all use indexes to connect elements stored in arrays.
No structure is optimal for every task: Improving one operation often creates trade-offs elsewhere.
Simple arrays are powerful building blocks: Many sophisticated structures can be implemented using arrays plus carefully designed indexes and rules.
A practical approach to a new programming problem is to begin with a simple array-based design, determine which operations are needed, and then introduce additional structure only when the data or performance requirements justify it.

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