Learn how data structures organize data before working with arrays, strings, hash maps, and sets.
A data structure organizes values so you can do particular operations on them. Imagine looking for a receipt. A stack of receipts puts the most recent one within reach. If you usually search by order number instead, a collection indexed by order number can save you a full scan.
Suppose a music app needs to store a playlist, its title, a play count for each track, and the tracks a listener has already heard. Four built-in structures answer four different questions:
| Question | Structure | Example |
|---|---|---|
| Which track is third? | Array or list | Read the track at index 2. |
| Which letters occur in the title? | String | Scan the title from left to right. |
| How many times did a track play? | Hash map | Look up a count by track ID. |
| Have we played this track? | Set | Check whether its ID is present. |
An array has a linear order. A tree branches into parent and child positions. A map associates a key with a value. Those descriptions tell you how to use the structure. Its physical representation tells you what each operation costs.
A traditional array puts fixed-size slots next to each other, so its starting address and an index locate a slot directly. In a linked sequence, a node stores a reference to the next node. Reaching the third node from the first requires following two links. A dynamic array may replace its underlying storage as the collection grows.
If a playlist contains n tracks, reading track number three takes O(1) time. Finding an unknown position by scanning for a title takes O(n) time in the worst case. A map keyed by track ID can retrieve a count in average O(1) time. Searching its values for a count of 100 can still require visiting every entry.
| Operation | Dynamic array | Hash map keyed by track ID |
|---|---|---|
| Read a known position or key | O(1) by index | Average O(1) by key |
| Search for an arbitrary value | O(n) worst case | O(n) worst case |
| Add an entry | Amortized O(1) at the end, O(n) at the front | Average O(1) by key |
| Remove an entry | O(n) to preserve order at the front | Average O(1) by key |
The table assumes fixed-cost keys and ordinary dense arrays. A single append can take longer when the backing storage grows. An unusually crowded hash location can also make an individual lookup slower.