Choosing the Best Data Structure

1️⃣ What operations do I need to perform efficiently?

2️⃣ How much memory do I have?

3️⃣ Is the data dynamic or static?

4️⃣ Do I need ordering or uniqueness?

How to Approach the Problem

Whenever you're given a problem, ask yourself these four key questions:

Example Scenarios & Best Data Structures

Scenario Best Data Structure Why?
Find top K largest elements MinHeap (Priority Queue) Efficient O(k log n) retrieval
Check if a number exists in a dataset HashSet Fast O(1) lookup
Store key-value pairs with fast lookup HashMap O(1) access time
Process elements in sorted order TreeSet / Priority Queue Maintains order dynamically
Find shortest path in a graph Dijkstra’s Algorithm (MinHeap + Graph) Efficient priority-based traversal
Implement LRU Cache HashMap + Doubly Linked List Fast lookups + efficient removals
Find median in a stream of numbers Two Heaps (MinHeap & MaxHeap) Efficient median tracking

Final Tip

You don’t need to memorize everything—just practice thinking in terms of operations. If you can explain why a data structure is best for a scenario, you’re already thinking like an SDE2!

C++ STL Data Structures: Set, Heap, Array, Map

1. set Usage and Ordering

#include <set>
set<int, greater<int>> numbers; // prints in decreasing order
set<int> nums2; // prints in ascending order
  

Searching in a Set

int val = 12; // value to search
auto it = numbers.find(val);
if(it != numbers.end()){
    cout << "found" << endl;
} else {
    cout << "not found" << endl;
}
  

2. When to Use Set, Array, or Heap for Min/Max

3. Heap (Priority Queue) Examples

priority_queue<int, vector<int>, greater<int>> minHeap; // min-heap
priority_queue<int> maxHeap; // max-heap

// For pairs:
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> minheap; // min-heap with pairs
priority_queue<pair<int, int>> maxheap; // max-heap with pairs
  

4. map vs unordered_map

Map Iteration Example

for(auto it: map_name){
    cout << it.first << " " << it.second << " ";
}