Show 25 50 100
PDF

Index

  1. Largest of Three Numbers
  2. Sum of 1 to N
  3. Swap Two Numbers
  4. Prime Number
  5. GCD / HCF
  6. LCM
  7. Armstrong Number
  8. Perfect Number
  9. Anagram Check
  10. Even or Odd
  11. Leap Year
  12. Factorial
  13. Fibonacci Series
  14. Reverse a Number
  15. Palindrome Number
  16. Reverse a String
  17. Count Vowels
  18. Sum of Digits
  19. Decimal to Binary
  20. Second Largest Element
  21. Remove Duplicates from Array
  22. Structure of a C++ Program
  23. Data Types and Sizes
  24. Pointers
  25. Reference vs Pointer
  26. Call by Value vs Call by Reference
  27. Function Overloading
  28. Dynamic Memory (new / delete)
  29. STL: vector, map, set
  30. String Functions
  31. const, static and inline
  32. Templates
  33. Exception Handling
  34. OOP, Class and Object
  35. Constructor and Destructor
  36. Encapsulation
  37. Access Specifiers
  38. Inheritance
  39. Polymorphism
  40. Abstraction and Abstract Class
  41. Interface vs Abstract Class
  42. this Pointer and Static Members
  43. Friend Function and Operator Overloading
  44. SOLID Principles
  45. Association, Aggregation, Composition
  46. What is a Data Structure
  47. Array
  48. Linked List
  49. Stack
  50. Queue
1 Index
Solution 1: if - else if C++ 6 lines
if(a >= b && a >= c)
    cout << a;
else if(b >= a && b >= c)
    cout << b;
else
    cout << c;
Solution 2: Nested max() C++ 1 line
cout << max(a, max(b, c));
Solution 3: max() with initializer list (shortest) C++ 1 line
cout << max({a, b, c});

Note: max() needs #include <algorithm>.

2 Index

Formula: (n * (n + 1)) / 2

Solution 1: Formula O(1) [BEST] C++ 2 lines
int n = 100;
cout << (n * (n + 1)) / 2; // 5050

Note: If N is big, use long long (n * (n + 1) can overflow int).

C++ 2 lines
long long n = 100000;
cout << (n * (n + 1)) / 2; // 5000050000
Solution 2: Loop O(n) C++ 4 lines
int n = 100, sum = 0;
for(int i = 1; i <= n; i++)
    sum += i;
cout << sum;
Solution 3: Recursion ★★★ C++ 4 lines
int sum(int n){
    if(n == 0) return 0;
    return n + sum(n - 1);
}
3 Index

Viva te 'swap without 3rd variable' khub jigges kore. Real code e std::swap use korbe.

Solution 1: Using 3rd variable C++ 4 lines
int a = 10, b = 20;
int temp = b;
b = a;
a = temp;
Solution 2: Without 3rd variable (+ / -) C++ 3 lines
a = a + b;
b = a - b;
a = a - b;
Solution 3: Without 3rd variable (XOR) C++ 3 lines
a = a ^ b;
b = a ^ b;
a = a ^ b;
Solution 4: std::swap (best in practice) C++ 2 lines
int a = 10, b = 20;
swap(a, b);

Note: swap() needs #include <utility> and #include <algorithm>.

4 Index

Note:

0 and 1 are not prime numbers.

2 is the smallest prime number.

A prime number is a number that can be divided only by 1 and itself.

Solution 1: Basic O(n) C++ 7 lines
bool isPrime(int n){
    if(n < 2) return false;
    for(int i = 2; i < n; i++){
        if(n % i == 0) return false;
    }
    return true;
}
Solution 2: Optimized O(sqrt n) ★★★★★ C++ 34 lines
#include <iostream>
using namespace std;

int main() {
    int n = 5;
    bool prime = true;
    if (n < 2)
        prime = false;

    // i*i means i × i.
    // We check only up to √n.
    // Example: n = 5
    // i = 2 → 2×2 = 4 <= 5 → check 5 % 2
    // i = 3 → 3×3 = 9 > 5 → stop
    //
    // We don't need to check after √n,
    // because the factors after √n are already covered.
    //
    // Advantage: Fewer checks and faster execution.
    // Time Complexity: O(√n)
    // Space Complexity: O(1)
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            prime = false;
            break;
        }
    }

    if (prime)
        cout << "Prime";
    else
        cout << "Not Prime";
    return 0;
}
5 Index

Note:

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two or more numbers is the largest number that divides all of them exactly (with no remainder).

It is found using the Euclidean Algorithm, which is very important for interviews.

Solution 1: Euclidean Algorithm (loop) C++ 7 lines
int a = 12, b = 18;
while(b != 0){
    int temp = b;
    b = a % b;
    a = temp;
}
cout << a; // 6
Solution 2: Recursive C++ 4 lines
int gcd(int a, int b){
    if(b == 0) return a;
    return gcd(b, a % b);
}
Solution 3: Built-in (C++17 std::gcd / __gcd) C++ 2 lines
cout << gcd(12, 18);   // <numeric>, C++17
cout << __gcd(12, 18);

Note: gcd() needs #include <numeric>.

