C++ STL Containers Cheat Sheet (Definitions, Operations, Code & Time Complexity) ☑️☑️

769
Aug 07, 2026
Sep 16, 2026

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.

C++
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 value

vector<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 5

2. 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 2

5. 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) % n

6. 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
8

10. 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 element

11. Next element circularly

for(int i = 0; i < n; i++) {

    int next = (i + 1) % n;

    cout << a[next] << " ";
}

Output:

2 3 4 5 1

12. 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

PatternFormula
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 / Elimination

The 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)) × b

For 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

MeaningExample
GCDBiggest number that divides bothgcd(12,18) = 6
LCMSmallest number that both can divide intolcm(12,18) = 36

🔥 Most important formula

GCD(a,b) × LCM(a,b) = a × b

So:

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:

12

Code

#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:

36

Code

#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:

12

Code

#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:

24

Code

#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
= 24

Answer:

24

🔴 Problem 5 — GCD + LCM Together

Given:

a = 18
b = 24

Find both GCD and LCM.

Output:

GCD = 6
LCM = 72

Code

#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) × b

Practice 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

TaskPattern
int → stringto_string(n)
string → intstoi(s)
binary string → intstoi(s,nullptr,2)
int → binarybitset<32>(n).to_string()
get last bitn & 1
divide by 2n >> 1
multiply by 2n << 1
check kth bit(n >> k) & 1
set kth bitn | (1 << k)
clear kth bitn & ~(1 << k)
toggle kth bitn ^ (1 << k)
remove rightmost 1n & (n - 1)
get rightmost 1n & -n
power of 2n > 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 tricks

If 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);  // false

2️⃣ 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 numberMany numbers
MethodisPrime()sieve()
ComplexityO(√n)O(n log log n)
UseCheck one numberFind 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 3

So:

12 = 2 × 2 × 3

Prime 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 = 12

Output:

1 2 3 4 6 12

3. Prime factors

Prime factors are the prime numbers that divide n.

12 = 2 × 2 × 3

Therefore:

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:

12

we get:

12 = 2 × 2 × 3

So:

