C++ STL Containers Cheat Sheet (Definitions, Operations, Code & Time Complexity) ☑️☑️
Short version
sort(v.begin(), v.end(), [](auto& a, auto& b) {
return a < b;
});Pair
Instead of:
sort(v.begin(), v.end(), [](const pair<int,int>& a,
const pair<int,int>& b) {
return a.first < b.first;
});Use:
sort(v.begin(), v.end(), [](auto& a, auto& b) {
return a.first < b.first;
});Two conditions
sort(v.begin(), v.end(), [](auto& a, auto& b) {
if (a.first != b.first)
return a.first < b.first;
return a.second > b.second;
});String
sort(v.begin(), v.end(), [](auto& a, auto& b) {
return a.length() < b.length();
});Frequency
sort(s.begin(), s.end(), [&](auto a, auto b) {
if (freq[a] != freq[b])
return freq[a] > freq[b];
return a < b;
});Largest Number
sort(v.begin(), v.end(), [](auto& a, auto& b) {
return a + b > b + a;
});Main template to memorize:
sort(v.begin(), v.end(), [](auto& a, auto& b) {
if (condition1)
return order1;
return order2;
});auto automatically detects the type of a and b, so you don't need to write const vector<int>&, const pair<int,int>&, const string&, etc.
class Solution {
bool isvowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' ||
ch == 'O' || ch == 'U';
}
public:
string sortVowels(string s) {
vector<pair<char, int>> count;
// Step 1: Store vowels + ASCII value
for (auto& ch : s) {
if (isvowel(ch)) {
count.push_back({ch, int(ch)});
}
}
// Step 2: Sort by ASCII value
sort(count.begin(), count.end(), [](auto& a, auto& b) {
return a.second < b.second;
});
// Step 3: Replace vowels
int idx = 0;
for (auto& ch : s) {
if (isvowel(ch)) {
ch = count[idx].first;
idx++;
}
}
return s;
}
};Your important comparator
sort(count.begin(), count.end(), [](auto& a, auto& b) {
return a.second < b.second;
});Here:
a.second = ASCII value
b.second = ASCII valuevector<pair<char,int>> keeps every vowel occurrence, while still allowing your int(ch) + auto comparator approach.
🔄 Circular Traversal — Important Patterns
Assume:
vector<int> a = {1, 2, 3, 4, 5};
int n = a.size();1. Circular traversal n times
for(int i = 0; i < n; i++) {
int idx = i % n;
cout << a[idx] << " ";
}Output:
1 2 3 4 52. Circular traversal 2*n times
for(int i = 0; i < 2*n; i++) {
int idx = i % n;
cout << a[idx] << " ";
}Output:
1 2 3 4 5 1 2 3 4 5⭐ Pattern:
idx = i % n;3. Start from any index
Start from idx = 2:
int idx = 2;
for(int i = 0; i < n; i++) {
int curr = (idx + i) % n;
cout << a[curr] << " ";
}Output:
3 4 5 1 2⭐ Pattern:
curr = (start + i) % n;4. Start from index and traverse 2*n
int start = 2;
for(int i = 0; i < 2*n; i++) {
int curr = (start + i) % n;
cout << a[curr] << " ";
}Output:
3 4 5 1 2 3 4 5 1 25. Circular traversal backward
int start = 2;
for(int i = 0; i < n; i++) {
int curr = (start - i + n) % n;
cout << a[curr] << " ";
}Output:
3 2 1 5 4⭐ Important:
(start - i + n) % n6. Move to next index
idx = (idx + 1) % n;Example:
0 → 1 → 2 → 3 → 4 → 0 → 1 ...7. Move to previous index
idx = (idx - 1 + n) % n;Example:
0 → 4 → 3 → 2 → 1 → 0 ...8. Circular window of size k
For every index, look at the next k elements.
int k = 3;
for(int i = 0; i < n; i++) {
for(int j = 0; j < k; j++) {
int idx = (i + j) % n;
cout << a[idx] << " ";
}
cout << endl;
}Output:
1 2 3
2 3 4
3 4 5
4 5 1
5 1 2🔥 Very important for circular subarray problems.
9. Circular window — sum
int k = 3;
for(int i = 0; i < n; i++) {
int sum = 0;
for(int j = 0; j < k; j++) {
int idx = (i + j) % n;
sum += a[idx];
}
cout << sum << endl;
}Output:
6
9
12
10
810. Circular array + two pointers
Sometimes you allow the right pointer to go beyond n.
int left = 0;
for(int right = 0; right < 2*n; right++) {
int idx = right % n;
cout << a[idx] << " ";
}This is useful for:
Circular sliding window
Circular subarray
Maximum circular subarray
Next greater element11. Next element circularly
for(int i = 0; i < n; i++) {
int next = (i + 1) % n;
cout << a[next] << " ";
}Output:
2 3 4 5 112. Previous element circularly
for(int i = 0; i < n; i++) {
int prev = (i - 1 + n) % n;
cout << a[prev] << " ";
}Output:
5 1 2 3 4🧠 The 5 formulas you MUST remember
| Pattern | Formula |
|---|---|
| Normal circular | (i % n) |
Start from start | (start + i) % n |
| Backward | (start - i + n) % n |
| Next index | (idx + 1) % n |
| Previous index | (idx - 1 + n) % n |
🚀 Problem patterns to practice
Learn them in this order:
1. Basic Circular Traversal
↓
2. Start from given index
↓
3. Forward / Backward
↓
4. Circular Window
↓
5. Circular Sliding Window
↓
6. Next Greater Element Circular
↓
7. Maximum Circular Subarray
↓
8. Josephus / EliminationThe core idea is almost always % n. Once you are comfortable with these 5 formulas, circular-array LeetCode problems become much easier.
These are very important in DSA. 👇
🔹 1. GCD — Greatest Common Divisor
GCD = the largest number that divides both numbers exactly.
Example:
12 → 1, 2, 3, 4, 6, 12
18 → 1, 2, 3, 6, 9, 18
Common → 1, 2, 3, 6
GCD = 6✅ C++
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}Or simply:
#include <numeric>
int ans = gcd(12, 18); // 6🔹 2. LCM — Least Common Multiple
LCM = the smallest positive number that is divisible by both numbers.
Example:
12 → 12, 24, 36, 48, 60, 72...
18 → 18, 36, 54, 72...
LCM = 36⭐ Formula
LCM(a, b) = (a / GCD(a, b)) × bFor 12, 18:
GCD = 6
LCM = (12 / 6) × 18
= 2 × 18
= 36✅ C++
long long lcm(int a, int b) {
return (long long)a / gcd(a, b) * b;
}Or built-in:
#include <numeric>
int g = gcd(12, 18); // 6
int l = lcm(12, 18); // 36🧠 Easy way to remember
| Meaning | Example | |
|---|---|---|
| GCD | Biggest number that divides both | gcd(12,18) = 6 |
| LCM | Smallest number that both can divide into | lcm(12,18) = 36 |
🔥 Most important formula
GCD(a,b) × LCM(a,b) = a × bSo:
6 × 36 = 12 × 18
216 = 216 ✅Absolutely 👍 Here are 5 DSA practice problems on GCD & LCM, from easy → medium, with C++ solutions.
🟢 Problem 1 — Find GCD of Two Numbers
Given: a = 24, b = 36
Output:
12Code
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 24, b = 36;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
cout << a;
}🧠 Pattern
a = 24, b = 36
36 % 24 = 12
24 % 12 = 0
GCD = 12🟢 Problem 2 — Find LCM of Two Numbers
Given: a = 12, b = 18
Output:
36Code
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int a = 12, b = 18;
long long ans = (long long)a / gcd(a, b) * b;
cout << ans;
}🧠 Formula
LCM = (a / GCD) * b🟡 Problem 3 — GCD of an Array
Given:
nums = [24, 36, 60]Find the GCD of all numbers.
Output:
12Code
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {24, 36, 60};
int ans = nums[0];
for (int i = 1; i < nums.size(); i++) {
ans = gcd(ans, nums[i]);
}
cout << ans;
}🧠 Intuition
Start with first number:
ans = 24
gcd(24,36) = 12
gcd(12,60) = 12
Answer = 12⭐ Pattern
GCD(GCD(a,b),c)🟡 Problem 4 — LCM of an Array
Given:
nums = [4, 6, 8]Find the LCM.
Output:
24Code
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {4, 6, 8};
long long ans = nums[0];
for (int i = 1; i < nums.size(); i++) {
ans = (ans / gcd(ans, nums[i])) * nums[i];
}
cout << ans;
}🧠 Dry Run
ans = 4
LCM(4,6)
= 4 / gcd(4,6) * 6
= 4 / 2 * 6
= 12
LCM(12,8)
= 12 / gcd(12,8) * 8
= 12 / 4 * 8
= 24Answer:
24🔴 Problem 5 — GCD + LCM Together
Given:
a = 18
b = 24Find both GCD and LCM.
Output:
GCD = 6
LCM = 72Code
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 18;
int b = 24;
int g = gcd(a, b);
long long l = (long long)a / g * b;
cout << "GCD = " << g << endl;
cout << "LCM = " << l << endl;
}🔥 Important C++ Shortcut
C++ already provides both:
#include <numeric>
int g = gcd(a, b);
int l = lcm(a, b);Example:
int a = 12;
int b = 18;
cout << gcd(a, b); // 6
cout << lcm(a, b); // 36🧠 Remember this
GCD → Euclidean Algorithm
while (b != 0)
a, b = b, a % b
LCM → Formula
LCM = (a / GCD) × bPractice order: 1 → 2 → 3 → 4 → 5 🚀
⭐ PART 13 — ALL IMPORTANT CONVERSIONS AT ONE PLACE
// int → string
string s = to_string(n);
// string → int
int n = stoi(s);
// binary string → int
int n = stoi(s, nullptr, 2);
// int → binary
string s = bitset<32>(n).to_string();
// int → binary manually
string s = "";
while (n > 0) {
s += (n & 1) + '0';
n >>= 1;
}
reverse(s.begin(), s.end());
// binary string → int manually
int ans = 0;
for (char c : s)
ans = ans * 2 + (c - '0');
// decimal → hexadecimal
stringstream ss;
ss << hex << n;
string hexString = ss.str();
// decimal → octal
stringstream ss;
ss << oct << n;
string octalString = ss.str();🧠 PART 14 — MASTER MEMORY TABLE
| Task | Pattern |
|---|---|
| int → string | to_string(n) |
| string → int | stoi(s) |
| binary string → int | stoi(s,nullptr,2) |
| int → binary | bitset<32>(n).to_string() |
| get last bit | n & 1 |
| divide by 2 | n >> 1 |
| multiply by 2 | n << 1 |
| check kth bit | (n >> k) & 1 |
| set kth bit | n | (1 << k) |
| clear kth bit | n & ~(1 << k) |
| toggle kth bit | n ^ (1 << k) |
remove rightmost 1 | n & (n - 1) |
get rightmost 1 | n & -n |
| power of 2 | n > 0 && !(n & (n-1)) |
| count set bits | __builtin_popcount(n) |
| reverse binary | (rev << 1) | (n & 1) |
🚨 Most Important 10 to Memorize for DSA
// 1. Last bit
n & 1
// 2. Divide by 2
n >> 1
// 3. Multiply by 2
n << 1
// 4. Check kth bit
(n >> k) & 1
// 5. Set kth bit
n | (1 << k)
// 6. Clear kth bit
n & ~(1 << k)
// 7. Toggle kth bit
n ^ (1 << k)
// 8. Remove rightmost 1
n & (n - 1)
// 9. Get rightmost 1
n & -n
// 10. Count set bits
__builtin_popcount(n)🏆 FINAL BIT DSA CHEAT SHEET
⭐ Must memorize
// Odd / Even
n & 1
// Divide by 2
n >> 1
// Multiply by 2
n << 1
// Check kth bit
(n >> k) & 1
// Set kth bit
n | (1 << k)
// Clear kth bit
n & ~(1 << k)
// Toggle kth bit
n ^ (1 << k)
// Remove rightmost 1
n & (n - 1)
// Get rightmost 1
n & -n
// Power of 2
n > 0 && (n & (n - 1)) == 0
// Count set bits
__builtin_popcount(n)
// Lowest set bit position
__builtin_ctz(n)
// Highest set bit position
31 - __builtin_clz(n)
// XOR single number
ans ^= x
// Generate subsets
mask & (1 << i)
// Extract lowest k bits
n & ((1 << k) - 1)🎯 DSA learning order
LEVEL 1
│
├── Binary ↔ Decimal
├── n & 1
├── n >> 1
└── n << 1
↓
LEVEL 2
│
├── Set bit
├── Clear bit
├── Toggle bit
└── Check kth bit
↓
LEVEL 3
│
├── n & (n-1)
├── n & -n
├── Power of 2
└── Count set bits
↓
LEVEL 4
│
├── XOR
├── Single number
├── Missing number
└── XOR patterns
↓
LEVEL 5
│
├── Subsets
├── Submasks
├── Bitmask DP
└── Advanced bit tricksIf you're preparing DSA, the biggest priority is the ⭐ patterns—not memorizing every obscure bit trick.
- 'a' = 97
- 'b' = 98
- 'c' = 99
- ...
- 'z' = 122
Key Formulas in C++ / Algorithms
1. Find the 0-based index of a letter (0 to 25):
Subtract 'a' (or 97) from the character.
char ch = 'b';
int index = ch - 'a'; // 'b' - 'a' => 98 - 97 = 1
2. Convert a 0-based index back to a character:
Add 'a' (or 97) to the index.
int index = 1;
char ch = index + 'a'; // 1 + 97 = 98 ('b')
3. Uppercase vs. Lowercase difference:
Uppercase 'A' is 65. The difference between lowercase and uppercase is always 32.
char lower = 'a';
char upper = lower - 32; // 97 - 32 = 65 ('A')
Sure 👍 Here are the 2 main codes you should remember.
1️⃣ Check whether a number is Prime
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}Example:
isPrime(17); // true
isPrime(18); // false2️⃣ Sieve of Eratosthenes — Find all primes 2 → n
vector<bool> sieve(int n) {
vector<bool> prime(n + 1, true);
prime[0] = prime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i) {
prime[j] = false;
}
}
}
return prime;
}Usage:
vector<bool> prime = sieve(30);
for (int i = 2; i <= 30; i++) {
if (prime[i])
cout << i << " ";
}Output:
2 3 5 7 11 13 17 19 23 29🧠 Main difference
| Single number | Many numbers | |
|---|---|---|
| Method | isPrime() | sieve() |
| Complexity | O(√n) | O(n log log n) |
| Use | Check one number | Find all primes up to n |
To calculate prime factors, repeatedly divide the number by the smallest prime that divides it.
Example: 12
12 ÷ 2 = 6 → take 2
6 ÷ 2 = 3 → take 2
3 ÷ 3 = 1 → take 3So:
12 = 2 × 2 × 3Prime factor set:
{2, 3}Because duplicates are removed.
More examples
6 = 2 × 3 → {2, 3}
10 = 2 × 5 → {2, 5}
15 = 3 × 5 → {3, 5}
20 = 2 × 2 × 5 → {2, 5}
30 = 2 × 3 × 5 → {2, 3, 5}C++ basic method
set<int> primeFactors(int n) {
set<int> factors;
for (int p = 2; p * p <= n; p++) {
while (n % p == 0) {
factors.insert(p);
n /= p;
}
}
if (n > 1)
factors.insert(n);
return factors;
}For example:
primeFactors(12)gives:
{2, 3}The important idea is: factor repeatedly, but insert each prime into a set, so duplicates automatically disappear.
Yes. There are several meanings of factors in DSA. For a number n, you should know these common types.
1. All factors / divisors
Example:
n = 12
Factors = {1, 2, 3, 4, 6, 12}Simple O(n)
vector<int> factors(int n) {
vector<int> ans;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
ans.push_back(i);
}
}
return ans;
}2. All factors — optimized O(√n)
Instead of checking 1 → n, check only up to √n.
vector<int> factors(int n) {
vector<int> ans;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
ans.push_back(i);
if (i != n / i) {
ans.push_back(n / i);
}
}
}
sort(ans.begin(), ans.end());
return ans;
}For:
n = 12Output:
1 2 3 4 6 123. Prime factors
Prime factors are the prime numbers that divide n.
12 = 2 × 2 × 3Therefore:
Prime factors = {2, 3}Code:
set<int> primeFactors(int n) {
set<int> factors;
for (int p = 2; p * p <= n; p++) {
while (n % p == 0) {
factors.insert(p);
n /= p;
}
}
if (n > 1) {
factors.insert(n);
}
return factors;
}4. Prime factorization
Here we keep duplicates.
For:
12we get:
12 = 2 × 2 × 3So:
{2, 2, 3}Code:
vector<int> primeFactorization(int n) {
vector<int> ans;
for (int p = 2; p * p <= n; p++) {
while (n % p == 0) {
ans.push_back(p);
n /= p;
}
}
if (n > 1) {
ans.push_back(n);
}
return ans;
}5. Number of factors
For:
12factors are:
1, 2, 3, 4, 6, 12Therefore:
count = 6Simple:
int countFactors(int n) {
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
cnt++;
}
}
return cnt;
}Optimized:
int countFactors(int n) {
int cnt = 0;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
cnt++;
if (i != n / i) {
cnt++;
}
}
}
return cnt;
}6. Sum of all factors
For:
121 + 2 + 3 + 4 + 6 + 12
= 28Code:
int sumFactors(int n) {
int sum = 0;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
sum += i;
if (i != n / i) {
sum += n / i;
}
}
}
return sum;
}7. Proper factors
Proper factors = all factors except the number itself.
For:
12Normal factors:
1 2 3 4 6 12Proper factors:
1 2 3 4 6Code:
vector<int> properFactors(int n) {
vector<int> ans;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
if (i != n) {
ans.push_back(i);
}
int other = n / i;
if (other != i && other != n) {
ans.push_back(other);
}
}
}
sort(ans.begin(), ans.end());
return ans;
}8. Check whether a number is prime
A prime number has exactly two factors: 1 and itself.
bool isPrime(int n) {
if (n < 2)
return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}Examples:
2 → prime
3 → prime
5 → prime
7 → prime
4 → not prime
6 → not prime
9 → not prime⭐ Most important distinction
For 12:
All factors:
{1, 2, 3, 4, 6, 12}
Prime factors:
{2, 3}
Prime factorization:
{2, 2, 3}
Number of factors:
6
Sum of factors:
28
Proper factors:
{1, 2, 3, 4, 6}For the LeetCode 4032 problem you're doing, you specifically need prime factors as a set, e.g.
6 → {2, 3}
10 → {2, 5}
[6, 10]
→ {2, 3} ∪ {2, 5}
→ {2, 3, 5}So focus especially on #3 (distinct prime factors) and set union.
C++ STL Containers Cheat Sheet (Definitions, Operations, Code & Time Complexity)
1. vector
Definition
vector is a dynamic array that automatically resizes when elements are added or removed. It stores elements in contiguous memory, making random access very fast.
When to Use
- Frequent access using index
- Insert/Delete at the end
- Dynamic array needed
Operations
| Function | Description | Time |
|---|---|---|
push_back(x) | Insert at end | O(1) Amortized |
pop_back() | Remove last element | O(1) |
insert(pos,x) | Insert at position | O(n) |
erase(pos) | Remove element | O(n) |
clear() | Remove all elements | O(n) |
resize(n) | Change size | O(n) |
reserve(n) | Increase capacity | O(n) (if reallocates) |
size() | Number of elements | O(1) |
empty() | Check empty | O(1) |
front() | First element | O(1) |
back() | Last element | O(1) |
at(i) | Access element | O(1) |
operator[] | Access element | O(1) |
find() (algorithm) | Search element | O(n) |
sort() (algorithm) | Sort vector | O(n log n) |
1. push_back(x) — O(1) Amortized
Adds an element at the end.
vector<int> v = {10, 20, 30};
v.push_back(40);
cout << v[3]; // 40Before: 10 20 30
After : 10 20 30 40
↑
addedWhy amortized O(1)?
Usually adding at the end is O(1).
But when capacity is full, vector creates a bigger memory block and copies elements.
Capacity full
[10][20][30][40]
↓ reallocate
[10][20][30][40][50][ ][ ][ ]That particular operation can be O(n), but over many insertions the average is O(1).
2. pop_back() — O(1)
Removes the last element.
vector<int> v = {10, 20, 30};
v.pop_back();
10 20 30
↓
10 20No shifting is required.
3. insert(pos, x) — O(n)
Inserts an element at a particular position.
vector<int> v = {10, 20, 30, 40};
v.insert(v.begin() + 2, 25);Result:
10 20 25 30 40
↑
insertedElements after the position must shift.
Before:
10 20 30 40
↓
After:
10 20 25 30 40
← shiftingTherefore:
O(n)
4. erase(pos) — O(n)
Removes an element from a position.
vector<int> v = {10, 20, 30, 40};
v.erase(v.begin() + 1);Result:
10 30 4020 is removed and elements after it shift left.
5. clear() — O(n)
Removes all elements.
vector<int> v = {10, 20, 30, 40};
v.clear();
cout << v.size(); // 0Before: 10 20 30 40
After : emptyThe elements must be destroyed, so generally O(n).
6. resize(n) — O(n)
Changes the size of the vector.
vector<int> v = {10, 20, 30};
v.resize(5);Result:
10 20 30 0 0If increasing the size, new elements are added.
You can also specify a value:
v.resize(5, 100);10 20 30 100 1007. reserve(n) — O(n) if reallocation
Reserves capacity, not size.
vector<int> v;
v.reserve(100);Important:
v.size(); // 0
v.capacity(); // at least 100resize() vs reserve()
v.resize(100);means:
size = 100while
v.reserve(100);means:
size = 0
capacity = 100+Very important for interviews.
8. size() — O(1)
Returns number of elements.
vector<int> v = {10, 20, 30};
cout << v.size();Output:
3Vector stores its size, so it doesn't need to count elements.
9. empty() — O(1)
Checks whether vector contains zero elements.
vector<int> v;
if(v.empty())
cout << "Empty";Output:
EmptyEquivalent idea:
v.size() == 010. front() — O(1)
Returns the first element.
vector<int> v = {10, 20, 30};
cout << v.front();Output:
10Same idea as:
v[0]11. back() — O(1)
Returns the last element.
vector<int> v = {10, 20, 30};
cout << v.back();Output:
30Same idea as:
v[v.size() - 1]12. at(i) — O(1)
Accesses an element using an index.
vector<int> v = {10, 20, 30};
cout << v.at(1);Output:
20Important difference
at() performs bounds checking.
v.at(10);If index doesn't exist, it throws an exception.
13. operator[] — O(1)
Normal vector indexing.
vector<int> v = {10, 20, 30};
cout << v[1];Output:
20Usually faster than at() because it doesn't perform bounds checking.
v[1] // no bounds checking
v.at(1) // bounds checking14. find() — O(n)
find() is an algorithm, not a vector member function.
#include <algorithm>
vector<int> v = {10, 20, 30, 40};
auto it = find(v.begin(), v.end(), 30);
if(it != v.end())
cout << "Found";How it searches
10 → 20 → 30
↑
foundIn the worst case it checks every element:
n elements → O(n)15. sort() — O(n log n)
sort() is also an algorithm.
#include <algorithm>
vector<int> v = {40, 10, 30, 20};
sort(v.begin(), v.end());Result:
10 20 30 40How to remember
sort(v.begin(), v.end());means:
start ───────────────→ end
sort everythingComplexity:
O(n log n)Descending order
sort(v.begin(), v.end(), greater<int>());Result:
40 30 20 10⭐ Most Important Vector Complexity
┌──────────────────────────────┬──────────┐
│ Operation │ Time │
├──────────────────────────────┼──────────┤
│ push_back() │ O(1)* │
│ pop_back() │ O(1) │
│ insert() │ O(n) │
│ erase() │ O(n) │
│ clear() │ O(n) │
│ resize() │ O(n) │
│ reserve() │ O(n)* │
│ size() │ O(1) │
│ empty() │ O(1) │
│ front() │ O(1) │
│ back() │ O(1) │
│ at() │ O(1) │
│ [] │ O(1) │
│ find() │ O(n) │
│ sort() │ O(n log n)│
└──────────────────────────────┴──────────┘
* amortized / when reallocation occurs🧠 Interview shortcut
Vector is fast at the end and random access, but slow in the middle.
Access → O(1)
End insert → O(1) amortized
End delete → O(1)
Middle insert → O(n)
Middle delete → O(n)
Search → O(n)
Sort → O(n log n)That single pattern is useful for quickly answering many DSA/MCQ vector questions.
2. deque
Definition
A deque (Double Ended Queue) allows insertion and deletion from both front and back efficiently.
When to Use
- Need fast insertion/deletion at both ends
- Sliding window problems
- Queue implementation
Operations
| Function | Description | Time |
|---|---|---|
push_back(x) | Insert back | O(1) |
push_front(x) | Insert front | O(1) |
pop_back() | Remove back | O(1) |
pop_front() | Remove front | O(1) |
insert() | Insert middle | O(n) |
erase() | Delete middle | O(n) |
front() | First element | O(1) |
back() | Last element | O(1) |
size() | Number of elements | O(1) |
empty() | Check empty | O(1) |
find() (algorithm) | Search | O(n) |
Example
#include <iostream>
#include <deque>
using namespace std;
int main() {
deque<int> dq;
dq.push_back(20);
dq.push_front(10);
dq.push_back(30);
dq.pop_front();
for(int x:dq)
cout<<x<<" ";
}Output
20 303. list
Definition
A list is a doubly linked list. It allows fast insertion and deletion anywhere if the iterator is known.
When to Use
- Frequent insertion/deletion
- No random access required
Operations
| Function | Description | Time |
|---|---|---|
push_back(x) | Insert end | O(1) |
push_front(x) | Insert front | O(1) |
pop_back() | Delete end | O(1) |
pop_front() | Delete front | O(1) |
insert(it,x) | Insert at iterator | O(1) |
erase(it) | Delete at iterator | O(1) |
remove(x) | Remove value | O(n) |
sort() | Sort list | O(n log n) |
reverse() | Reverse list | O(n) |
size() | Number of elements | O(1) |
find() (algorithm) | Search | O(n) |
Example
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> l;
l.push_back(20);
l.push_front(10);
l.push_back(30);
l.remove(20);
for(int x:l)
cout<<x<<" ";
}Output
10 304. set
Definition
A set stores unique elements in sorted order using a Red-Black Tree.
When to Use
- Unique values only
- Automatic sorting
- Fast search
Operations
| Function | Description | Time |
|---|---|---|
insert(x) | Insert element | O(log n) |
erase(x) | Delete element | O(log n) |
find(x) | Search | O(log n) |
count(x) | Check existence | O(log n) |
lower_bound(x) | First ≥ x | O(log n) |
upper_bound(x) | First > x | O(log n) |
size() | Number of elements | O(1) |
empty() | Check empty | O(1) |
clear() | Remove all | O(n) |
Example
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s;
s.insert(30);
s.insert(10);
s.insert(20);
s.insert(20);
s.erase(10);
for(int x:s)
cout<<x<<" ";
}Output
20 305. unordered_set
Definition
An unordered_set stores unique elements using a Hash Table. Elements are not sorted.
When to Use
- Fast lookup
- Order doesn't matter
Operations
| Function | Description | Time |
|---|---|---|
insert(x) | Insert | O(1) Average |
erase(x) | Delete | O(1) Average |
find(x) | Search | O(1) Average |
count(x) | Exists | O(1) Average |
size() | Number of elements | O(1) |
empty() | Check empty | O(1) |
clear() | Remove all | O(n) |
Example
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<int> us;
us.insert(10);
us.insert(20);
us.insert(30);
us.erase(20);
for(int x:us)
cout<<x<<" ";
}6. map
Definition
A map stores key-value pairs in sorted order using a Red-Black Tree. Keys are unique.
When to Use
- Need sorted keys
- Key-value mapping
Operations
| Function | Description | Time |
|---|---|---|
insert({k,v}) | Insert pair | O(log n) |
mp[k]=v | Insert/Update | O(log n) |
erase(k) | Delete | O(log n) |
find(k) | Search | O(log n) |
count(k) | Exists | O(log n) |
lower_bound(k) | First key ≥ k | O(log n) |
upper_bound(k) | First key > k | O(log n) |
size() | Number of pairs | O(1) |
clear() | Remove all | O(n) |
Example
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string,int> mp;
mp["Apple"]=10;
mp["Banana"]=20;
mp["Apple"]=30;
for(auto x:mp)
cout<<x.first<<" "<<x.second<<endl;
}Output
Apple 30
Banana 207. unordered_map
Definition
An unordered_map stores key-value pairs using a Hash Table. Keys are unique, but the order is not guaranteed.
When to Use
- Fast key-value lookup
- Order is not important
- Frequency counting
Operations
| Function | Description | Time |
|---|---|---|
insert({k,v}) | Insert pair | O(1) Average |
mp[k]=v | Insert/Update | O(1) Average |
erase(k) | Delete | O(1) Average |
find(k) | Search | O(1) Average |
count(k) | Exists | O(1) Average |
contains(k) (C++20) | Check key | O(1) Average |
size() | Number of pairs | O(1) |
empty() | Check empty | O(1) |
clear() | Remove all | O(n) |
Example
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string,int> mp;
mp["Apple"]=5;
mp["Banana"]=10;
mp["Apple"]++;
mp.erase("Banana");
for(auto x:mp)
cout<<x.first<<" "<<x.second<<endl;
}Possible Output
Apple 6STL Container Complexity Summary
| Container | Insert | Delete | Search | Access |
|---|---|---|---|---|
vector | O(1) end, O(n) middle | O(1) end, O(n) middle | O(n) | O(1) |
deque | O(1) front/back | O(1) front/back | O(n) | O(1) |
list | O(1) (iterator known) | O(1) (iterator known) | O(n) | O(n) |
set | O(log n) | O(log n) | O(log n) | Not supported |
unordered_set | O(1) average | O(1) average | O(1) average | Not supported |
map | O(log n) | O(log n) | O(log n) | O(log n) by key |
unordered_map | O(1) average | O(1) average | O(1) average | O(1) average by key |
1. map<int, vector<int>> pos
Think:
map<int, vector<int>> pos;means:
key → multiple integersExample:
pos[1] = {10, 20, 30};
pos[2] = {40, 50};
pos[3] = {60};Visually:
1 → [10, 20, 30]
2 → [40, 50]
3 → [60]Access
cout << pos[1][0]; // 10
cout << pos[1][1]; // 20
cout << pos[2][0]; // 40General formula
pos[key][vector_index]For example:
pos[1][2]means:
map key = 1
↓
vector = [10,20,30]
↓
index = 2
↓
302. Insert / update
pos[1].push_back(10);
pos[1].push_back(20);
pos[1].push_back(30);
pos[2].push_back(40);
pos[2].push_back(50);Now:
1 → [10,20,30]
2 → [40,50]You can also directly assign:
pos[1] = {10,20,30};3. Traverse map<int, vector<int>>
Only keys
for(auto &p : pos) {
cout << p.first << endl;
}p.first → key
p.second → vector
Keys + all vector values
for(auto &p : pos) {
cout << "Key: " << p.first << endl;
for(auto &x : p.second) {
cout << x << " ";
}
cout << endl;
}Output:
Key: 1
10 20 30
Key: 2
40 50map<int, vector<int>> pos — Full Example
This is a very useful pattern in DSA, especially when you want to store all indices/positions of each value.
map<int, vector<int>> pos;Think of it as:
key → list of positions
value → all indices where it occursFor example:
vector<int> nums = {3, 5, 3, 2, 5, 3};We want:
3 → {0, 2, 5}
5 → {1, 4}
2 → {3}1. Complete Program
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
vector<int> nums = {3, 5, 3, 2, 5, 3};
map<int, vector<int>> pos;
// Store every value with its index
for (int i = 0; i < nums.size(); i++) {
pos[nums[i]].push_back(i);
}
// Print map
for (auto &p : pos) {
cout << "Value = " << p.first << " : ";
for (int index : p.second) {
cout << index << " ";
}
cout << endl;
}
return 0;
}Output
Value = 2 : 3
Value = 3 : 0 2 5
Value = 5 : 1 42. Understand pos[nums[i]].push_back(i)
This line is the most important:
pos[nums[i]].push_back(i);Break it into pieces.
Suppose:
nums = {3, 5, 3, 2, 5, 3};i = 0
nums[0] = 3So:
pos[3].push_back(0);Map becomes:
3 → {0}i = 1
nums[1] = 5pos[5].push_back(1);Map:
3 → {0}
5 → {1}i = 2
nums[2] = 3pos[3].push_back(2);Map:
3 → {0, 2}
5 → {1}i = 3
nums[3] = 2pos[2].push_back(3);Map:
2 → {3}
3 → {0, 2}
5 → {1}i = 4
nums[4] = 5pos[5].push_back(4);Map:
2 → {3}
3 → {0, 2}
5 → {1, 4}i = 5
nums[5] = 3pos[3].push_back(5);Final:
2 → {3}
3 → {0, 2, 5}
5 → {1, 4}3. Why does pos[3] work?
The type is:
map<int, vector<int>> pos;So:
map
↓
int key → vector<int> valueTherefore:
pos[3]means:
give me the vector<int> associated with key 3Initially, if 3 doesn't exist:
pos[3]automatically creates an empty vector:
3 → {}Then:
pos[3].push_back(0);becomes:
3 → {0}Next:
pos[3].push_back(2);becomes:
3 → {0, 2}4. Access the positions
Suppose:
map<int, vector<int>> pos;contains:
2 → {3}
3 → {0, 2, 5}
5 → {1, 4}You can do:
cout << pos[3][0];Output:
0cout << pos[3][1];Output:
2cout << pos[3][2];Output:
5So:
pos[3]is:
{0, 2, 5}and:
pos[3][1]is:
2Think:
pos[3] → vector {0, 2, 5}
pos[3][0] → 0
pos[3][1] → 2
pos[3][2] → 55. Find a value
You can use find():
auto it = pos.find(3);
if (it != pos.end()) {
cout << "Found\n";
for (int index : it->second) {
cout << index << " ";
}
}Output:
Found
0 2 5Remember:
it->firstis the key.
it->secondis the vector.
So:
for (auto &it : pos) {
cout << it.first << " ";
for (int index : it.second) {
cout << index << " ";
}
}6. Another very common example
Suppose:
vector<int> nums = {10, 20, 10, 30, 20, 10};Build:
map<int, vector<int>> pos;
for (int i = 0; i < nums.size(); i++) {
pos[nums[i]].push_back(i);
}Result:
10 → {0, 2, 5}
20 → {1, 4}
30 → {3}Now:
pos[10]gives:
{0, 2, 5}and:
pos[20]gives:
{1, 4}7. Why use this in DSA?
Suppose the question says:
Find all positions where each number occurs.
Instead of repeatedly searching the array, build:
map<int, vector<int>> pos;Then you immediately know:
number → all its positionsThis is particularly useful for:
- Duplicate elements
- Frequency + positions
- Index lookup
- Two Sum variations
- Grouping elements
- Range/index queries
- Problems involving repeated values
⭐ Remember this pattern
map<int, vector<int>> pos;
for (int i = 0; i < nums.size(); i++) {
pos[nums[i]].push_back(i);
}The mental model is simply:
map
↓
┌─────────────┐
│ value │
│ ↓ │
│ positions │
└─────────────┘
3 → {0, 2, 5}
5 → {1, 4}
2 → {3}One-line meaning
map<int, vector<int>> pos= for every value, store all indices where that value appears.
4. map<int, vector<pair<int,int>>>
This is another very important structure.
map<int, vector<pair<int,int>>> mp;Meaning:
key → vector → pairExample:
mp[1].push_back({10,20});
mp[1].push_back({30,40});
mp[2].push_back({50,60});Structure:
1 → [(10,20), (30,40)]
2 → [(50,60)]Access
cout << mp[1][0].first; // 10
cout << mp[1][0].second; // 20
cout << mp[1][1].first; // 30
cout << mp[1][1].second; // 40General pattern
mp[key][vector_index].first
mp[key][vector_index].second5. Traverse it
for(auto &p : mp) {
cout << "Key = " << p.first << endl;
for(auto &q : p.second) {
cout << q.first << " " << q.second << endl;
}
}Here:
p
│
├── p.first → map key
│
└── p.second → vector<pair<int,int>>
│
├── q.first
└── q.secondmap<int, vector<pair<int,int>>> mp; means:
- Key →
int - Value →
vector<pair<int,int>> - One key can store multiple pairs.
Full example
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, vector<pair<int,int>>> mp;
// key = 1
mp[1].push_back({10, 20});
mp[1].push_back({30, 40});
mp[1].push_back({50, 60});
// key = 2
mp[2].push_back({100, 200});
mp[2].push_back({300, 400});
// key = 5
mp[5].push_back({7, 8});
// Print
for (auto &it : mp) {
cout << "Key = " << it.first << "\n";
for (auto &p : it.second) {
cout << " (" << p.first
<< ", " << p.second << ")\n";
}
cout << "\n";
}
return 0;
}Output
Key = 1
(10, 20)
(30, 40)
(50, 60)
Key = 2
(100, 200)
(300, 400)
Key = 5
(7, 8)Understand the structure
Think of it like:
map
│
├── 1 → vector
│ ├── pair(10,20)
│ ├── pair(30,40)
│ └── pair(50,60)
│
├── 2 → vector
│ ├── pair(100,200)
│ └── pair(300,400)
│
└── 5 → vector
└── pair(7,8)So:
mp[1]gives:
vector<pair<int,int>>and:
mp[1][0]gives:
pair<int,int>{10, 20}Then:
mp[1][0].first // 10
mp[1][0].second // 20Common use: graph / adjacency list
For example, if the pair represents:
(destination, weight)then:
map<int, vector<pair<int,int>>> mp;
mp[1].push_back({2, 10});
mp[1].push_back({3, 20});
mp[2].push_back({4, 5});means:
1 → 2 (weight 10)
1 → 3 (weight 20)
2 → 4 (weight 5)You can traverse it with:
for (auto &[node, edges] : mp) {
cout << "Node: " << node << "\n";
for (auto &[next, weight] : edges) {
cout << " Goes to: " << next
<< ", Weight: " << weight << "\n";
}
}Key idea: mp[key].push_back({a,b}) is the important pattern. It adds a (a,b) pair to the vector belonging to that key.
6. vector<vector<int>>
This is a 2D dynamic array.
vector<vector<int>> v;Example:
v = {
{1,2,3},
{4,5,6},
{7,8,9}
};Access:
v[0][0] // 1
v[0][1] // 2
v[1][2] // 6
v[2][0] // 7General:
v[row][column]7. vector<vector<pair<int,int>>>
Now we have:
vector
↓
vector
↓
pairDeclaration:
vector<vector<pair<int,int>>> v;Example:
v = {
{{1,2}, {3,4}},
{{5,6}, {7,8}}
};Access:
v[0][0].first // 1
v[0][0].second // 2
v[0][1].first // 3
v[0][1].second // 4
v[1][0].first // 5
v[1][0].second // 6General:
v[row][column].first
v[row][column].second8. Very important: vector<pair<int,int>>
This is simpler:
vector<pair<int,int>> v;Structure:
v
│
├── [0] → (10,20)
├── [1] → (30,40)
└── [2] → (50,60)Access:
v[0].first
v[0].second
v[1].first
v[1].second9. map<int, vector<vector<int>>>
Three layers:
map
↓
vector
↓
vector
↓
intmap<int, vector<vector<int>>> mp;Example:
mp[1] = {
{10,20},
{30,40}
};Access:
mp[1][0][0] // 10
mp[1][0][1] // 20
mp[1][1][0] // 30
mp[1][1][1] // 40General:
mp[key][row][column]10. map<int, vector<pair<int,int>>>
This one is extremely common in DSA.
map<int, vector<pair<int,int>>> mp;Example:
mp[5].push_back({10,20});
mp[5].push_back({30,40});
mp[7].push_back({50,60});Structure:
5 → [(10,20), (30,40)]
7 → [(50,60)]Access:
mp[5][0].first // 10
mp[5][0].second // 20
mp[5][1].first // 30
mp[5][1].second // 4011. unordered_map<int, vector<int>>
Almost exactly the same access as map.
unordered_map<int, vector<int>> mp;
mp[1].push_back(10);
mp[1].push_back(20);Access:
mp[1][0]; // 10
mp[1][1]; // 20Difference:
map → sorted keys
unordered_map → no sorted order12. The easiest way to remember
Look at the declaration from left to right.
vector<int>
vector → int
v[i]vector<pair<int,int>>
vector → pair → int
v[i].first
v[i].secondvector<vector<int>>
vector → vector → int
v[i][j]vector<vector<pair<int,int>>>
vector → vector → pair → int
v[i][j].first
v[i][j].secondmap<int,vector<int>>
map → vector → int
mp[key][i]map<int,vector<pair<int,int>>>
map → vector → pair → int
mp[key][i].first
mp[key][i].secondmap<int,vector<vector<int>>>
map → vector → vector → int
mp[key][i][j]13. Master table
| Declaration | Structure | Access |
|---|---|---|
vector<int> | vector → int | v[i] |
vector<pair<int,int>> | vector → pair | v[i].first |
vector<pair<int,int>> | vector → pair | v[i].second |
vector<vector<int>> | vector → vector | v[i][j] |
vector<vector<pair<int,int>>> | vector → vector → pair | v[i][j].first |
map<int,int> | map → int | mp[key] |
map<int,vector<int>> | map → vector | mp[key][i] |
map<int,pair<int,int>> | map → pair | mp[key].first |
map<int,vector<pair<int,int>>> | map → vector → pair | mp[key][i].first |
map<int,vector<vector<int>>> | map → vector → vector | mp[key][i][j] |
unordered_map<int,vector<int>> | map → vector | mp[key][i] |
🔥 One rule for DSA
Don't memorize every syntax. Follow the layers.
map<int, vector<pair<int,int>>>
↓ ↓ ↓
key index value
↓ ↓ ↓
mp[key] [index] .first/.secondSo:
mp[key][index].firstmeans:
find the key → find the vector index → get the first value of the pair.
1. STACK
Definition
A Stack is a linear data structure that follows:
LIFO — Last In, First Out
The element inserted last is removed first.
Example:
push(10)
push(20)
push(30)
Stack:
30 ← top
20
10
pop() → removes 30Real-life example
A stack of plates:
30 ← first removed
20
10A. Stack using STL
#include <stack>
stack<int> st;Important functions
| Function | Meaning | Complexity |
|---|---|---|
push(x) | Insert at top | O(1) |
pop() | Remove top | O(1) |
top() | Get top | O(1) |
empty() | Check empty | O(1) |
size() | Number of elements | O(1) |
Example:
stack<int> st;
st.push(10);
st.push(20);
st.push(30);
cout << st.top(); // 30
st.pop();
cout << st.top(); // 20⚠️ pop() does not return the element.
Wrong:
int x = st.pop();Correct:
int x = st.top();
st.pop();2. Manual Stack
We can create a stack using an array.
class Stack {
int arr[100];
int topIndex;
public:
Stack() {
topIndex = -1;
}
void push(int x) {
arr[++topIndex] = x;
}
void pop() {
if (topIndex == -1) return;
topIndex--;
}
int top() {
return arr[topIndex];
}
bool empty() {
return topIndex == -1;
}
int size() {
return topIndex + 1;
}
};Concept
topIndex = -1
push(10)
index: 0
↓
arr: [10]
topIndex = 0After:
push(20);arr:
[10][20]
↑
top3. QUEUE
Definition
A Queue follows:
FIFO — First In, First Out
The element inserted first is removed first.
push → 10 20 30 → pop
↑ ↑
front backFirst inserted:
10First removed:
104. Queue using STL
#include <queue>
queue<int> q;Functions
| Function | Meaning | Complexity |
|---|---|---|
push(x) | Insert at back | O(1) |
pop() | Remove front | O(1) |
front() | First element | O(1) |
back() | Last element | O(1) |
empty() | Check empty | O(1) |
size() | Size | O(1) |
Example:
queue<int> q;
q.push(10);
q.push(20);
q.push(30);
cout << q.front(); // 10
cout << q.back(); // 30
q.pop();
cout << q.front(); // 20Again:
q.pop();doesn't return the removed element.
5. Manual Queue
Using an array:
class Queue {
int arr[100];
int frontIndex;
int rear;
public:
Queue() {
frontIndex = 0;
rear = -1;
}
void push(int x) {
arr[++rear] = x;
}
void pop() {
if (frontIndex > rear) return;
frontIndex++;
}
int front() {
return arr[frontIndex];
}
int back() {
return arr[rear];
}
bool empty() {
return frontIndex > rear;
}
int size() {
return rear - frontIndex + 1;
}
};For interview implementation, a circular queue is better because the simple array version doesn't reuse freed positions.
6. PRIORITY QUEUE / HEAP
A Heap is a complete binary tree satisfying a heap property.
There are two common types:
Max Heap
Largest element is always at the top.
50
/ \
30 40
/ \
10 20Min Heap
Smallest element is always at the top.
10
/ \
20 30
/ \
40 50In C++, we normally use:
priority_queuefor heaps.
7. MAX HEAP
STL
priority_queue<int> pq;By default:
priority_queue= Max Heap
Example:
priority_queue<int> pq;
pq.push(10);
pq.push(50);
pq.push(20);
pq.push(40);
cout << pq.top(); // 50Functions
| Function | Meaning | Complexity |
|---|---|---|
push(x) | Insert | O(log n) |
pop() | Remove top | O(log n) |
top() | Maximum | O(1) |
empty() | Check empty | O(1) |
size() | Size | O(1) |
8. MIN HEAP
Syntax:
priority_queue<int, vector<int>, greater<int>> pq;Example:
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(50);
pq.push(10);
pq.push(30);
pq.push(20);
cout << pq.top(); // 10Remember
priority_queue<int>means:
MAX HEAPwhile
priority_queue<int, vector<int>, greater<int>>means:
MIN HEAP9. How Heap Works Internally
For an array:
index: 0 1 2 3 4
50 30 40 10 20Tree:
50
/ \
30 40
/ \
10 20For zero-based indexing:
Parent
parent = (i - 1) / 2;Left child
left = 2 * i + 1;Right child
right = 2 * i + 2;This is very important for heaps.
10. Manual Max Heap
class MaxHeap {
vector<int> heap;
public:
void push(int x) {
heap.push_back(x);
int i = heap.size() - 1;
while (i > 0) {
int parent = (i - 1) / 2;
if (heap[parent] >= heap[i])
break;
swap(heap[parent], heap[i]);
i = parent;
}
}
int top() {
return heap[0];
}
void pop() {
if (heap.empty())
return;
heap[0] = heap.back();
heap.pop_back();
int i = 0;
while (true) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int largest = i;
if (left < heap.size() &&
heap[left] > heap[largest])
largest = left;
if (right < heap.size() &&
heap[right] > heap[largest])
largest = right;
if (largest == i)
break;
swap(heap[i], heap[largest]);
i = largest;
}
}
};11. Custom Comparator
and if digit sums are equal, sort by the actual number.
So the key is:
sort(v.begin(), v.end(), [](auto &a, auto &b) {
if (digitSum(a) != digitSum(b))
return digitSum(a) < digitSum(b);
return a < b;
});Then calculate the minimum swaps to transform the original array into this sorted order.
This is one of the most important C++ DSA concepts.
A comparator tells a data structure:
How should I order these elements?
12. Custom Comparator for priority_queue
Suppose:
vector<pair<int,int>>and you want the pair with larger first value on top.
priority_queue<
pair<int,int>,
vector<pair<int,int>>,
greater<pair<int,int>>
> pq;Example:
pq.push({10, 5});
pq.push({30, 2});
pq.push({20, 7});Top:
{30, 2}because pairs compare lexicographically.
13. Your Own Comparator
Suppose:
pair<int,int>and we want:
smaller
first→ higher priority
struct Compare {
bool operator()(pair<int,int>& a,
pair<int,int>& b) {
return a.first > b.first;
}
};Then:
priority_queue<
pair<int,int>,
vector<pair<int,int>>,
Compare
> pq;14. VERY IMPORTANT: Understand Comparator
This part confuses many beginners.
return a.first > b.first;means:
ashould come afterbwhena.firstis larger.
Therefore the smaller first value comes to top.
Example:
{10, 5}
{20, 2}
{30, 7}Top:
{10,5}So:
a.first > b.firstcreates a min-priority queue based on first.
15. Max Heap with Custom Comparator
Want larger first on top?
struct Compare {
bool operator()(pair<int,int>& a,
pair<int,int>& b) {
return a.first < b.first;
}
};Then:
priority_queue<
pair<int,int>,
vector<pair<int,int>>,
Compare
> pq;Top:
largest first16. Custom Tie-Breaking
Suppose:
{10, 5}
{10, 2}
{20, 1}You want:
- Larger
first - If first is equal, smaller
second
Comparator:
struct Compare {
bool operator()(pair<int,int>& a,
pair<int,int>& b) {
if (a.first != b.first)
return a.first < b.first;
return a.second > b.second;
}
};Top becomes:
{20,1}Then:
{10,2}Then:
{10,5}17. greater<>
C++ provides a ready-made comparator:
greater<int>()Example:
priority_queue<int,
vector<int>,
greater<int>> pq;Equivalent concept:
smallest element → topUseful for:
- Dijkstra
- Kth smallest
- Merge K sorted lists
- Scheduling
- Greedy problems
18. TRIE
Definition
A Trie is a tree-based data structure used to store and search strings efficiently.
It is also called:
Prefix Tree
Example words:
cat
car
care
dogTrie:
root
/ \
c d
| |
a o
/ \ \
t r g
|
eTrie is especially useful when we care about:
Prefixes
Example:
car
care
catAll share:
ca19. Trie Node
For lowercase English letters:
struct TrieNode {
TrieNode* child[26];
bool isEnd;
TrieNode() {
isEnd = false;
for(int i = 0; i < 26; i++)
child[i] = nullptr;
}
};20. Trie Insert
void insert(string word) {
TrieNode* curr = root;
for(char ch : word) {
int index = ch - 'a';
if(curr->child[index] == nullptr)
curr->child[index] = new TrieNode();
curr = curr->child[index];
}
curr->isEnd = true;
}21. Trie Search
bool search(string word) {
TrieNode* curr = root;
for(char ch : word) {
int index = ch - 'a';
if(curr->child[index] == nullptr)
return false;
curr = curr->child[index];
}
return curr->isEnd;
}Important:
Suppose we inserted:
appleSearch:
appshould be:
falseunless app was also inserted.
That's why:
isEndis necessary.
22. Trie Prefix Search
To check:
Does any word start with
"app"?
bool startsWith(string prefix) {
TrieNode* curr = root;
for(char ch : prefix) {
int index = ch - 'a';
if(curr->child[index] == nullptr)
return false;
curr = curr->child[index];
}
return true;
}Example:
Inserted:
apple
application
app
bananastartsWith("app")returns:
true23. Complete Trie Class
class Trie {
struct Node {
Node* child[26];
bool isEnd;
Node() {
isEnd = false;
for(int i = 0; i < 26; i++)
child[i] = nullptr;
}
};
Node* root;
public:
Trie() {
root = new Node();
}
void insert(string word) {
Node* curr = root;
for(char ch : word) {
int index = ch - 'a';
if(curr->child[index] == nullptr)
curr->child[index] = new Node();
curr = curr->child[index];
}
curr->isEnd = true;
}
bool search(string word) {
Node* curr = root;
for(char ch : word) {
int index = ch - 'a';
if(curr->child[index] == nullptr)
return false;
curr = curr->child[index];
}
return curr->isEnd;
}
bool startsWith(string prefix) {
Node* curr = root;
for(char ch : prefix) {
int index = ch - 'a';
if(curr->child[index] == nullptr)
return false;
curr = curr->child[index];
}
return true;
}
};24. Trie Complexity
If the word length is L:
| Operation | Complexity |
|---|---|
| Insert | O(L) |
| Search | O(L) |
| Prefix Search | O(L) |
| Delete | O(L) |
This is independent of the number of stored words in the basic complexity expression.
25. Stack vs Queue vs Heap vs Trie
| DS | Main Rule | Main Use |
|---|---|---|
| Stack | LIFO | DFS, parentheses, monotonic stack |
| Queue | FIFO | BFS, scheduling |
| Max Heap | Maximum first | K largest, priority |
| Min Heap | Minimum first | Dijkstra, K smallest |
| Trie | Prefix-based tree | Strings/prefixes |
26. The Most Important C++ Syntax to Memorize
Stack
stack<int> st;
st.push(x);
st.pop();
st.top();
st.empty();
st.size();Queue
queue<int> q;
q.push(x);
q.pop();
q.front();
q.back();
q.empty();
q.size();Max Heap
priority_queue<int> pq;
pq.push(x);
pq.pop();
pq.top();Min Heap
priority_queue<int,
vector<int>,
greater<int>> pq;Pair Min Heap
priority_queue<
pair<int,int>,
vector<pair<int,int>>,
greater<pair<int,int>>
> pq;Custom Heap
struct Compare {
bool operator()(const pair<int,int>& a,
const pair<int,int>& b) {
return a.first > b.first;
}
};
priority_queue<
pair<int,int>,
vector<pair<int,int>>,
Compare
> pq;Trie
Trie trie;
trie.insert("apple");
trie.search("apple");
trie.startsWith("app");27. One Mental Model for All of Them
Think of the data structures this way:
STACK
↓
Last In → First Out
QUEUE
↓
First In → First Out
MAX HEAP
↓
Largest → First
MIN HEAP
↓
Smallest → First
CUSTOM HEAP
↓
"My own priority rule"
TRIE
↓
Characters → Prefix → WordFor DSA problem solving
When you see:
"last element"
"undo"
"matching brackets"
"previous greater/smaller"Think:
STACK
When you see:
"first come"
"level order"
"BFS"
"sliding window"Think:
QUEUE / DEQUE
When you see:
"largest"
"smallest"
"top K"
"minimum cost"
"maximum priority"Think:
HEAP / PRIORITY_QUEUE
When you see:
"prefix"
"dictionary"
"starts with"
"word search"Think:
TRIE