Solution 4: GCD of multiple numbers ★★★★★ C++ 18 lines
int gcd(int a, int b){
    while(b != 0){
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main(){
    int arr[] = {12, 18, 24, 30, 36};
    int len = sizeof(arr) / sizeof(arr[0]);
    int result = arr[0];
    for(int i = 1; i < len; i++){
        result = gcd(result, arr[i]);
    }
    cout << result; // 6
}
6 Index

Note:

LCM (Least Common Multiple) is the smallest number that is a multiple of both numbers.

Example: LCM of 12 and 18 is 36.

Formula: LCM(a, b) = (a × b) / GCD(a, b)

Solution 1: Two numbers (using GCD) C++ 14 lines
int lcm(int a, int b){
    int x = a, y = b;
    while(y != 0){
        int temp = y;
        y = x % y;
        x = temp;
    }
    int gcd = x;
    return (a / gcd) * b;
}

int main(){
    cout << lcm(12, 18); // 36
}
Solution 2: Multiple numbers C++ 22 lines
int gcd(int a, int b){
    while(b != 0){
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int lcm(int a, int b){
    return (a / gcd(a, b)) * b;
}

int main(){
    int arr[] = {5, 10, 15, 30};
    int len = sizeof(arr) / sizeof(arr[0]);
    int result = arr[0];
    for(int i = 1; i < len; i++){
        result = lcm(result, arr[i]);
    }
    cout << "LCM " << result; // 30
}
7 Index

Note:

Let number = abcd and total digits = n.

If aⁿ + bⁿ + cⁿ + dⁿ = original number, then it is an Armstrong number.

Example 1: 153 → 1³ + 5³ + 3³ = 1 + 125 + 27 = 153

Example 2: 1634 → 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634

Solution 1: Manual power (safe, no double) C++ 19 lines
int main() {
    int n = 1634;
    int len = to_string(n).length();
    int temp = n;
    int sum = 0;

    while(temp != 0){
        int digit = temp % 10;
        int power = 1;
        for(int i = 0; i < len; i++){
            power = power * digit;
        }
        sum = sum + power;
        temp = temp / 10;
    }

    if(sum == n) cout << "Armstrong";
    else cout << "Not Armstrong";
}
Solution 2: Using pow() (round is needed) C++ 2 lines
int digit = temp % 10;
sum += (int)round(pow(digit, len));

Note: pow() returns a double, so a direct int cast can give a wrong answer (for example 124.99999 becomes 124). Use round() to be safe.

8 Index

Definition:

A perfect number is a number whose sum of all divisors (excluding the number itself) is equal to the number.

Example: 6 = 1 + 2 + 3

C++ 6 lines
int n = 28, sum = 0;
for(int i = 1; i <= n / 2; i++){
    if(n % i == 0) sum += i;
}
if(sum == n) cout << "Perfect";
else cout << "Not Perfect";
9 Index

Definition:

Two strings are anagrams if they have the same characters (same count) but in a different order.

Example: listen / silent

Solution 1: Sorting O(n log n) C++ 4 lines
string a = "listen", b = "silent";
sort(a.begin(), a.end());
sort(b.begin(), b.end());
cout << (a == b ? "Anagram" : "Not Anagram");

Note: sort() needs #include <algorithm>.

10 Index

A number is even if it is divisible by 2 (n % 2 == 0), otherwise it is odd.

Solution 1: Modulus C++ 3 lines
int n = 7;
if(n % 2 == 0) cout << "Even";
else cout << "Odd";
Solution 2: Bitwise AND (faster) C++ 3 lines
// The last bit of an odd number is always 1
if(n & 1) cout << "Odd";
else cout << "Even";
11 Index

Rule: a year is a leap year if it is divisible by 400, or divisible by 4 but not by 100.

Example: 2000 and 2024 are leap years; 1900 is not.

C++ 5 lines
int y = 2024;
if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
    cout << "Leap Year";
else
    cout << "Not Leap Year";
12 Index

Formula: n! = n × (n-1) × ... × 1, and 0! = 1.

Example: 5! = 120

Solution 1: Loop O(n) C++ 5 lines
int n = 5;
long long fact = 1;
for(int i = 1; i <= n; i++)
    fact *= i;
cout << fact; // 120
Solution 2: Recursion C++ 4 lines
long long fact(int n){
    if(n <= 1) return 1;
    return n * fact(n - 1);
}

Note: 20! is the largest factorial that fits in long long.

13 Index

Each term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13 ...

Formula: F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1

Solution 1: Loop O(n) C++ 8 lines
int n = 10, a = 0, b = 1;
for(int i = 0; i < n; i++){
    cout << a << " ";
    int next = a + b;
    a = b;
    b = next;
}
// 0 1 1 2 3 5 8 13 21 34
Solution 2: Recursion O(2^n) (slow, viva only) C++ 4 lines
int fib(int n){
    if(n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}
Solution 3: Memoization O(n) C++ 6 lines
long long memo[100];
long long fib(int n){
    if(n <= 1) return n;
    if(memo[n]) return memo[n];
    return memo[n] = fib(n - 1) + fib(n - 2);
}

Q & A

  1. Why is plain recursive Fibonacci slow?
    The same values are computed again and again, so the calls grow like 2^n. Memoization stores each answer once and makes it O(n).
14 Index

Take the last digit with % 10, add it to the result, then drop it with / 10.

C++ 7 lines
int n = 1234, rev = 0;
while(n != 0){
    int digit = n % 10;
    rev = rev * 10 + digit;
    n /= 10;
}
cout << rev; // 4321
15 Index

A number is a palindrome if it reads the same backwards. Example: 121, 1331

Solution 1: Reverse and compare C++ 6 lines
int n = 121, temp = n, rev = 0;
while(temp != 0){
    rev = rev * 10 + temp % 10;
    temp /= 10;
}
cout << (rev == n ? "Palindrome" : "Not Palindrome");
Solution 2: Palindrome string (two pointers) C++ 5 lines
string s = "madam";
bool ok = true;
for(int i = 0, j = s.size() - 1; i < j; i++, j--)
    if(s[i] != s[j]) { ok = false; break; }
cout << (ok ? "Palindrome" : "Not Palindrome");
16 Index
Solution 1: std::reverse C++ 3 lines
string s = "hello";
reverse(s.begin(), s.end());
cout << s; // olleh
Solution 2: Two pointers C++ 6 lines
string s = "hello";
int i = 0, j = s.size() - 1;
while(i < j){
    swap(s[i], s[j]);
    i++; j--;
}

Note: reverse() needs #include <algorithm>.

17 Index
C++ 8 lines
string s = "Programming";
int count = 0;
for(char c : s){
    c = tolower(c);
    if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
        count++;
}
cout << count; // 3
19 Index

Divide by 2 repeatedly and read the remainders from bottom to top. Example: 13 = 1101

Solution 1: Repeated division C++ 7 lines
int n = 13;
string bin = "";
while(n > 0){
    bin = char('0' + n % 2) + bin;
    n /= 2;
}
cout << bin; // 1101
Solution 2: bitset C++ 2 lines
#include <bitset>
cout << bitset<8>(13); // 00001101
Binary to Decimal C++ 5 lines
string b = "1101";
int dec = 0;
for(char c : b)
    dec = dec * 2 + (c - '0');
cout << dec; // 13
20 Index
Single pass O(n) C++ 11 lines
int arr[] = {12, 35, 1, 10, 34, 1};
int first = INT_MIN, second = INT_MIN;
for(int x : arr){
    if(x > first){
        second = first;
        first = x;
    } else if(x > second && x != first){
        second = x;
    }
}
cout << second; // 34
21 Index
Solution 1: sort + unique C++ 4 lines
vector<int> v = {1, 2, 2, 3, 4, 4, 5};
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
// 1 2 3 4 5
Solution 2: set C++ 1 line
set<int> s(v.begin(), v.end()); // keeps one of each, sorted
22 Index

Every C++ program starts running from main(). Header files bring in library code, and using namespace std; lets us write cout instead of std::cout.

C++ 10 lines
#include <iostream>      // header for input / output
using namespace std;     // use names from std without std::

int main() {             // execution starts here
    int age;
    cout << "Enter age: ";
    cin >> age;          // input
    cout << "Age is " << age << endl;  // output
    return 0;            // 0 = program ended successfully
}
  • #include is a preprocessor directive; it copies the header in before compiling.
  • cin uses >> (extraction), cout uses << (insertion).
  • endl adds a new line and flushes the buffer; "\n" only adds a new line (faster).

Q & A

  1. What is the difference between C and C++?
    C is procedural. C++ adds object-oriented programming (classes, inheritance, polymorphism), references, function overloading, templates, exceptions and the STL.
  2. Why does main() return int?
    The return value goes to the operating system. 0 means success, any other value means an error.
23 Index
TypeSize (typical)Range / Use
bool1 bytetrue / false
char1 byte-128 to 127, one character
int4 bytesabout ±2.1 × 109
long long8 bytesabout ±9.2 × 1018
float4 bytes~7 decimal digits
double8 bytes~15 decimal digits
stringvariestext (std::string)
C++ 3 lines
cout << sizeof(int) << endl;        // 4
cout << sizeof(long long) << endl;  // 8
cout << INT_MAX << endl;            // 2147483647 (needs <climits>)

Type casting: (double)a / b or static_cast<double>(a) / b gives a decimal result; a / b with two ints drops the fraction.

24 Index

A pointer stores the memory address of another variable. & gives an address, * reads the value at an address (dereference).

p holds the address of x, so *p gives the value of x

p holds the address of x, so *p gives the value of x

C++ 8 lines
int x = 10;
int *p = &x;        // p stores the address of x
cout << p;          // address, e.g. 0x7ffe10
cout << *p;         // 10
*p = 20;            // changes x through the pointer
cout << x;          // 20

int *q = nullptr;   // points nowhere (always initialise pointers)
Pointer and array C++ 3 lines
int arr[] = {10, 20, 30};
int *p = arr;           // array name = address of first element
cout << *(p + 1);       // 20  (pointer arithmetic)

Q & A

  1. What is a null pointer?
    A pointer that points to nothing (nullptr). Dereferencing it crashes the program, so check before use.
  2. What is a dangling pointer?
    A pointer that still holds the address of memory that has already been freed or has gone out of scope.
  3. What is a void pointer?
    A generic pointer (void*) that can hold the address of any type, but must be cast before dereferencing.
25 Index

A reference is another name (alias) for an existing variable.

C++ 4 lines
int x = 10;
int &r = x;   // r is another name for x
r = 50;
cout << x;    // 50
ReferencePointer
Must be initialised when declaredCan be declared without a value
Cannot be nullCan be nullptr
Cannot be changed to refer to another variableCan point to another address later
No special syntax to access (r)Needs * to access (*p)
26 Index

Call by value passes a copy, so changes inside the function do not affect the caller. Call by reference passes the variable itself.

C++ 11 lines
void byValue(int a)      { a = 100; }
void byReference(int &a) { a = 100; }
void byPointer(int *a)   { *a = 100; }

int main() {
    int x = 1;
    byValue(x);      cout << x;  // 1   (copy changed)
    byReference(x);  cout << x;  // 100
    x = 1;
    byPointer(&x);   cout << x;  // 100
}

Tip: pass large objects as const T& to avoid copying and to stop accidental changes.

27 Index

Several functions with the same name but different parameter lists (number or type). The compiler picks the right one at compile time (compile-time polymorphism).

C++ 7 lines
int add(int a, int b)          { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c)   { return a + b + c; }

add(2, 3);        // 5
add(2.5, 1.5);    // 4.0
add(1, 2, 3);     // 6

Note: a different return type alone is not enough to overload.

28 Index

new allocates memory on the heap at run time; delete frees it. Forgetting delete causes a memory leak.

Local variables live on the stack, new allocates on the heap

Local variables live on the stack, new allocates on the heap

C++ 9 lines
int *p = new int(5);       // single int on heap
delete p;

int n = 5;
int *arr = new int[n];     // array on heap
delete[] arr;              // use delete[] for arrays

// Modern C++: smart pointers free memory automatically
unique_ptr<int> u = make_unique<int>(10);   // needs <memory>

Q & A

  1. malloc vs new?
    malloc is a C function that returns void* and does not call constructors. new is a C++ operator, returns the correct type and calls the constructor; delete calls the destructor.
29 Index

The Standard Template Library gives ready-made containers and algorithms.

vector (dynamic array) C++ 5 lines
vector<int> v = {3, 1, 2};
v.push_back(4);             // add at end
sort(v.begin(), v.end());   // 1 2 3 4
cout << v.size();           // 4
for (int x : v) cout << x << " ";
map (key → value) C++ 6 lines
map<string, int> age;       // sorted by key
age["Rahim"] = 25;
age["Karim"] = 30;
for (auto &[name, a] : age)
    cout << name << " " << a << endl;
if (age.count("Rahim")) cout << "found";
set (unique, sorted) C++ 3 lines
set<int> s = {5, 1, 5, 3};  // unique and sorted: 1 3 5
s.insert(2);
cout << s.count(5);         // 1 = present
ContainerLookupNotes
vectorO(1) by indexContiguous, push_back amortised O(1)
map / setO(log n)Red-black tree, keeps keys sorted
unordered_map / setO(1) averageHash table, no order
stack / queuetop/front O(1)Adapters for LIFO / FIFO
priority_queuetop O(1), push O(log n)Max-heap by default
30 Index
C++ 10 lines
string s = "Hello World";
s.length();              // 11
s.substr(0, 5);          // "Hello"
s.find("World");         // 6 (string::npos if not found)
s += "!";                // append
s.replace(0, 5, "Hi");   // "Hi World!"
toupper(s[0]);           // single char to upper case
stoi("123");             // string → int
to_string(456);          // int → string
getline(cin, s);         // read a full line with spaces
31 Index
  • const — value cannot change after initialisation. A const member function cannot modify the object.
  • static local variable — keeps its value between function calls.
  • static member — one copy shared by all objects of the class.
  • inline — asks the compiler to paste the function body at the call site to avoid call overhead (for small functions).
C++ 6 lines
void counter() {
    static int count = 0;   // initialised only once
    count++;
    cout << count << " ";
}
// counter(); counter(); counter();  →  1 2 3
32 Index

Templates let one function or class work with any data type (generic programming). The STL is built on templates.

C++ 8 lines
template <typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}

getMax(3, 7);        // 7
getMax(2.5, 1.5);    // 2.5
getMax<char>('a', 'z');
33 Index

Errors are thrown with throw and caught with try / catch, so the program does not crash.

C++ 10 lines
int divide(int a, int b) {
    if (b == 0) throw runtime_error("Division by zero");
    return a / b;
}

try {
    cout << divide(10, 0);
} catch (const exception &e) {
    cout << "Error: " << e.what();
}
34 Index

OOP (Object Oriented Programming) organises a program around objects that hold data (attributes) and behaviour (methods) together.

Class is the blueprint; object is a real instance created from it. Example: class Car → objects myCar, yourCar.

Encapsulation, Abstraction, Inheritance, Polymorphism

Encapsulation, Abstraction, Inheritance, Polymorphism

C++ 16 lines
class Car {
public:
    string brand;       // attribute
    int speed;

    void drive() {      // method
        cout << brand << " is driving at " << speed << " km/h\n";
    }
};

int main() {
    Car c1;             // object
    c1.brand = "Toyota";
    c1.speed = 80;
    c1.drive();
}

Q & A

  1. Does a class take memory?
    No. Memory is allocated only when an object is created.
  2. Advantages of OOP?
    Reusability (inheritance), security (encapsulation), easy maintenance, real-world modelling and flexibility (polymorphism).
35 Index

A constructor has the same name as the class, no return type, and runs automatically when an object is created. A destructor (~ClassName) runs when the object is destroyed.

  • Default constructor — no parameters.
  • Parameterised constructor — takes arguments.
  • Copy constructor — creates an object from another object: Student(const Student &s).
  • Constructors can be overloaded; a destructor cannot (only one, no parameters).
C++ 13 lines
class Student {
    string name;
    int roll;
public:
    Student() : name("Unknown"), roll(0) {}                 // default
    Student(string n, int r) : name(n), roll(r) {}          // parameterised
    Student(const Student &s) : name(s.name), roll(s.roll) {} // copy
    ~Student() { cout << name << " destroyed\n"; }          // destructor
};

Student a;               // default
Student b("Rahim", 7);   // parameterised
Student c = b;           // copy

Q & A

  1. Can a constructor be private?
    Yes. It stops outside code from creating objects directly, used for example in the Singleton pattern.
  2. Shallow vs deep copy?
    A shallow copy copies pointer values, so both objects share the same memory. A deep copy allocates new memory and copies the data.
36 Index

Wrapping data and methods into a single unit (class) and hiding the data with private. Outside code uses public getters and setters, which can validate values.

C++ 14 lines
class BankAccount {
private:
    double balance = 0;          // hidden
public:
    void deposit(double amount) {
        if (amount > 0) balance += amount;   // validation
    }
    double getBalance() const { return balance; }
};

BankAccount acc;
acc.deposit(500);
// acc.balance = 1000000;   // error: balance is private
cout << acc.getBalance();    // 500
37 Index
SpecifierSame classChild classOutside
public✔✔✔
protected✔✔✘
private✔✘✘

Note: in C++ class members are private by default; struct members are public by default.

38 Index

A child (derived) class gets the members of a parent (base) class, so code is reused. It models an is-a relationship: a Dog is an Animal.

Single, multilevel, multiple and hierarchical inheritance

Single, multilevel, multiple and hierarchical inheritance

C++ 13 lines
class Animal {
public:
    void eat() { cout << "Eating\n"; }
};

class Dog : public Animal {      // Dog inherits Animal
public:
    void bark() { cout << "Barking\n"; }
};

Dog d;
d.eat();    // from Animal
d.bark();   // own method

Q & A

  1. What is the diamond problem?
    In multiple inheritance, if B and C both inherit A and D inherits B and C, D gets two copies of A. C++ solves it with virtual inheritance (class B : virtual public A).
  2. Constructor call order in inheritance?
    Parent constructor runs first, then child. Destructors run in the reverse order: child first, then parent.
39 Index

Polymorphism means one name, many forms.

Compile-time (static)Run-time (dynamic)
Function overloading, operator overloadingFunction overriding with virtual functions
Decided by the compilerDecided while running (via vtable)
FasterMore flexible
Run-time polymorphism C++ 24 lines
class Shape {
public:
    virtual double area() { return 0; }     // virtual = can be overridden
    virtual ~Shape() {}
};

class Circle : public Shape {
    double r;
public:
    Circle(double r) : r(r) {}
    double area() override { return 3.1416 * r * r; }
};

class Square : public Shape {
    double a;
public:
    Square(double a) : a(a) {}
    double area() override { return a * a; }
};

Shape *s1 = new Circle(2);
Shape *s2 = new Square(3);
cout << s1->area();   // 12.56  → Circle's area()
cout << s2->area();   // 9      → Square's area()

Q & A

  1. Overloading vs overriding?
    Overloading: same name, different parameters, in the same class, compile time. Overriding: same signature in parent and child, run time, needs inheritance (and virtual in C++).
  2. Why should a base class destructor be virtual?
    So that deleting a child object through a base pointer also runs the child destructor; otherwise resources leak.
40 Index

Abstraction shows only the essential features and hides the details. Example: you press the brake without knowing how the brake system works.

In C++ a class with at least one pure virtual function (= 0) is an abstract class. It cannot be instantiated; child classes must implement the function.

C++ 13 lines
class Payment {                       // abstract class
public:
    virtual void pay(double amount) = 0;   // pure virtual
};

class Bkash : public Payment {
public:
    void pay(double amount) override { cout << "Paid " << amount << " by bKash\n"; }
};

// Payment p;       // error: cannot create an abstract object
Payment *p = new Bkash();
p->pay(500);
41 Index
Abstract classInterface
Can have both abstract and normal methodsOnly method declarations (Java 8+ also allows default methods)
Can have fields / state and constructorsOnly constants, no constructor
A class extends only one abstract class (Java/C#)A class can implement many interfaces
Used for closely related classes (is-a)Used for a capability (can-do), e.g. Comparable

C++ has no interface keyword: a class with only pure virtual functions acts as an interface.

Java: one class, many interfaces Java 7 lines
interface Flyable { void fly(); }
interface Swimmable { void swim(); }

class Duck implements Flyable, Swimmable {
    public void fly()  { System.out.println("Duck flies"); }
    public void swim() { System.out.println("Duck swims"); }
}
42 Index
  • this points to the current object. Used when a parameter has the same name as a member, or to return the object itself.
  • static data member — one copy shared by every object, e.g. a counter of objects.
  • static member function — called with the class name, can use only static members (no this).
C++ 14 lines
class Student {
    string name;
    static int count;          // shared
public:
    Student(string name) {
        this->name = name;     // this-> separates member from parameter
        count++;
    }
    static int total() { return count; }
};
int Student::count = 0;        // define outside the class

Student a("A"), b("B");
cout << Student::total();      // 2
43 Index

A friend function is not a member but can access private members. It is often used for operator overloading such as <<.

C++ 15 lines
class Complex {
    int re, im;
public:
    Complex(int r = 0, int i = 0) : re(r), im(i) {}

    Complex operator+(const Complex &o) const {     // member operator
        return Complex(re + o.re, im + o.im);
    }
    friend ostream& operator<<(ostream &out, const Complex &c) {
        return out << c.re << " + " << c.im << "i";
    }
};

Complex a(2, 3), b(1, 4);
cout << a + b;    // 3 + 7i
44 Index
LetterPrincipleMeaning
SSingle ResponsibilityA class should have only one reason to change.
OOpen / ClosedOpen for extension, closed for modification (add new classes, do not edit old ones).
LLiskov SubstitutionA child object must work wherever the parent is expected.
IInterface SegregationMany small interfaces are better than one big one.
DDependency InversionDepend on abstractions (interfaces), not on concrete classes.
45 Index
  • Association — a general relationship: a Teacher teaches a Student.
  • Aggregation (has-a, weak) — the part can exist alone: a Department has Teachers; if the department closes, teachers still exist.
  • Composition (has-a, strong) — the part cannot exist without the whole: a House has Rooms; delete the house, the rooms are gone.
46 Index

A data structure is a way of organising and storing data so it can be used efficiently.

LinearNon-linear
Elements in a sequenceElements in a hierarchy or network
Array, Linked List, Stack, QueueTree, Graph, Heap

Static (fixed size, e.g. array) vs dynamic (grows at run time, e.g. linked list, vector).

Time complexity cheat sheet

StructureAccessSearchInsertDelete
ArrayO(1)O(n)O(n)O(n)
Linked ListO(n)O(n)O(1) at headO(1) at head
Stack / QueueO(n)O(n)O(1)O(1)
Hash Table—O(1) avgO(1) avgO(1) avg
BST (balanced)O(log n)O(log n)O(log n)O(log n)
Heaptop O(1)O(n)O(log n)O(log n)
47 Index

An array stores elements of the same type in contiguous memory. Access by index is O(1); inserting or deleting in the middle needs shifting, O(n).

Index-based access is O(1) because the address can be calculated

Index-based access is O(1) because the address can be calculated

C++ 9 lines
int arr[5] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);   // length = 5

// insert 99 at index 2 (shift right)
int a[6] = {10, 20, 30, 40, 50};
for (int i = 5; i > 2; i--) a[i] = a[i - 1];
a[2] = 99;                              // 10 20 99 30 40 50

int m[2][3] = {{1, 2, 3}, {4, 5, 6}};  // 2D array
48 Index

A linked list is a chain of nodes; each node holds data and a pointer to the next node. Size can grow at run time and insert/delete at the head is O(1), but there is no random access.

head → 10 → 20 → 30 → 40 → NULL

head → 10 → 20 → 30 → 40 → NULL

C++ 27 lines
struct Node {
    int data;
    Node *next;
    Node(int d) : data(d), next(nullptr) {}
};

void insertHead(Node *&head, int x) {
    Node *n = new Node(x);
    n->next = head;
    head = n;
}

void print(Node *head) {
    for (Node *cur = head; cur; cur = cur->next)
        cout << cur->data << " ";
}

Node* reverse(Node *head) {          // very common interview question
    Node *prev = nullptr;
    while (head) {
        Node *next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }
    return prev;
}
  • Singly — next pointer only.
  • Doubly — next and prev pointers.
  • Circular — last node points back to the first.

Q & A

  1. Array vs linked list?
    Array: contiguous, O(1) index access, fixed size, costly insert/delete. Linked list: scattered nodes, O(n) access, dynamic size, O(1) insert/delete when you already have the node.
  2. How to find the middle of a linked list?
    Slow and fast pointers: slow moves 1 step, fast moves 2 steps. When fast reaches the end, slow is at the middle.
  3. How to detect a cycle?
    Floyd's algorithm: the same slow/fast pointers meet inside the loop if there is a cycle.
49 Index

A stack is LIFO (Last In, First Out). Operations: push, pop, top/peek, isEmpty, all O(1).

Uses: function call stack, undo, browser back button, expression evaluation, balanced parentheses, DFS.

Stack removes the newest item, queue removes the oldest

Stack removes the newest item, queue removes the oldest

Balanced parentheses C++ 14 lines
bool isBalanced(string s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '{' || c == '[') st.push(c);
        else {
            if (st.empty()) return false;
            char t = st.top(); st.pop();
            if ((c == ')' && t != '(') || (c == '}' && t != '{') || (c == ']' && t != '['))
                return false;
        }
    }
    return st.empty();
}
// isBalanced("{[()]}") → true,  isBalanced("(]") → false
Stack using an array C++ 3 lines
int st[100], top = -1;
void push(int x) { if (top < 99) st[++top] = x; }      // overflow check
int  pop()       { return top >= 0 ? st[top--] : -1; } // underflow check
50 Index

A queue is FIFO (First In, First Out): insert at the rear (enqueue), remove from the front (dequeue).

  • Circular queue — reuses empty slots at the start: rear = (rear + 1) % size.
  • Deque — insert/remove at both ends.
  • Priority queue — highest priority leaves first (usually a heap).

Uses: CPU scheduling, printer queue, BFS, buffering.

C++ 5 lines
queue<int> q;
q.push(10); q.push(20); q.push(30);
cout << q.front();   // 10
q.pop();             // removes 10
cout << q.size();    // 2