1. Home
  2. Explore
  3. Computer Science
  4. Computer Memory and Arrays

Study methods

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

Computer Memory and Arrays

Data Structures: Building Everything on Arrays

Computer memory can seem mysterious because memory addresses are often large hexadecimal numbers, but the underlying idea is surprisingly simple. At the lowest conceptual level, memory can be viewed as a long array of small storage locations.

Each location holds a basic unit of data, such as a byte, and each location has a sequential number called an address. The computer’s fundamental operations are:

  1. Read the data stored at a particular address.
  2. Write data to a particular address.

This simple model is the foundation for understanding data structures. Every more advanced structure—lists, stacks, queues, hashmaps, trees, and graphs—is ultimately a strategy for organizing data in memory and finding the right location efficiently.

A data structure is a strategy for arranging data and finding, inserting, or removing it in an underlying array of memory.

Memory as an Array

An array is a collection of elements stored in an ordered sequence. Each element is identified by an index, and an index tells the computer where to look.

For example, a one-element array has only one possible position:

IndexData
000A

If the array stores one character, the character must go at index 000. There is no alternative because the array contains only one location.

With two elements, however, the order matters. If the elements are A and B, the possible arrangements are:

  • A, B
  • B, A

With three distinct elements, such as A, B, and C, there are:

  • A, B, C
  • A, C, B
  • B, A, C
  • B, C, A
  • C, A, B
  • C, B, A

The number of possible arrangements of nnn distinct elements is described by the factorial function:

n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n-1) \times (n-2) \times \cdots \times 1n!=n×(n−1)×(n−2)×⋯×1

For three elements:

3!=3×2×1=63! = 3 \times 2 \times 1 = 63!=3×2×1=6

For a million elements, the number of possible arrangements is:

1,000,000!1{,}000{,}000!1,000,000!

That number is unimaginably large. This matters because the way elements are arranged can make some questions easy and other questions difficult.

The Limits of Basic Memory Operations

Suppose an array contains one million random English characters, and the task is to determine whether the letter Z appears anywhere.

The computer can only read an element at a time by using its index. If the characters are randomly arranged, there is no safe shortcut. The search must begin at index 000 and continue through the array until either:

  • Z is found, or
  • the end of the array is reached.

The worst case requires checking every element.

Now suppose the same characters are sorted alphabetically. Finding whether Z appears becomes much easier. The final element is the largest character in the sorted array. Therefore:

  • If the final element is Z, the array contains Z.
  • If the final element is not Z, the array cannot contain Z.

The same data has been arranged differently, and that arrangement has changed the difficulty of the search.

However, a sorted array does not automatically make every question easy. Suppose the task is to find the most frequent character. Even though the characters are alphabetically sorted, the final element does not reveal which character occurs most often. The array may need to be examined throughout.

An arrangement sorted by frequency would make that particular question easier: the most frequent character could be placed at the beginning. The important lesson is that each arrangement helps with some operations but not others.

Think About It

If an array is sorted by a user’s last name, which operation is likely to be easy, and which operation might still require examining many elements?

What a Data Structure Really Is

A data structure combines two ideas:

  1. An arrangement of elements
  2. A set of operations for using that arrangement

The arrangement determines where elements are placed. The operations determine how the computer searches for, inserts, removes, or updates them.

For example, a sorted array arranges elements according to some ordering, such as alphabetical order or numerical order. Its search logic can take advantage of that ordering.

The elements do not always have to be sorted according to their entire contents. Consider a collection of user objects. Each user might contain several fields:

  • User ID
  • Name
  • Email address
  • Other information

The array could be sorted by user ID even though the user object contains many other fields. In this case, the ordering is based on one selected field.

Multiple Index Arrays

Sometimes the same data must be searched according to several different properties. A user database might need efficient lookup by both:

  • User ID
  • User name