{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:

12

factors are:

1, 2, 3, 4, 6, 12

Therefore:

count = 6

Simple:

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:

12
1 + 2 + 3 + 4 + 6 + 12
= 28

Code:

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:

12

Normal factors:

1 2 3 4 6 12

Proper factors:

1 2 3 4 6

Code:

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

FunctionDescriptionTime
push_back(x)Insert at endO(1) Amortized
pop_back()Remove last elementO(1)
insert(pos,x)Insert at positionO(n)
erase(pos)Remove elementO(n)
clear()Remove all elementsO(n)
resize(n)Change sizeO(n)
reserve(n)Increase capacityO(n) (if reallocates)
size()Number of elementsO(1)
empty()Check emptyO(1)
front()First elementO(1)
back()Last elementO(1)
at(i)Access elementO(1)
operator[]Access elementO(1)
find() (algorithm)Search elementO(n)
sort() (algorithm)Sort vectorO(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];   // 40
Before: 10 20 30
After : 10 20 30 40
                    ↑
                  added

Why 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 20

No 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
      ↑
    inserted

Elements after the position must shift.

Before:
10 20 30 40
      ↓
After:
10 20 25 30 40
         ← shifting

Therefore:

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 40

20 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();   // 0
Before: 10 20 30 40
After : empty

The 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 0

If increasing the size, new elements are added.

You can also specify a value:

v.resize(5, 100);
10 20 30 100 100

7. reserve(n) — O(n) if reallocation

Reserves capacity, not size.

vector<int> v;

v.reserve(100);

Important:

v.size();       // 0
v.capacity();   // at least 100

resize() vs reserve()

v.resize(100);

means:

size = 100

while

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:

3

Vector 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:

Empty

Equivalent idea:

v.size() == 0

10. front() — O(1)

Returns the first element.

vector<int> v = {10, 20, 30};

cout << v.front();

Output:

10

Same idea as:

v[0]

11. back() — O(1)

Returns the last element.

vector<int> v = {10, 20, 30};

cout << v.back();

Output:

30

Same 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:

20

Important 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:

20

Usually faster than at() because it doesn't perform bounds checking.

v[1]      // no bounds checking
v.at(1)   // bounds checking

14. 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
          ↑
        found

In 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 40

How to remember

sort(v.begin(), v.end());

means:

start ───────────────→ end
      sort everything

Complexity:

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

FunctionDescriptionTime
push_back(x)Insert backO(1)
push_front(x)Insert frontO(1)
pop_back()Remove backO(1)
pop_front()Remove frontO(1)
insert()Insert middleO(n)
erase()Delete middleO(n)
front()First elementO(1)
back()Last elementO(1)
size()Number of elementsO(1)
empty()Check emptyO(1)
find() (algorithm)SearchO(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 30

3. 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

FunctionDescriptionTime
push_back(x)Insert endO(1)
push_front(x)Insert frontO(1)
pop_back()Delete endO(1)
pop_front()Delete frontO(1)
insert(it,x)Insert at iteratorO(1)
erase(it)Delete at iteratorO(1)
remove(x)Remove valueO(n)
sort()Sort listO(n log n)
reverse()Reverse listO(n)
size()Number of elementsO(1)
find() (algorithm)SearchO(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 30

4. 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

FunctionDescriptionTime
insert(x)Insert elementO(log n)
erase(x)Delete elementO(log n)
find(x)SearchO(log n)
count(x)Check existenceO(log n)
lower_bound(x)First ≥ xO(log n)
upper_bound(x)First > xO(log n)
size()Number of elementsO(1)
empty()Check emptyO(1)
clear()Remove allO(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 30

5. 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

FunctionDescriptionTime
insert(x)InsertO(1) Average
erase(x)DeleteO(1) Average
find(x)SearchO(1) Average
count(x)ExistsO(1) Average
size()Number of elementsO(1)
empty()Check emptyO(1)
clear()Remove allO(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

FunctionDescriptionTime
insert({k,v})Insert pairO(log n)
mp[k]=vInsert/UpdateO(log n)
erase(k)DeleteO(log n)
find(k)SearchO(log n)
count(k)ExistsO(log n)
lower_bound(k)First key ≥ kO(log n)
upper_bound(k)First key > kO(log n)
size()Number of pairsO(1)
clear()Remove allO(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 20

7. 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

FunctionDescriptionTime
insert({k,v})Insert pairO(1) Average
mp[k]=vInsert/UpdateO(1) Average
erase(k)DeleteO(1) Average
find(k)SearchO(1) Average
count(k)ExistsO(1) Average
contains(k) (C++20)Check keyO(1) Average
size()Number of pairsO(1)
empty()Check emptyO(1)
clear()Remove allO(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 6

STL Container Complexity Summary

ContainerInsertDeleteSearchAccess
vectorO(1) end, O(n) middleO(1) end, O(n) middleO(n)O(1)
dequeO(1) front/backO(1) front/backO(n)O(1)
listO(1) (iterator known)O(1) (iterator known)O(n)O(n)
setO(log n)O(log n)O(log n)Not supported
unordered_setO(1) averageO(1) averageO(1) averageNot supported
mapO(log n)O(log n)O(log n)O(log n) by key
unordered_mapO(1) averageO(1) averageO(1) averageO(1) average by key

1. map<int, vector<int>> pos

Think:

map<int, vector<int>> pos;

means:

key → multiple integers

Example:

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];  // 40

General formula

pos[key][vector_index]

For example:

pos[1][2]

means:

map key = 1
       ↓
   vector = [10,20,30]
                ↓
          index = 2
                ↓
               30

2. 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 50

map<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 occurs

For 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 4

2. 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] = 3

So:

pos[3].push_back(0);

Map becomes:

3 → {0}

i = 1

nums[1] = 5
pos[5].push_back(1);

Map:

3 → {0}
5 → {1}

i = 2

nums[2] = 3
pos[3].push_back(2);

Map:

3 → {0, 2}
5 → {1}

i = 3

nums[3] = 2
pos[2].push_back(3);

Map:

2 → {3}
3 → {0, 2}
5 → {1}

i = 4

nums[4] = 5
pos[5].push_back(4);

Map:

2 → {3}
3 → {0, 2}
5 → {1, 4}

i = 5

nums[5] = 3
pos[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> value

Therefore:

pos[3]

means:

give me the vector<int> associated with key 3

Initially, 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:

0
cout << pos[3][1];

Output:

2
cout << pos[3][2];

Output:

5

So:

pos[3]

is:

{0, 2, 5}

and:

pos[3][1]

is:

2

Think:

pos[3]       → vector {0, 2, 5}
pos[3][0]    → 0
pos[3][1]    → 2
pos[3][2]    → 5

5. 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 5

Remember:

it->first

is the key.

it->second

is 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 positions

This 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 → pair

Example:

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;  // 40

General pattern

mp[key][vector_index].first
mp[key][vector_index].second

5. 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.second

map<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  // 20

Common 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]   // 7

General:

v[row][column]

7. vector<vector<pair<int,int>>>

Now we have:

vector
  ↓
vector
  ↓
pair

Declaration:

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   // 6

General:

v[row][column].first
v[row][column].second

8. 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].second

9. map<int, vector<vector<int>>>

Three layers:

map
 ↓
vector
 ↓
vector
 ↓
int
map<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]  // 40

General:

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  // 40

11. 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];  // 20

Difference:

map            → sorted keys
unordered_map  → no sorted order

12. 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].second

vector<vector<int>>

vector → vector → int

v[i][j]

vector<vector<pair<int,int>>>

vector → vector → pair → int

v[i][j].first
v[i][j].second

map<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].second

map<int,vector<vector<int>>>

map → vector → vector → int

mp[key][i][j]

13. Master table

DeclarationStructureAccess
vector<int>vector → intv[i]
vector<pair<int,int>>vector → pairv[i].first
vector<pair<int,int>>vector → pairv[i].second
vector<vector<int>>vector → vectorv[i][j]
vector<vector<pair<int,int>>>vector → vector → pairv[i][j].first
map<int,int>map → intmp[key]
map<int,vector<int>>map → vectormp[key][i]
map<int,pair<int,int>>map → pairmp[key].first
map<int,vector<pair<int,int>>>map → vector → pairmp[key][i].first
map<int,vector<vector<int>>>map → vector → vectormp[key][i][j]
unordered_map<int,vector<int>>map → vectormp[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/.second

So:

mp[key][index].first

means:

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 30

Real-life example

A stack of plates:

   30 ← first removed
   20
   10

A. Stack using STL

#include <stack>

stack<int> st;

Important functions

FunctionMeaningComplexity
push(x)Insert at topO(1)
pop()Remove topO(1)
top()Get topO(1)
empty()Check emptyO(1)
size()Number of elementsO(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 = 0

After:

push(20);
arr:
[10][20]
      ↑
    top

3. QUEUE

Definition

A Queue follows:

FIFO — First In, First Out

The element inserted first is removed first.

push → 10 20 30 → pop
        ↑       ↑
      front     back

First inserted:

10

First removed:

10

4. Queue using STL

#include <queue>

queue<int> q;

Functions

FunctionMeaningComplexity
push(x)Insert at backO(1)
pop()Remove frontO(1)
front()First elementO(1)
back()Last elementO(1)
empty()Check emptyO(1)
size()SizeO(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(); // 20

Again:

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 20

Min Heap

Smallest element is always at the top.

        10
       /  \
     20    30
    / \
   40 50

In C++, we normally use:

priority_queue

for 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(); // 50

Functions

FunctionMeaningComplexity
push(x)InsertO(log n)
pop()Remove topO(log n)
top()MaximumO(1)
empty()Check emptyO(1)
size()SizeO(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(); // 10

Remember

priority_queue<int>

means:

MAX HEAP

while

priority_queue<int, vector<int>, greater<int>>

means:

MIN HEAP

9. How Heap Works Internally

For an array:

index:  0   1   2   3   4

        50  30  40  10  20

Tree:

          50
        /    \
      30      40
     /  \
   10    20

For 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:

a should come after b when a.first is larger.

Therefore the smaller first value comes to top.

Example:

{10, 5}
{20, 2}
{30, 7}

Top:

{10,5}

So:

a.first > b.first

creates 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 first

16. Custom Tie-Breaking

Suppose:

{10, 5}
{10, 2}
{20, 1}

You want:

  1. Larger first
  2. 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 → top

Useful 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
dog

Trie:

             root
            /    \
           c      d
           |      |
           a      o
         /  \      \
        t    r      g
             |
             e

Trie is especially useful when we care about:

Prefixes

Example:

car
care
cat

All share:

ca

19. 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:

apple

Search:

app

should be:

false

unless app was also inserted.

That's why:

isEnd

is 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
banana
startsWith("app")

returns:

true

23. 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:

OperationComplexity
InsertO(L)
SearchO(L)
Prefix SearchO(L)
DeleteO(L)

This is independent of the number of stored words in the basic complexity expression.


25. Stack vs Queue vs Heap vs Trie

DSMain RuleMain Use
StackLIFODFS, parentheses, monotonic stack
QueueFIFOBFS, scheduling
Max HeapMaximum firstK largest, priority
Min HeapMinimum firstDijkstra, K smallest
TriePrefix-based treeStrings/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 → Word

For 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

Comments (0)