VibeKoding / Ensiklopedia Β· Fondasi KuatEnsiklopedia Β· Fondasi Kuat / Data Structures: An IntroductionData Structures: An Introduction
VK

Data Structures: An IntroductionData Structures: An Introduction

πŸ“š Ensiklopedia Β· Fondasi KuatEnsiklopedia Β· Fondasi Kuat 🌏 Dual Bahasa (ID / EN) ⚑ VibeKoding Native

Ensiklopedia VibeKoding: Data Structures: An Introduction.Ensiklopedia VibeKoding: Data Structures: An Introduction.

πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

Programs = Data Structures + Algorithms. Previously, we learned how the CPU executes instructions and how the operating system manages resources. But the core objects that programs handle are data β€” user information, product lists, social relationships... How this data is organized in memory directly determines whether a program is fast or slow. You may have wondered: why do some programs process tens of thousands of records quickly while others freeze with just a few hundred? The answer often lies in the choice of data structures.Programs = Data Structures + Algorithms. Previously, we learned how the CPU executes instructions and how the operating system manages resources. But the core objects that programs handle are data β€” user information, product lists, social relationships... How this data is organized in memory directly determines whether a program is fast or slow. You may have wondered: why do some programs process tens of thousands of records quickly while others freeze with just a few hundred? The answer often lies in the choice of data structures.

What will you learn from this article?What will you learn from this article?

After completing this chapter, you will gain:After completing this chapter, you will gain:

ChapterContentCore Concepts
Chapter 1Big PictureFour major data structure categories, classification criteria
Chapter 2Linear StructuresArrays, linked lists, stacks, queues
Chapter 3Hash TablesHash functions, collision handling, O(1) lookup
Chapter 4Tree StructuresBinary trees, file system trees, DOM trees
Chapter 5Graph StructuresDirected graphs, undirected graphs, traversal algorithms
Chapter 6Performance ComparisonTime complexity, space complexity
Chapter 7Selection GuideScenario analysis, decision flow

------

1. Big Picture: Data Structures Overview1. Big Picture: Data Structures Overview

Imagine you need to organize a pile of books:Imagine you need to organize a pile of books:

Different organizational methods result in vastly different book-finding efficiency. A data structure is the "organization method" for data β€” it determines how data is stored, found, and modified.Different organizational methods result in vastly different book-finding efficiency. A data structure is the "organization method" for data β€” it determines how data is stored, found, and modified.

All data structures can be categorized into four major types:All data structures can be categorized into four major types:

TypeData RelationshipTypical ExamplesReal-life Analogy
LinearOne-to-one, arranged in a lineArrays, linked lists, stacks, queuesTrain cars, checkout lines
HashKey→Value mappingHash tables, dictionaries, setsLibrary index cards
TreeOne-to-many, hierarchicalBinary trees, B-trees, heapsFamily trees, folder structures
GraphMany-to-many, networkedDirected graphs, undirected graphsSubway maps, social networks
πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

Because there is no universal data structure. Each one is a trade-off between "lookup speed," "insertion speed," and "memory usage." Just as you wouldn't use a backpack to move furniture or a truck to deliver a single letter β€” choosing the right tool makes all the difference.Because there is no universal data structure. Each one is a trade-off between "lookup speed," "insertion speed," and "memory usage." Just as you wouldn't use a backpack to move furniture or a truck to deliver a single letter β€” choosing the right tool makes all the difference.

------

2. Linear Structures: The Most Basic Organization2. Linear Structures: The Most Basic Organization

Linear structures are the most intuitive way to organize data β€” data items are arranged one after another, like train cars. But different "connection methods" and "operation endpoints" produce four variants, each with its own strengths.Linear structures are the most intuitive way to organize data β€” data items are arranged one after another, like train cars. But different "connection methods" and "operation endpoints" produce four variants, each with its own strengths.

2.1 Arrays vs Linked Lists: Two Fundamentally Different Storage Methods2.1 Arrays vs Linked Lists: Two Fundamentally Different Storage Methods

