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

Speaker 1Speaker 2

Computer Memory and Arrays

13:00
0:00-13:00
  1. Anna

    Let's begin with a surprisingly powerful idea: computer memory can be viewed as a long line of tiny boxes. Each box stores a basic unit of data, such as a byte, and each box has a sequential number called its address.

  2. Michael

    And the computer gives us an extremely simple interface for using those boxes. If we know an address, we can either write data to it or read data from it.

  3. Anna

    That should sound familiar to programmers, because conceptually it's an array. In software terms, memory is essentially a very large array, even though addresses are often displayed as hexadecimal numbers. A memory address is just another way of describing an index into that array.

  4. Michael

    So everything that runs on a computer is ultimately built on top of that array, using only two fundamental operations: reading from an index and writing to an index.

  5. Anna

    Exactly. Start with the simplest possible memory: an array containing one byte. If we want to store one character, there's no decision to make. The character goes into index zero.

  6. Michael

    But with two elements, choices appear. If we have two characters, we can store them in either order. With three distinct elements, there are six possible arrangements, which is three factorial.

  7. Anna

    In general, an array of distinct elements can be arranged in a number of ways described by a factorial. As the number of elements grows, the number of possible orderings increases astronomically. That matters because different orderings can make different questions easy or difficult.

  8. Michael

    For example, imagine a million boxes containing random English characters. If I ask whether the letter Z is present, our only general option is to start at address zero and inspect every character until we find Z or reach the end.

  9. Anna

    Right. In the worst case, that takes a very long time. But if I tell you the characters are sorted alphabetically, the same question becomes trivial: inspect the last element. If it is Z, then Z is present; otherwise, it is not.

  10. Michael

    Now change the question. What is the most frequent character? Even with the characters alphabetically sorted, you may still need to examine the whole array, because the most frequent character could be anywhere in that ordering.

  11. Anna

    Unless we choose a different ordering. If the characters are arranged by frequency, with the most frequent character first, then that question becomes much faster. The broader lesson is that every possible ordering has strengths and weaknesses.

  12. Michael

    That leads to the first foundational idea: because every data access eventually becomes an array-index calculation, programming strategies ultimately need to figure out which index contains the desired data.

  13. Anna

    The second idea is that the arrangement of elements determines which operations are efficient. A data structure is therefore a strategy for finding and manipulating things in an array.

  14. Michael

    A data structure has two main parts. One is the ordering or arrangement of elements in the underlying array. The other is the logic for operations such as finding, inserting, and removing elements.

  15. Anna

    A sorted array is the basic example. If the elements themselves are simple characters, we can sort them directly. But real data is often made of larger objects, such as users, and we might sort those objects by a field like user ID.

  16. Michael

    And sometimes we need more than one way to find the same objects. Suppose we need to look up users both by ID and by name. We can keep one array containing the actual user objects, then create separate arrays of indexes: one sorted according to user names and another sorted according to user IDs.

  17. Anna

    Those indexes function like pointers to the actual user objects. A useful analogy is a library. The physical book exists in one stable location, while catalog systems can help you find it by title, author, or genre without duplicating the entire library.

  18. Michael

    Let's move to the array list. An array list is an ordered collection that supports arbitrary index access like an array, but it also allows elements to be added to the end and removed from arbitrary positions.

  19. Anna

    The underlying array has a fixed length called its capacity. Separately, the list stores a size or count that tells us how many positions are currently being used. Adding an element means using the current count as the next array index, writing the new value there, and increasing the count.

  20. Michael

    Removing an element from the middle is more expensive. Since the underlying array cannot physically remove a memory location, every later element has to be copied backward by one position to fill the gap.

  21. Anna

    Insertion in the middle is the mirror image. The later elements must be copied forward to create an empty position. For a very large list, these reads and writes can be costly.

  22. Michael

    That is why language-provided operations are not automatically fast. A list may look abstract and convenient, but its performance still depends on the array arrangement underneath and on the access pattern your program uses.

  23. Anna

    Stacks and queues make a different trade-off. They restrict where insertion and deletion can happen, and that restriction can give them excellent performance.

  24. Michael

    A stack allows changes only at one end, called the top. Think of physical blocks stacked vertically: to reach a block lower down, you first have to remove the blocks above it.

  25. Anna

    A stack can be implemented using an array and a count, just like an array list. To push an item, write it after the current last item and increase the count. To pop an item, simply decrease the count, because there are no later elements that need to be shifted.

  26. Michael

    That makes adding and removing at the end special cases of array-list insertion and removal. If the data pattern really is last-in, first-out, stacks are both simple and fast.

  27. Anna

    Undo history in a text editor is a classic example. Each change can be pushed onto a stack, and pressing undo removes the most recent change. Redo can be handled with a second stack of redoable changes; if the user makes a brand-new change, the redo stack is emptied.

  28. Michael

    A queue extends the idea by allowing removal from the front as well as insertion at the back. Queues process items in the order they arrive, which is useful for a web server handling incoming requests.

  29. Anna

    Using a stack for requests could cause older requests to remain buried under newer ones, potentially never being processed under heavy load. A queue instead sends responses in the same order requests arrived, producing a more reasonable response pattern.

  30. Michael

    Removing from the front of a normal array sounds expensive because every remaining item would need to shift backward. But a queue can avoid that by storing a start index and an end index.

  31. Anna

    When the front item is removed, or dequeued, we simply increase the start index and treat the old position as no longer part of the queue. The problem is that the start index eventually moves past the end of the backing array, leaving dead space.

  32. Michael

    The solution is a circular queue. Whenever we access the backing array, we take the index modulo the array's capacity. Modulo creates a repeating range of indexes, so when the end reaches the array's boundary, it wraps back to zero.

  33. Anna

    The queue can then wrap around the array like a game of Snake. Items are added at the back and removed at the front without reallocating or copying the entire collection.

  34. Michael

    Next is the linked list. Instead of relying on physical array order, a linked list stores each element together with an index pointing to the next element in the list.

  35. Anna

    For example, user one might be stored at array index zero and user three at array index one. If user two is inserted between them, user two can be added at the next available array position, and the links can be changed so the logical order becomes user one, user two, user three.

  36. Michael

    Removing user three is similarly simple: change user two's next index to minus one, indicating that user two is now the end of the list. No later elements need to be shifted.

  37. Anna

    But linked lists give up efficient positional access. If the list has a million items and we want position 300,000, we may have to start at the first node and follow the next link 300,000 times.

  38. Michael

    So linked lists offer fast insertion and removal when we already have a direct reference to the relevant neighboring element, but poor access by position. Iteration can also be slower than array iteration because the elements may be spread through memory, producing poorer cache performance.

  39. Anna

    In many programs, linked-list nodes are created with a language feature such as new or malloc, and the links are represented by pointers or references rather than integer indexes. That is still consistent with the array model: at the lowest level, a pointer is essentially an index into memory.

  40. Michael

    The language or standard library usually provides a heap for those allocations, and that heap is itself built on memory. Because a general-purpose heap must support many different workloads, managing linked-list nodes inside your own array may sometimes perform better than allocating each node separately.

  41. Anna

    A hashmap, also called a dictionary, uses a non-numerical key, such as a string, to find a value. Imagine looking up flower prices by flower name.

  42. Michael

    To turn a string into an array index, the hashmap uses a hash function. The function produces a number spread across a large range, and that number is reduced to a valid backing-array index by taking it modulo the array length.

  43. Anna

    Different keys can produce the same index. That situation is called a collision, and the hashmap needs a strategy for handling it.

  44. Michael

    One strategy stores everything in a single array. When a collision occurs, we move forward through the array until we find an empty slot. Each entry must include identifying information, such as the flower name, so lookups can check whether an encountered entry is actually the requested key.

  45. Anna

    A disadvantage is clustering: collisions can create long consecutive runs of occupied positions, forcing searches to inspect many entries before finding the desired key or an empty slot.

  46. Michael

    Another strategy uses two arrays. The first stores the initial item for each hash location. Colliding items go into a second array, where each item stores the index of the next colliding item, forming a linked list.

  47. Anna

    This approach follows links rather than scanning forward through consecutive array positions. It also demonstrates a useful property of linked lists: many separate linked lists can be interleaved in one underlying array, because their logical relationships come from links, not physical adjacency.

  48. Michael

    That is more flexible than creating a separate resizable array list for every collision bucket. With separate lists, we would need many allocations and would have to plan for an unpredictable distribution of collisions.

  49. Anna

    So far, the relationships between elements have mostly been about sequence. A tree adds explicit relationships between elements, such as the relationship between a user-interface container and the controls inside it.

  50. Michael

    In a tree, each element is called a node. Relationships point from parent to child: a child has one parent, while a parent can have multiple children.

  51. Anna

    A tree can be implemented with two arrays using linked-list ideas. One array stores the nodes. Each node points to the first child in a second array, and each entry in that second array stores a child-node index plus a link to the next child.

  52. Michael

    To traverse a tree, we follow those indexes. We might start at a root node, use its child index to find the first child, then follow the child's own child links. If a node has several children, the next-child link lets us move among them.

  53. Anna

    There are other tree implementations, including versions packed into one array or versions optimized for particular data sizes and access patterns. The important point is that the same array-and-link principles can represent the structure.

  54. Michael

    A graph is a more general structure than a tree. In a tree, a child can have only one parent. In a graph, a node can have multiple connections coming in as well as multiple connections going out.

  55. Anna

    The nodes in a graph are also called vertices, and the connections are called edges. You can think of the progression this way: a linked list permits one previous and one next link; a tree allows multiple next links; and a graph relaxes the restriction on previous links too.

  56. Michael

    Graphs are widely used for pathfinding. The A-star algorithm, for example, finds a shortest path between two points and is commonly used in video games to choose a route from a character's current location to a target.

  57. Anna

    The array implementation of a graph can look much like the tree implementation: one array stores nodes, and another stores edges as linked relationships. The major difference is in the operations, because graph traversal may proceed in many directions rather than only from parent to child.

  58. Michael

    If we need to traverse an edge in both directions, we generally store the relevant vertex information so the connection is accessible from both nodes. Some specialized graphs use other arrangements, but two arrays are sufficient in many cases.

  59. Anna

    The overall lesson is that data structures are not mysterious objects separate from memory. They are arrangements and access rules built on top of arrays, each optimized for particular data and patterns of use.

  60. Michael

    A sorted array favors searches based on ordering. An array list makes general ordered collections convenient but pays for middle insertion and removal. Stacks favor last-in, first-out access, queues favor first-in, first-out processing, linked lists favor changes when neighboring links are known, hashmaps favor key-based lookup, and trees and graphs represent relationships.

  61. Anna

    And when you face a new programming problem, a useful starting point is deliberately simple: try building it with an array. Seeing how far you can get with just indexed reads and writes may reveal exactly what arrangement and operations your data needs.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent