
Think together · Start with a little story
The robot has three jobs: find scores by number, handle requests in arrival order, and undo the latest action. The girl gives it different tools.
Lay out the process
- By numberArray
- By arrival orderQueue
- Undo the latestStack
Choose a structure by listing the operations you need.
Consider an array when you need index access, a queue for first-in, first-out work, and a stack for last-in, first-out work. The name matters less than whether its rules fit the task.
01What should you ask before choosing a data structure?
Do not start with “Which STL container do I know?” Start by asking:
How is the data related?
Is it in a sequence, a hierarchy, or a network of connections?
What do you do most often?
Access, insert, delete, or search?
Does order matter?
Should the first item added be handled first, or the latest?
How large is the data?
Dozens of items or millions?
02When should you think of an array?
If the data has a clear order and you need index access, traversal, or sorting, an array or vector is often a natural choice.
03When should you think of a stack?
If the problem emphasizes any of these:
- Handle the most recently added item first
- Undoing actions
- Returning to the previous level
- Matching parentheses
Think of a LIFO stack.
04When should you think of a queue?
If the problem emphasizes any of these:
- Handle items in the order they arrive
- Spreading outward one layer at a time
- Processing tasks by arrival order
Think of a FIFO queue.
05When should you think of a tree?
If the data naturally has levels, for example:
- Folders
- Organizational structures
- Expression structures
- Search trees
A tree is often the more natural model.
06When should you think of a graph?
If objects can connect in many different ways—such as roads, friendships, networks, or dependencies—consider a graph.
07Is there a “strongest” data structure?
No.
One operation is very fast
Another operation may be more complicated, or the structure may use more space.
The structure is very flexible
It may also take more work to manage.
08How can you decide while solving a problem?
Then check whether your choice is fast enough for the data size and algorithm.
What have you learned?
- Choose a data structure based on what the problem needs.
- Arrays suit ordered data and index access.
- Stacks are last-in, first-out; queues are first-in, first-out.
- Trees suit hierarchies; graphs suit general connections.
- No single data structure is best in every situation.
- Choosing a data structure means balancing operations and efficiency.
Topic complete: The next topic is “Basic Algorithms.”
Your turn to try
A drawing app lets you draw a circle and then a square. Which should one undo action remove first?
Ready? Open to see the explanation
The square. The most recent action is undone first, following a stack’s last-in, first-out rule.