Arrays and linked lists are the two most basic linear structures. Their core difference lies in memory layout:Arrays and linked lists are the two most basic linear structures. Their core difference lies in memory layout:

ComparisonArrayLinked List
Memory layoutOne continuous blockScattered, connected by pointers
Access nth elementCalculate address directly, O(1)Search from the head one by one, O(n)
Insert in the middleMust shift all subsequent elements, O(n)Just change two pointers, O(1)
SizeFixed at creationCan grow at any time
Real-life analogyA row of numbered lockersA chain of treasure hunt clues
πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

- Known data volume, frequent access by position β†’ Array (e.g., student grade tables, pixel matrices) - Unknown data volume, frequent insertion/deletion β†’ Linked list (e.g., playlists, undo history) - Not sure? β†’ Start with an array. In most scenarios, arrays' cache-friendly nature provides greater performance advantages- Known data volume, frequent access by position β†’ Array (e.g., student grade tables, pixel matrices) - Unknown data volume, frequent insertion/deletion β†’ Linked list (e.g., playlists, undo history) - Not sure? β†’ Start with an array. In most scenarios, arrays' cache-friendly nature provides greater performance advantages

2.2 Stacks and Queues: Linear Structures with "Rules"2.2 Stacks and Queues: Linear Structures with "Rules"

Stacks and queues are essentially arrays or linked lists, just with restricted operation methods. It may seem like reduced functionality, but this restriction gives them specific purposes:Stacks and queues are essentially arrays or linked lists, just with restricted operation methods. It may seem like reduced functionality, but this restriction gives them specific purposes:

StructureRuleOperationsAnalogyWhere in Your Code?
StackLast In, First Out (LIFO)push / popA stack of platesFunction call stack, browser back button, Ctrl+Z undo
QueueFirst In, First Out (FIFO)enqueue / dequeueWaiting in line for ticketsTask scheduling, message queues, print queues
πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

Imagine a stack with only two operations β€” "place plate" and "remove plate." You'll never get the order wrong. Restriction brings certainty, and certainty brings reliability. The function call stack relies on "last in, first out" to ensure the most recently called function returns first. If random access to intermediate functions were allowed, programs would be chaotic.Imagine a stack with only two operations β€” "place plate" and "remove plate." You'll never get the order wrong. Restriction brings certainty, and certainty brings reliability. The function call stack relies on "last in, first out" to ensure the most recently called function returns first. If random access to intermediate functions were allowed, programs would be chaotic.

------

3. Hash Tables: The Fastest Lookup3. Hash Tables: The Fastest Lookup

Linear structures aren't fast enough for lookups β€” arrays require O(n) traversal, and even sorted binary search is O(log n). Is there a structure that can achieve O(1) direct lookup? Yes β€” the hash table.Linear structures aren't fast enough for lookups β€” arrays require O(n) traversal, and even sorted binary search is O(log n). Is there a structure that can achieve O(1) direct lookup? Yes β€” the hash table.

3.1 The Core Idea of Hash Tables3.1 The Core Idea of Hash Tables

The principle of hash tables is actually quite simple:The principle of hash tables is actually quite simple:

  1. You provide a key (e.g., "apple")You provide a key (e.g., "apple")
  2. A hash function computes a number from the key (e.g., hash("apple") = 3)A hash function computes a number from the key (e.g., hash("apple") = 3)
  3. Go directly to position 3 in the array β€” no traversal needed, one step and you're thereGo directly to position 3 in the array β€” no traversal needed, one step and you're there
  4. This is like a library's index system: instead of searching shelf by shelf, you check the index card to find the book's exact location.This is like a library's index system: instead of searching shelf by shelf, you check the index card to find the book's exact location.

    3.2 Hash Collision Resolution Methods3.2 Hash Collision Resolution Methods

    Two different keys may compute the same index β€” this is called a hash collision. Like two books having the same index number pointing to the same location.Two different keys may compute the same index β€” this is called a hash collision. Like two books having the same index number pointing to the same location.

    Resolution MethodPrincipleAnalogy
    ChainingStore multiple values at the same position using a linked listPut multiple books in the same cabinet
    Open addressingIf there's a collision, look for the next empty slotIf the cabinet is full, use the adjacent one

    3.3 Hash Table Performance3.3 Hash Table Performance

    OperationAverage CaseWorst Case (All Collisions)
    LookupO(1)O(n)
    InsertO(1)O(n)
    DeleteO(1)O(n)
    ⚠️ Catatan Keamanan / Peringatan⚠️ Warning / Security Note

    When all keys map to the same index, the hash table degrades into a linked list and all operations become O(n). Prevention: choose a good hash function + dynamic resizing (expand when the load factor exceeds a threshold).When all keys map to the same index, the hash table degrades into a linked list and all operations become O(n). Prevention: choose a good hash function + dynamic resizing (expand when the load factor exceeds a threshold).

    πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

    - JavaScript {} objects and Map β†’ Hash table - Python dict β†’ Hash table - Java HashMap β†’ Hash table - Database indexes β†’ Also use hashing at the底层 Every time you write user["name"] or map.get("key"), a hash table is working behind the scenes.- JavaScript {} objects and Map β†’ Hash table - Python dict β†’ Hash table - Java HashMap β†’ Hash table - Database indexes β†’ Also use hashing at the底层 Every time you write user["name"] or map.get("key"), a hash table is working behind the scenes.

    ------

    4. Tree Structures: Expressing Hierarchical Relationships4. Tree Structures: Expressing Hierarchical Relationships

    Hash tables are fast for lookups, but data is unordered. If you need both fast lookup and ordered data, you need tree structures.Hash tables are fast for lookups, but data is unordered. If you need both fast lookup and ordered data, you need tree structures.

    The core characteristic of a tree: each node can have multiple "children" but only one "parent" (except the root node). This one-to-many hierarchical relationship is everywhere in the real world.The core characteristic of a tree: each node can have multiple "children" but only one "parent" (except the root node). This one-to-many hierarchical relationship is everywhere in the real world.

    4.1 Binary Search Trees: Ordered Trees4.1 Binary Search Trees: Ordered Trees

    A binary search tree has one simple but powerful rule: left is smaller, right is larger.A binary search tree has one simple but powerful rule: left is smaller, right is larger.

    • All values in the left subtree < root nodeAll values in the left subtree < root node
    • All values in the right subtree > root nodeAll values in the right subtree > root node

    When searching, each comparison eliminates half the nodes, with time complexity O(log n). Like the number guessing game β€” "Is it bigger or smaller than 50?" "Bigger." "Bigger or smaller than 75?" β€” eliminating half each time.When searching, each comparison eliminates half the nodes, with time complexity O(log n). Like the number guessing game β€” "Is it bigger or smaller than 50?" "Bigger." "Bigger or smaller than 75?" β€” eliminating half each time.

    4.2 Balanced Trees: Preventing Degradation4.2 Balanced Trees: Preventing Degradation

    Binary search trees have a problem: if data is inserted in order (1, 2, 3, 4, 5), the tree degenerates into a linked list and lookups return to O(n). Balanced trees avoid this by automatically adjusting the structure:Binary search trees have a problem: if data is inserted in order (1, 2, 3, 4, 5), the tree degenerates into a linked list and lookups return to O(n). Balanced trees avoid this by automatically adjusting the structure:

    TypeBalancing StrategyCharacteristicsTypical Applications
    AVL TreeStrict balance (height difference ≀ 1)Fastest lookups, slightly slower insertions/deletionsScenarios requiring frequent lookups
    Red-Black TreeApproximate balanceGood overall performanceJava TreeMap, Linux kernel
    B-TreeMulti-way balance; one node stores multiple valuesReduces disk I/ODatabase indexes
    πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

    - File system: Nested folders are tree structures - HTML DOM: β†’ β†’

    β†’

    is a tree - Database indexes: B+ trees enable lookups across millions of records with only 3-4 disk reads - JSON/XML: Nested data formats are essentially trees- File system: Nested folders are tree structures - HTML DOM: β†’ β†’

    β†’

    is a tree - Database indexes: B+ trees enable lookups across millions of records with only 3-4 disk reads - JSON/XML: Nested data formats are essentially trees

    ------

    5. Graph Structures: Networks of Complex Relationships5. Graph Structures: Networks of Complex Relationships

    Trees can only represent "one-to-many" hierarchical relationships. But many real-world relationships are "many-to-many" β€” your friends also have friends, and there are multiple routes between cities. A structure where any node can potentially connect to any other node is a graph.Trees can only represent "one-to-many" hierarchical relationships. But many real-world relationships are "many-to-many" β€” your friends also have friends, and there are multiple routes between cities. A structure where any node can potentially connect to any other node is a graph.

    5.1 Three Types of Graphs5.1 Three Types of Graphs

    TypeCharacteristicsAnalogyTypical Applications
    Undirected graphEdges have no direction; A→B equals B→AWeChat friends (mutual)Social networks, communication networks
    Directed graphEdges have direction; A→B is not the same as B→AWeibo follows (one-way)Web page links, dependency relationships
    Weighted graphEdges have weights (distance, cost, etc.)Highways between cities (with mileages)Map navigation, shortest path

    5.2 Graph Traversal5.2 Graph Traversal

    Graph traversal is more complex than linear structures because there may be cycles (A→B→C→A), requiring tracking of "visited" nodes:Graph traversal is more complex than linear structures because there may be cycles (A→B→C→A), requiring tracking of "visited" nodes:

    Traversal MethodStrategyAnalogyUse Cases
    BFS (Breadth-First)Visit all neighbors first, then neighbors' neighborsRipples spreading in waterShortest path, level-order traversal
    DFS (Depth-First)Go as deep as possible on one path, backtrack when stuckNavigating a mazePath search, connectivity checking
    πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

    - Map navigation: Cities are nodes, roads are edges; navigation finds the shortest path in the graph - Social networks: Users are nodes, follows/friendships are edges; "People you may know" is graph algorithm recommendations - Package managers: npm/pip dependency relationships are directed graphs; npm install performs topological sorting of the graph- Map navigation: Cities are nodes, roads are edges; navigation finds the shortest path in the graph - Social networks: Users are nodes, follows/friendships are edges; "People you may know" is graph algorithm recommendations - Package managers: npm/pip dependency relationships are directed graphs; npm install performs topological sorting of the graph

    ------

    6. Performance Comparison: One Table to See All Data Structures6. Performance Comparison: One Table to See All Data Structures

    After learning so many data structures, how do their performances actually compare? The interactive comparison below will help you build intuition:After learning so many data structures, how do their performances actually compare? The interactive comparison below will help you build intuition:

    Core Performance Comparison Table:Core Performance Comparison Table:

    Data StructureAccessSearchInsertDeleteSpace
    ArrayO(1)O(n)O(n)O(n)O(n)
    Linked ListO(n)O(n)O(1)O(1)O(n)
    Stack/QueueO(n)O(n)O(1)O(1)O(n)
    Hash Tableβ€”O(1)O(1)O(1)O(n)
    Binary Search Treeβ€”O(log n)O(log n)O(log n)O(n)
    Graphβ€”O(V+E)O(1)O(E)O(V+E)
    πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

    - O(1): Regardless of data volume, operation time is constant β€” fastest - O(log n): Doubling the data adds only one step β€” very fast - O(n): Doubling the data doubles the time β€” average - O(V+E): Depends on the number of vertices and edges β€” specific to graphs Note: These are all average cases. In the worst case, hash tables degrade to O(n), and binary search trees also degrade to O(n).- O(1): Regardless of data volume, operation time is constant β€” fastest - O(log n): Doubling the data adds only one step β€” very fast - O(n): Doubling the data doubles the time β€” average - O(V+E): Depends on the number of vertices and edges β€” specific to graphs Note: These are all average cases. In the worst case, hash tables degrade to O(n), and binary search trees also degrade to O(n).

    ------

    7. Selection Guide: Data Structure Application Scenarios7. Selection Guide: Data Structure Application Scenarios

    After learning so many data structures, how do you choose when facing actual requirements? The key is to start from the requirements and ask yourself a few questions:After learning so many data structures, how do you choose when facing actual requirements? The key is to start from the requirements and ask yourself a few questions:

    1. What's the most frequent operation? Lookup? Insertion? Deletion? Traversal?What's the most frequent operation? Lookup? Insertion? Deletion? Traversal?
    2. What's the relationship between data items? One-to-one? One-to-many? Many-to-many?What's the relationship between data items? One-to-one? One-to-many? Many-to-many?
    3. How much data? The optimal choice for dozens vs. millions of records may be completely differentHow much data? The optimal choice for dozens vs. millions of records may be completely different
    4. Does order matter? Do you need to traverse data in a specific order?Does order matter? Do you need to traverse data in a specific order?
    5. Quick Decision Flow:Quick Decision Flow:

      Your NeedRecommended StructureReason
      Fast access by positionArrayO(1) random access
      Frequent insertion/deletion in the middleLinked listO(1) insert/delete without moving elements
      Last in, first out (undo, recursion)StackLIFO semantics naturally match
      First in, first out (task queue)QueueFIFO semantics naturally match
      Fast lookup by keyHash tableO(1) average lookup
      Ordered data + fast lookupBinary search treeO(log n) lookup while maintaining order
      Complex many-to-many relationshipsGraphCan express connections between any nodes
      πŸ’‘ Tips PraktisπŸ’‘ Pro Tip

      - 80% of scenarios are fine with arrays and hash tables - Consider trees when you need ordering - Consider graphs when relationships are complex - Not sure? Start with the simplest and switch when you hit performance issues. Premature optimization is the root of all evil- 80% of scenarios are fine with arrays and hash tables - Consider trees when you need ordering - Consider graphs when relationships are complex - Not sure? Start with the simplest and switch when you hit performance issues. Premature optimization is the root of all evil

      ------

      SummarySummary

      > Data structures are the skeleton of programs. Arrays are like a row of numbered lockers β€” fastest for retrieving items by position; linked lists are like a chain of treasure hunt clues β€” most flexible for insertions and deletions; hash tables are like a library index β€” fastest for finding things by name; trees are like family trees β€” expressing hierarchical relationships while maintaining order; graphs are like subway maps β€” expressing arbitrarily complex networked relationships. There's no best data structure, only the most appropriate one β€” the key is understanding the strengths and costs of each structure and making trade-offs based on actual requirements.> Data structures are the skeleton of programs. Arrays are like a row of numbered lockers β€” fastest for retrieving items by position; linked lists are like a chain of treasure hunt clues β€” most flexible for insertions and deletions; hash tables are like a library index β€” fastest for finding things by name; trees are like family trees β€” expressing hierarchical relationships while maintaining order; graphs are like subway maps β€” expressing arbitrarily complex networked relationships. There's no best data structure, only the most appropriate one β€” the key is understanding the strengths and costs of each structure and making trade-offs based on actual requirements.

      ------

      Further ReadingFurther Reading

      TopicRecommended Resources
      Data structure visualization[VisuAlgo](https://visualgo.net/) - Animated demonstrations of various data structures and algorithms
      Algorithms and data structuresGrokking Algorithms by Aditya Bhargava β€” illustrated and beginner-friendly
      In-depth understandingData Structures and Algorithm Analysis by Mark Allen Weiss
      Practice problems[LeetCode](https://leetcode.com/) - Practice categorized by data structure

      ------

      Next StepsNext Steps

      Now that you've mastered the core knowledge of data structures, you can continue learning:Now that you've mastered the core knowledge of data structures, you can continue learning:

      • [Introduction to Algorithms](./algorithm-thinking.md): Learn to solve problems using sorting, searching, recursion, dynamic programming, and other algorithmic paradigms[Introduction to Algorithms](./algorithm-thinking.md): Learn to solve problems using sorting, searching, recursion, dynamic programming, and other algorithmic paradigms
      • [Programming Languages](./programming-languages.md): Understand how different programming languages implement these data structures[Programming Languages](./programming-languages.md): Understand how different programming languages implement these data structures