Duplicating every user object into two separately sorted arrays would waste memory. Instead, the program can maintain:

  • One array containing the actual user objects
  • One array of indexes sorted by user ID
  • Another array of indexes sorted by user name

The index arrays do not contain duplicate users. They contain references to the locations of users in the main array.

For example, if a user object is stored at position 171717 in the main array, an index array might contain the number 171717. That number tells the program where to find the actual user.

This is conceptually similar to a library. A physical book exists in one location, but a catalog can organize references to that book by:

  • Title
  • Author
  • Genre

The catalog does not need to create a second physical copy of the book for every search category. It only needs to provide directions to the book’s stable location.

Pointers as Locations

A pointer is a value that identifies where some other data is stored. At the conceptual memory level, a pointer can be understood as an index into the memory array.

A pointer does not usually contain the object itself. Instead, it answers the question:

“Where can the actual object be found?”

This distinction allows many different structures to refer to the same underlying object without copying that object.

Think About It

Why might an application use several arrays of indexes instead of duplicating the full user objects in several differently sorted arrays?

Array Lists

An array list is an ordered collection that behaves like an array but provides additional operations. It normally 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

The important difference between an ordinary array and an array list is that an ordinary array has a fixed length, while an array list can grow and shrink from the programmer’s perspective.

Capacity and Size

An array list usually uses an array internally. That underlying array is called the backing array.

The backing array has a fixed amount of storage called its capacity. The array list separately tracks how many positions are currently being used. This number is called the size or count.

For example:

  • Backing-array capacity: 101010
  • Current list size: 444

The list contains four elements, but the backing array has room for six more.

When an element is added to the end:

  1. The list uses its current size as the next array index.
  2. It writes the new element there.
  3. It increases the size by one.

If the backing array becomes full, the list must obtain a larger array and copy the existing elements into it. The source material emphasizes the distinction between the list’s logical number of elements and the backing array’s physical capacity.

Removing from the Middle

Suppose an array list contains:

IndexElement
000A
111B
222C
333D

If the element at index 111 is removed, the list cannot simply leave a hole if it wants to preserve its ordered structure. It must shift later elements backward:

IndexElement
000A
111C
222D

The elements after the removed element must each be:

  1. Read from their current positions
  2. Written to the preceding positions

The farther toward the beginning the removal occurs, the more elements may need to be copied.

Inserting into the Middle

Insertion is the opposite process. If a new element is inserted at index 111, existing elements must move forward to make room:

BeforeAfter
A, B, CA, X, B, C

The program must copy later elements toward the end before writing the new element into the opened position.

This illustrates a general principle:

A data structure’s performance depends on whether its organization supports the operations the program performs most often.

An array list is excellent when elements are accessed by index and new elements are commonly added at the end. It is less efficient when elements are frequently inserted or removed near the beginning or middle because many elements must be shifted.

Think About It

Why is adding an element at the end of an array list usually simpler than inserting one at the beginning?

Stacks

A stack is an ordered structure that permits adding and removing elements only at one end. That end is called the top.

A stack behaves like a physical stack of blocks. The only block immediately available is the top block. To reach a block underneath, every block above it would have to be removed first.

The defining rule is:

The most recently added element is the first one removed.

This is called last in, first out, or LIFO.

Stack Operations

A stack is often implemented using an array and a count:

  • The array stores the elements.
  • The count identifies how many elements are currently in the stack.
  • The final occupied position is the top.

Pushing

Adding an element is called pushing.

If the current count is nnn, the new element is written at index nnn, and the count increases:

new count=n+1\text{new count} = n + 1new count=n+1

Popping

Removing the top element is called popping.

If the stack contains nnn elements, the top is at index n−1n-1n−1. Removing it requires only decreasing the count:

new count=n−1\text{new count} = n - 1new count=n−1

No later elements need to be moved because there are no elements after the top.

This makes adding and removing at the end especially efficient. Adding to the end is a special case of insertion, and popping from the end is a special case of removal. In both cases, there are no subsequent elements to shift.

Example: Undo History

A text editor can use a stack to store changes.

Each time a user makes a change, the editor pushes that change onto the stack. When the user selects Undo, the editor pops the most recent change.

This matches the expected behavior: the newest change is undone first.

Redo can be supported using a second stack:

  • Undo stack: stores changes that can be undone
  • Redo stack: stores changes that can be restored

When a user performs Undo, the change can move from the undo stack to the redo stack. If the user then makes a completely new change, the redo stack is cleared because the previous redo history no longer matches the new editing path.

Think About It

Why would a stack be a better choice than an ordinary array list for an undo system?

Queues

A queue is similar to a stack but allows removal from the front as well as insertion at the back.

A queue follows the rule:

The first element added is the first element removed.

This is called first in, first out, or FIFO.

A real-world line of people is a useful analogy. The person who arrives first is normally served first.

Why Order Matters

Consider a web server receiving requests. If the server uses a stack, each new request is placed above older requests. Under heavy load, an old request near the bottom might be delayed indefinitely.

A queue processes requests in arrival order:

  1. New requests enter at the back.
  2. The oldest request leaves from the front.
  3. Responses are produced in a fairer order.

This can provide a more reasonable response experience than repeatedly prioritizing the newest request.

The Naive Array Approach

Removing an element from the end of an array is simple: the count can be reduced.

Removing the first element seems more difficult. If the first item is deleted, every later element would need to shift backward by one to fill the empty position.

For a large queue, repeatedly copying all remaining elements would be inefficient.

A Queue with Start and End Indexes

A more effective array-based queue stores additional information:

  • Start index: where the first queue element is located
  • End index: where the next element can be added, or the logical end of the queue
  • Capacity: the length of the backing array

When the front item is removed, the queue does not copy anything. It simply increases the start index by one.

The old element is treated as no longer belonging to the queue.

This creates unused space at the beginning of the array. Eventually, the indexes could move beyond the array’s capacity, even though there may be available space at the beginning.

Circular Queues and Modulo

A circular queue solves this problem by treating the backing array as if its end connects back to its beginning.

Whenever the queue accesses an array position, it uses the modulo operator:

physical index=logical index mod capacity\text{physical index} = \text{logical index} \bmod \text{capacity}physical index=logical indexmodcapacity

The modulo operation produces a repeating sequence of indexes from 000 through capacity−1\text{capacity}-1capacity−1.

For an array with capacity 555, the logical indexes map like this:

Logical indexPhysical index
000000
111111
222222
333333
444444
555000
666111

When the end moves past the final physical position, it wraps around to index 000. The queue can therefore reuse spaces that were freed at the beginning.

This arrangement is similar to a game of Snake moving around the edges of the screen: the logical sequence continues forward while the physical positions wrap around.

Think About It

How does a circular queue prevent the repeated copying that would be required when removing items from the front of an ordinary array?

Linked Lists

A linked list stores elements in a logical order without requiring them to appear in that order physically in the underlying array.

Each element is stored in a node containing:

  • The element’s data
  • A link to the next element

In an array-based implementation, the link can be an index identifying where the next node is stored.

Building a Linked List

Suppose the first user is placed at index 000:

Array indexUserNext index
000User 1none

A second user, User 3, might be placed at index 111:

Array indexUserNext index
000User 1111
111User 3none

The next index of User 1 points to User 3.

Now suppose User 2 must be placed between User 1 and User 3. The new node does not need to be inserted physically between them. It can be added at another free position, such as index 222:

Array indexUserNext index
000User 1222
111User 3none
222User 2111

The logical order is now:

User 1→User 2→User 3\text{User 1} \rightarrow \text{User 2} \rightarrow \text{User 3}User 1→User 2→User 3

The physical array order is different, but the links define the list’s order.

Insertion and Removal

To insert User 2 between User 1 and User 3:

  1. Store User 2 in an available array position.
  2. Change User 1’s next link to point to User 2.
  3. Set User 2’s next link to point to User 3.

To remove User 3:

  1. Find the node before User 3.
  2. Change that node’s next link to indicate the element after User 3.
  3. If User 3 was at the end, the next link becomes a special end marker, such as −1-1−1.

No later elements need to be shifted. This gives linked lists strong insertion and removal performance when the relevant neighboring node is already known.

The Cost of Finding Elements

Linked lists sacrifice efficient indexed access.

In an array, the element at index 300,000300{,}000300,000 can be accessed directly. In a linked list, the element’s physical position may have no relationship to its logical position. To find the element at logical position 300,000300{,}000300,000, the program may need to:

  1. Start at the first node.
  2. Follow the next link.
  3. Repeat this process 300,000300{,}000300,000 times.

Thus, a linked list is useful when the program already has a direct reference to the position where insertion or removal should occur, but less useful when the program frequently asks for the element at a particular numerical position.

Linked lists can also be slower to iterate through than arrays because their nodes may be scattered throughout memory. The processor’s cache works especially well when nearby data is stored close together. A linked list’s scattered access pattern can therefore produce poorer cache performance.

Pointers, References, and the Heap

Some programming languages implement linked lists using pointers or references rather than explicit array indexes. This does not contradict the array-based memory model.

At the lowest level, pointers are still locations in memory. When a program uses an allocation operation such as new or malloc, it requests memory from a system commonly called the heap.

The heap is itself a data structure built over the computer’s memory array. It manages which regions of memory are available and assigns them to requested objects.

Because heap allocation must support many different kinds of workloads, it is designed to be general-purpose. A manually managed array of nodes may sometimes have better performance because the program knows exactly how the nodes will be used and can arrange them more deliberately.

Think About It

What does a linked list gain by separating logical order from physical array order, and what does it lose?

Hashmaps

A hashmap, also called a dictionary, stores values using keys rather than ordinary numerical indexes.

For example, a flower-price hashmap might associate:

  • "rose" with a price
  • "tulip" with a price
  • "lily" with a price

The key is the name used to find the value.

The challenge is that the underlying array requires a numerical index, while the key may be a string. A hashmap solves this using a hash function.

Hash Functions

A hash function accepts a key and produces a number:

hash(key)→number\text{hash}(\text{key}) \rightarrow \text{number}hash(key)→number

A good hash function spreads different keys reasonably evenly over a large numerical range.

The output might be large enough to use the full range of a 323232-bit or 646464-bit integer, so it cannot necessarily be used directly as an array position. The hashmap converts it into a valid array index with modulo:

array index=hash(key) mod array length\text{array index} = \text{hash}(\text{key}) \bmod \text{array length}array index=hash(key)modarray length

The result is always within the range:

0≤array index<array length0 \leq \text{array index} < \text{array length}0≤array index<array length

The key has therefore been transformed into a location in the backing array.

Collisions

Different keys can produce the same array index. This is called a collision.

For example:

hash("rose") mod 10=4\text{hash}(\text{"rose"}) \bmod 10 = 4hash("rose")mod10=4

and

hash("lily") mod 10=4\text{hash}(\text{"lily"}) \bmod 10 = 4hash("lily")mod10=4

Both keys map to index 444, so the hashmap needs a collision-handling strategy.

Collision Handling with One Array

One approach stores all entries in a single array.

When a collision occurs:

  1. The program checks the calculated index.
  2. If that position contains the desired key, the operation is complete.
  3. If the position contains a different key, the program checks the next position.
  4. This continues until the key is found or an empty position is reached.

Each stored entry must include identifying information, such as its original key. The hashmap cannot rely only on the calculated index because several different keys may map there.

A disadvantage is the formation of clusters: long consecutive runs of occupied positions. When clusters form, searches may need to inspect many entries before finding either the desired key or an empty location.

Collision Handling with Two Arrays

