V Talks Tech · 15 SEPT 2025

Data Structures #1: The Array - More Than Just a List

This post deconstructs the array, from its low-level contiguous memory and O(1) access to how dynamic arrays in popular languages work under the hood.

By
Vibhishan Ranga
Read
7 min
Tags
data structuresalgorithmsarrays
Cover image for Data Structures #1: The Array - More Than Just a List

Welcome to the first post in our "Under the Hood" series on data structures. Before we can talk about complex trees or graphs, we must start with the undisputed bedrock of all data storage: the Array. It might seem simple, but understanding how an array truly works at the memory level is the key to unlocking high-performance code and grasping the trade-offs behind nearly every other data structure.

The one concept to remember is this: An array is a single, unbroken, contiguous block of memory. Think of it like a train. Each element is a coach, and they are all physically linked together in a specific sequence. You can't just have a random coach floating somewhere else; it must be part of the continuous chain. This rigid, sequential structure is its superpower and, as we'll see, its greatest weakness.

Under the Hood: Memory, Pointers, and O(1) Magic

When you declare an array, you ask the operating system for a continuous chunk of memory. If you ask for an array of 5 integers, and each integer takes 4 bytes, the OS reserves a 20-byte block for you.

The magic of an array is its instant access. How does my_array[3] work so fast? It's not magic; it's simple and brilliant pointer arithmetic.

When you access an element, the computer performs a calculation:

memory_address = base_address + (index * size_of_element)
  • base_address: The memory location of the very first element (my_array[0]).

  • index: The position you want to access (e.g., 3).

  • size_of_element: The fixed size of each element in the array (e.g., 4 bytes for an int).

This calculation is incredibly fast for a CPU, taking the same amount of time regardless of whether you're accessing the 3rd or the 3,000,000th element. This is what we call O(1), or constant time, access. This direct memory manipulation is also why pointers are so integral to understanding arrays; the variable name for an array (especially in languages like C++) is essentially a pointer to that base address.

However, this contiguous nature has a cost. Adding an element to the middle of an array requires shuffling every subsequent element one position to the right - an O(n) operation, where n is the number of elements to shift.

The Dynamic Dilemma: What Happens When an Array Gets Full?

This is where things get interesting and where languages start to differ. In low-level languages, if you declare an array of size 10, that's it. You get 10 slots. Trying to access my_array[10] leads to a buffer overflow—undefined behavior and a potential security risk.

But what about Python lists or JavaScript arrays, where you can just keep adding elements? These are called dynamic arrays. Under the hood, they are still fixed-size arrays, but with a clever resizing mechanism.

Here’s the process:

  1. You create a dynamic array. The language allocates a small initial fixed-size array (e.g., size 4).

  2. You keep adding elements.

  3. When you try to add an element to a full array, the language performs a resizing operation: It allocates a brand new, larger array in memory. The growth factor varies, but it's often 1.5x or 2x the old size. It copies every single element from the old array to the new one. The old array is deallocated (freed from memory). Your new element is finally added to the new, larger array.

This copying is an expensive O(n) operation. However, since it doesn't happen on every add operation, the cost is spread out over many additions. We say dynamic arrays have an amortized time complexity of O(1) for appends.

Language Implementations: A Spectrum of Abstraction

Let's see how different languages handle arrays, from manual memory management to fully abstracted dynamic lists.

C++: Raw Power and Control

C++ gives you both raw, C-style static arrays and a powerful dynamic array wrapper, std::vector.

#include <iostream>
#include <vector>

int main() {
    // C-style static array. Size is fixed at compile time.
    int static_array[5] = {10, 20, 30, 40, 50};
    // static_array[5] = 60; // Error! Out of bounds.

    // std::vector - the dynamic array
    // Starts with a small initial capacity.
    std::vector<int> dynamic_vector; 
    dynamic_vector.push_back(1);
    dynamic_vector.push_back(2);
    // When its internal capacity is reached, it will automatically
    // allocate a new, larger array (typically 2x the size) and copy elements.
    std::cout << "Vector capacity: " << dynamic_vector.capacity() << std::endl;

    return 0;
}
  • Internals: A std::vector is a class that manages a raw array on the heap. When it resizes, its capacity typically doubles.

Java: Type-Safe and Structured

Java's arrays are fixed-size once created. For dynamic behavior, you use ArrayList.

import java.util.ArrayList;
import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        // Standard array. Size is fixed upon creation.
        int[] staticArray = new int[5];
        staticArray[0] = 10;
        // staticArray[5] = 60; // Throws ArrayIndexOutOfBoundsException

        // ArrayList - the dynamic array
        // Starts with an initial capacity (default is 10).
        ArrayList<Integer> dynamicList = new ArrayList<>();
        dynamicList.add(1);
        // When capacity is reached, it creates a new array 1.5x the old size
        // and copies the elements over.
    }
}
  • Internals: An ArrayList is backed by a standard Java array. Its growth factor is 1.5x.

Python: The Dynamic List

In Python, the list type is the default dynamic array. You almost never think about size.

# The Python list is a dynamic array.
# You don't specify a size.
my_list = []
my_list.append(1)
my_list.append(2)
print(my_list) # Output: [1, 2]

# Internals: Python lists start with a capacity of 0, then grow to 4, 8, 16, 25, 35, etc.
# The growth factor is not a simple multiplier but is designed to be efficient
# for various growth patterns. The core mechanism of re-allocation and copying remains.

JavaScript: The Flexible Engine

JavaScript's Array is the most abstract. It's a dynamic array, but its implementation can be heavily optimized by the JavaScript engine (like V8 in Chrome).

// A JavaScript Array is dynamic by nature.
let myArray = [];
myArray.push(1);
myArray.push(2);
console.log(myArray); // Output: [1, 2]

// Internals: JS engines like V8 are highly optimized. When an array is created,
// it allocates an internal fixed-size array. When it grows, it follows the same
// re-allocation and copy pattern. The growth factor can vary, but it's
// often around 1.5x. Engines can also de-optimize an array to a hash-map-like
// structure if you do strange things like creating a sparse array (e.g., arr[1000] = 1).

Famous Algorithms & Tricks with Arrays

The array's structure makes it the perfect tool for many classic algorithms.

Binary Search

The poster child for array algorithms. By repeatedly dividing the search interval in half, it can find an element in a sorted array in O(log n) time. This only works because of the array's O(1) random access, which allows us to jump to the middle element instantly.

// C++ Example
int binary_search(const std::vector<int>& arr, int target) {
    int low = 0;
    int high = arr.size() - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2; // Avoids overflow
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return -1; // Not found
}

Prefix Sum

A powerful technique for answering range sum queries. You create a second array where prefix_sum[i] stores the sum of all elements from 0 to i in the original array. This allows you to find the sum of any subarray [i...j] in O(1) time by calculating prefix_sum[j] - prefix_sum[i-1].

Two Pointers (Left Max / Right Max)

A common pattern for searching or processing arrays. You maintain two pointers, often one at the beginning and one at the end, and move them inwards based on some logic. This is used in problems like finding pairs that sum to a target, or in the "Trapping Rain Water" problem, where you pre-calculate the maximum height to the left and right of each position.

Conclusion: The Unsung Hero

From rendering pixels on your screen (a 2D array of color values) and processing audio signals (an array of sound samples) to the internal implementation of a database index, the array is everywhere. Its simplicity is its strength. The predictable, contiguous memory layout plays perfectly to the strengths of modern CPU caches, making array operations incredibly fast in practice.

While more complex data structures are designed to overcome the array's weaknesses (like slow insertions), they are very often built using arrays at their core. Understanding the array is not just learning the first data structure - it's learning the fundamental building block of computation.

All posts →

Pit wall · Newsletter

Want to stay updated?

Get new posts in your inbox as soon as they're out. No spam, just the latest from V Talks Tech.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.