C++ Essential Data Structures
Here is an easy to reference syntax cheat-sheet for working with common datastructures in C++.
| Data Structure | Operation | Code | Big O |
|---|---|---|---|
| Hash Table | instantiate | | O(1) |
is empty? | | O(1) | |
get length | | O(1) | |
set value for key | | O(1)** | |
check if key exists | | O(1) | |
erase key value pair | | O(1)** | |
filter out some pairs | | O(n) | |
| Auto-resizing Array | instantiate empty | | O(1) |
instantiate 2D Array | | O(m*n) | |
get length | | O(1) | |
assign value | | O(1)**? | |
add value to end | | O(1)** | |
iterate through indexes | | O(n) | |
iterate through values | | O(n) | |
iterate through values | | O(n) | |
| Set | instantiate | | O(1) |
is empty? | | O(1) | |
get length | | O(1) | |
insert element | | O(1)** | |
if set contains | | O(1) | |
remove element | | O(1)** | |
| Queue | instantiate | | O(1) |
is empty? | | O(1) | |
get length | | O(1) | |
add to queue | | O(1) | |
remove from queue | | O(1) | |
get value at front | | O(1) | |
get value at back | | O(1) | |
| Stack | instantiate | | O(1) |
is empty? | | O(1) | |
get length | | O(1) | |
push onto stack | | O(1) | |
pop stack | | O(1) | |
peek at top | | O(1) | |
| max/min heap | build max heap | | O(n) |
build min heap | | O(n) | |
is empty? | | O(1) | |
get length | | O(1) | |
push value | | O(log(n)) | |
pop max/min | | O(log(n)) | |
get max/min value | | O(1) | |
| Self-Balancing Binary Search Tree (red-black tree) | instantiate | | O(n) |
is empty? | | O(1) | |
get length | | O(1) | |
set value for key | | O(log(n)) | |
if key exists | | O(log(n)) | |
erase key value pair | | O(log(n)) | |
| Binary Tree | define tree node type | | n/a |
| Linked List | define list node type | | n/a |
Note*: Assumes you have using namespace std;. (LeetCode does this automatically.) Otherwise, you will have to instantiate structures differently e.g.std::unordered_map<keyType, valType> mp;.
Note**: This is the Amortized run-time per operation i.e. the upper bound per operation over a series of operations if we divided the work equally between.