Another approach uses two arrays:

  1. A first array stores the first entry associated with each hash bucket.
  2. A second array stores entries that collide with one another.

Each collision entry contains a link to the next collision entry. The colliding entries therefore form a linked list.

A lookup works as follows:

  1. Hash the key.
  2. Convert the hash into an index in the first array.
  3. Find the first entry for that bucket.
  4. Compare its key with the requested key.
  5. Follow linked references through the collision entries until the key is found or the chain ends.

This approach uses linked lists to keep collision groups separate. The second array may contain several different linked lists interleaved with one another. That is acceptable because the links define each list’s order; physical adjacency is unnecessary.

This is one of the useful properties of linked lists:

Multiple independent linked lists can share one underlying array, even when their elements are mixed together physically.

If separate array lists were used for each collision bucket, the program would need to allocate and manage a separate dynamic structure for every bucket. It would also be difficult to predict how much space each bucket would need because the distribution of collisions is not known in advance.

Think About It

Why must a hashmap store the original key along with the value?

Trees

So far, the relationships among elements have mainly described sequence: one element comes before or after another. Some problems require richer relationships.

A user interface is a good example. A screen may contain:

  • A window
  • Panels inside the window
  • Buttons and text fields inside the panels
  • Icons or labels inside the buttons

An element can be positioned relative to a parent rather than directly relative to the screen. If the parent moves, the children move with it. This creates a hierarchy.

A tree is a data structure used to represent hierarchical relationships.

Tree Terminology

A tree consists of nodes connected by relationships.

  • The node above another node is its parent.
  • The node below another node is its child.
  • The node at the top is the root.
  • A parent may have multiple children.
  • Each child has only one parent.

The relationships point in one direction, from parent to child.

A tree is therefore more flexible than a linked list in one direction because a node can point to several children rather than only one next element.

Implementing a Tree with Arrays

A tree can be implemented using two arrays:

  1. A node array containing the actual tree nodes
  2. A relationship array containing links between parents and children

Each node stores an index pointing to its first child relationship. Each relationship contains:

  • The index of a child node in the node array
  • The index of the next child relationship in the relationship array

The child relationships form a linked list.

For example, suppose a menu item has two children:

  • Text reading “New”
  • An icon

The node for the menu item points to the first child relationship. That relationship points to the text node and also points to the next relationship. The next relationship points to the icon node.

To traverse from the menu item to the icon:

  1. Follow the menu item’s child index to the first relationship.
  2. Follow the relationship’s next-child link to the second relationship.
  3. Follow the second relationship’s node index to the icon node.

The nodes do not need to be stored next to one another in the underlying array. The relationships provide the logical structure.

There are other tree implementations. Some can pack the entire tree into one array, while others may perform better for particular tree sizes and access patterns. The best representation depends on the type of data and the way the program expects to use it.

Think About It

Why is a tree more suitable than a simple linked list for representing a user-interface hierarchy?

Graphs

A graph is a more general structure than a tree. It consists of:

  • Nodes, sometimes called vertices
  • Edges, which represent relationships between nodes

A tree restricts each child to one parent. A graph removes that restriction, allowing a node to have multiple connections from other nodes.

The progression can be understood this way:

  1. A linked list gives each element a link to one next element.
  2. A tree allows each node to link to multiple children.
  3. A graph allows nodes to have multiple connections in different directions.

The relationships in a graph do not have to form a simple hierarchy.

For example, a road network can be represented as a graph:

  • Intersections are nodes.
  • Roads are edges.
  • A location may be reachable from several other locations.

Similarly, a social network can represent people as nodes and relationships as edges.

Graphs and Trees

A tree is a constrained type of graph because:

  • A tree has parent-child relationships.
  • Each child has one parent.
  • Relationships form a hierarchy.

A graph can be less restrictive:

  • A node may have multiple incoming connections.
  • A node may have multiple outgoing connections.
  • Relationships may exist in many directions.

