Data Structures
At the bare metal level, a computer's memory (RAM) is just a massive, flat grid of bytes. It has no idea what an "array," a "list," or a "tree" is.
A data structure is exactly: a structured way of organizing and manipulating that raw memory space so we can store, access, and modify data efficiently under physical constraints.
The Two Physical Pillars of Memory
Every complex data structure you will ever build or use on LeetCode is ultimately constructed from just two raw physical layouts in memory:
1. Contiguous Memory (The Array)
The data is stored in one single, unbroken block of memory addresses, right next to each other.
-
The Constraint: Since they are side-by-side, if you know where the first item is, you can instantly calculate where the
-th item is in time. -
The Catch: If you want to grow the size of your array, but the neighboring memory is already taken by other programs, you have to allocate a brand new, larger block of memory somewhere else and copy everything over.
2. Linked/Pointer-Based Memory (The Node)
The data is scattered all over your RAM wherever there is free space. Each piece of data (a "Node") contains its value and a "pointer" (the physical memory address) pointing to where the next piece of data is.
-
The Constraint: You can grow this structure infinitely without needing one big contiguous block of RAM.
-
The Catch: You lose instant access. To find the 100th item, you have to physically jump from pointer to pointer 100 times (
time).
Why do we need different structures?
Because of trade-offs. No single memory layout is perfect for everything.
For example, think of a Stack (where you only add and remove from the top, like a stack of plates) versus a Queue (where you add to the back and pull from the front, like a line at a grocery store). We organize the memory differently depending on which operations we need to be lightning-fast.