The data arrangement for a tree and a graph can be very similar. Both can use:

  1. An array of nodes
  2. An array of relationships

For a graph, each node stores the index of its first edge, and the edges form a linked list of connections.

The major difference is not necessarily how the data is stored. The difference is how the relationships are interpreted and how operations traverse them.

If traversal must work in both directions, the graph may store duplicate or reverse-accessible edge information so that a connection can be followed from either endpoint.

Pathfinding

One well-known graph application is A*, pronounced “A-star.” A* is a pathfinding algorithm that searches for a short or efficient route between two points.

Video games frequently use pathfinding to determine how a character can travel from a current location to a target location. The game world can be represented as a graph:

  • Walkable locations become nodes.
  • Connections between locations become edges.
  • The pathfinding algorithm evaluates possible routes.

The structure of the graph provides the relationships. The algorithm determines how to navigate those relationships to find a suitable path.

Think About It

What restriction separates a tree from a general graph?

Choosing the Right Data Structure

No data structure is universally best. Each one organizes elements in a way that favors particular operations.

Data structureMain organizationStrengthLimitation
ArrayElements stored by numerical indexDirect indexed accessFixed length and costly middle changes
Array listOrdered elements over a backing arrayFlexible size and efficient end additionsMiddle insertion and removal require shifting
StackAccess restricted to the topEfficient push and popCannot directly remove arbitrary elements
QueueAdd at the back, remove at the frontProcesses items in arrival orderRequires careful front and back management
Linked listNodes connected by linksEfficient insertion and removal with a known locationSlow indexed access and weaker cache behavior
HashmapKeys converted to array indexesFast key-based lookup when well organizedMust handle collisions
TreeHierarchical parent-child linksRepresents nested relationshipsTraversal depends on tree organization
GraphGeneral node-and-edge relationshipsRepresents complex connectionsRequires more involved traversal logic

The correct choice depends on the data and the expected access pattern.

For example:

  • A stack suits undo history because the newest change is handled first.
  • A queue suits incoming web requests because requests should be processed in arrival order.
  • A linked list suits situations with frequent insertions and removals where the relevant location is already known.
  • A hashmap suits lookup by names, IDs, or other keys.
  • A tree suits hierarchical structures such as menus.
  • A graph suits networks and pathfinding.
  • An array list suits collections that need indexed access and frequent changes at the end.

The programming language may provide these structures as convenient built-in types, but convenience does not remove their underlying trade-offs. Every operation ultimately becomes reads and writes to memory locations. If a structure’s organization requires many elements to be copied, a language cannot eliminate that fundamental work.

Comprehensive Review

Computer memory can be modeled as a large array of addressable locations. At the most basic level, the computer performs two operations: reading from an address and writing to an address.

From this foundation, data structures arise by arranging elements and defining rules for locating and modifying them. A sorted array makes some searches easy because its order provides useful information. An array list adds flexible logical sizing but must shift elements during middle insertion and removal. A stack restricts operations to the end, producing efficient push and pop behavior. A queue processes items in arrival order and can use modulo arithmetic to wrap through a circular backing array.

A linked list separates logical order from physical array order by storing links between nodes. This makes insertion and removal efficient when a nearby node is already known, but it makes indexed access and iteration less efficient. Pointers and references represent memory locations, while heap allocation provides a general system for obtaining those locations.

A hashmap converts arbitrary keys into array indexes with a hash function and modulo arithmetic. Because different keys can map to the same index, collisions must be handled, either by searching through nearby array positions or by linking collision entries together.

Trees represent one-directional hierarchies in which parents can have multiple children but each child has one parent. Graphs generalize this idea by allowing nodes to have multiple relationships in multiple directions. Both can be implemented with arrays of nodes and arrays of linked relationships.

The central idea is simple but powerful:

Every data-access strategy eventually reduces to finding an index in an array of memory.

The best data structure is the one whose organization matches the operations the program performs most often.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent