Back In the print window choose "Save as PDF" as the destination
NOTE.CS

All Topics

161 topics · 28 Nov 2026
1

Largest of Three Numbers

↑ Index
Problem Solving
Solution 1: if - else if · C++
if(a >= b && a >= c)
    cout << a;
else if(b >= a && b >= c)
    cout << b;
else
    cout << c;
Solution 2: Nested max() · C++
cout << max(a, max(b, c));
Solution 3: max() with initializer list (shortest) · C++
cout << max({a, b, c});

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

2

Sum of 1 to N

↑ Index
Problem Solving

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

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

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

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

Swap Two Numbers

↑ Index
Problem Solving

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

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

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

4

Prime Number ★★★★★

↑ Index
Problem Solving

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

GCD / HCF ★★★★★

↑ Index
Problem Solving

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++
int a = 12, b = 18;
while(b != 0){
    int temp = b;
    b = a % b;
    a = temp;
}
cout << a; // 6
Solution 2: Recursive · C++
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++
cout << gcd(12, 18);   // <numeric>, C++17
cout << __gcd(12, 18);

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

Solution 4: GCD of multiple numbers ★★★★★ · C++
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

LCM

↑ Index
Problem Solving

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

Armstrong Number

↑ Index
Problem Solving

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

Perfect Number

↑ Index
Problem Solving

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

Anagram Check

↑ Index
Problem Solving

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

Even or Odd

↑ Index
Problem Solving

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

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

Leap Year

↑ Index
Problem Solving

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++
int y = 2024;
if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
    cout << "Leap Year";
else
    cout << "Not Leap Year";
12

Factorial

↑ Index
Problem Solving

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

Example: 5! = 120

Solution 1: Loop O(n) · C++
int n = 5;
long long fact = 1;
for(int i = 1; i <= n; i++)
    fact *= i;
cout << fact; // 120
Solution 2: Recursion · C++
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

Fibonacci Series ★★★★★

↑ Index
Problem Solving

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++
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++
int fib(int n){
    if(n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}
Solution 3: Memoization O(n) · C++
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

Reverse a Number

↑ Index
Problem Solving

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

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

Palindrome Number

↑ Index
Problem Solving

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

Solution 1: Reverse and compare · C++
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++
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

Reverse a String

↑ Index
Problem Solving
Solution 1: std::reverse · C++
string s = "hello";
reverse(s.begin(), s.end());
cout << s; // olleh
Solution 2: Two pointers · C++
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

Count Vowels

↑ Index
Problem Solving
C++
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
18

Sum of Digits

↑ Index
Problem Solving
C++
int n = 1234, sum = 0;
while(n > 0){
    sum += n % 10;
    n /= 10;
}
cout << sum; // 10
19

Decimal to Binary

↑ Index
Problem Solving

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

Solution 1: Repeated division · C++
int n = 13;
string bin = "";
while(n > 0){
    bin = char('0' + n % 2) + bin;
    n /= 2;
}
cout << bin; // 1101
Solution 2: bitset · C++
#include <bitset>
cout << bitset<8>(13); // 00001101
Binary to Decimal · C++
string b = "1101";
int dec = 0;
for(char c : b)
    dec = dec * 2 + (c - '0');
cout << dec; // 13
20

Second Largest Element

↑ Index
Problem Solving
Single pass O(n) · C++
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

Remove Duplicates from Array

↑ Index
Problem Solving
Solution 1: sort + unique · C++
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++
set<int> s(v.begin(), v.end()); // keeps one of each, sorted
22

Structure of a C++ Program

↑ Index
C++

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

Data Types and Sizes

↑ Index
C++
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++
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

Pointers ★★★★★

↑ Index
C++

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

Reference vs Pointer

↑ Index
C++

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

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

Call by Value vs Call by Reference ★★★★★

↑ Index
C++

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

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

Function Overloading

↑ Index
C++

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

Dynamic Memory (new / delete)

↑ Index
C++

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

STL: vector, map, set ★★★★★

↑ Index
C++

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

vector (dynamic array) · C++
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++
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++
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

String Functions

↑ Index
C++
C++
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

const, static and inline

↑ Index
C++
  • 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++
void counter() {
    static int count = 0;   // initialised only once
    count++;
    cout << count << " ";
}
// counter(); counter(); counter();  →  1 2 3
32

Templates

↑ Index
C++

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

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

Exception Handling

↑ Index
C++

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

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

OOP, Class and Object ★★★★★

↑ Index
OOP

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

Constructor and Destructor ★★★★★

↑ Index
OOP

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

Encapsulation ★★★★★

↑ Index
OOP

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

Access Specifiers

↑ Index
OOP
SpecifierSame classChild classOutside
public✔✔✔
protected✔✔✘
private✔✘✘

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

38

Inheritance ★★★★★

↑ Index
OOP

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

Polymorphism ★★★★★

↑ Index
OOP

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

Abstraction and Abstract Class

↑ Index
OOP

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

Interface vs Abstract Class

↑ Index
OOP
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
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

this Pointer and Static Members

↑ Index
OOP
  • 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++
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

Friend Function and Operator Overloading

↑ Index
OOP

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

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

SOLID Principles

↑ Index
OOP
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

Association, Aggregation, Composition

↑ Index
OOP
  • 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

What is a Data Structure

↑ Index
Data Structure

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

Array

↑ Index
Data Structure

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

Linked List ★★★★★

↑ Index
Data Structure

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

Stack

↑ Index
Data Structure

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

Queue

↑ Index
Data Structure

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++
queue<int> q;
q.push(10); q.push(20); q.push(30);
cout << q.front();   // 10
q.pop();             // removes 10
cout << q.size();    // 2
51

Hash Table

↑ Index
Data Structure

A hash table maps keys to values using a hash function that turns a key into an array index. Two keys with the same index cause a collision.

  • Chaining — each slot keeps a list of entries.
  • Open addressing — find another free slot (linear probing, quadratic probing, double hashing).
  • Load factor = items / slots; when it gets high the table is resized (rehashing).

Collision handled by chaining

Collision handled by chaining

Counting frequency with a hash map · C++
unordered_map<string, int> freq;
for (string w : {"a", "b", "a", "c", "a"})
    freq[w]++;
cout << freq["a"];   // 3
52

Binary Tree and Traversals ★★★★★

↑ Index
Data Structure

A binary tree is a tree where each node has at most two children. Terms: root, leaf, parent, child, height, depth, level.

  • Full — every node has 0 or 2 children.
  • Complete — all levels full except possibly the last, filled from the left.
  • Perfect — all internal nodes have 2 children and all leaves are at the same level (2h+1 − 1 nodes).
  • Balanced — height is O(log n), e.g. AVL, Red-Black tree.
C++
struct Node {
    int val;
    Node *left, *right;
    Node(int v) : val(v), left(nullptr), right(nullptr) {}
};

void inorder(Node *r)   { if (!r) return; inorder(r->left); cout << r->val << " "; inorder(r->right); }   // L N R
void preorder(Node *r)  { if (!r) return; cout << r->val << " "; preorder(r->left); preorder(r->right); } // N L R
void postorder(Node *r) { if (!r) return; postorder(r->left); postorder(r->right); cout << r->val << " "; } // L R N

int height(Node *r) { return r ? 1 + max(height(r->left), height(r->right)) : 0; }

void levelOrder(Node *root) {          // BFS
    queue<Node*> q;
    if (root) q.push(root);
    while (!q.empty()) {
        Node *cur = q.front(); q.pop();
        cout << cur->val << " ";
        if (cur->left) q.push(cur->left);
        if (cur->right) q.push(cur->right);
    }
}
53

Binary Search Tree (BST) ★★★★★

↑ Index
Data Structure

In a BST every left subtree value is smaller and every right subtree value is larger than the node. Inorder traversal gives sorted output. Search/insert/delete are O(log n) when balanced, O(n) when skewed.

A balanced BST with 7 nodes

A balanced BST with 7 nodes

C++
Node* insert(Node *root, int x) {
    if (!root) return new Node(x);
    if (x < root->val) root->left = insert(root->left, x);
    else               root->right = insert(root->right, x);
    return root;
}

bool search(Node *root, int x) {
    while (root) {
        if (x == root->val) return true;
        root = (x < root->val) ? root->left : root->right;
    }
    return false;
}

Delete: leaf → remove; one child → replace with the child; two children → replace with the inorder successor (smallest in the right subtree), then delete that successor.

54

Heap and Priority Queue

↑ Index
Data Structure

A heap is a complete binary tree stored in an array. Max-heap: parent ≥ children (largest on top). Min-heap: parent ≤ children.

Insert and remove-top are O(log n), reading the top is O(1). Building a heap from n items is O(n). Used in heap sort, Dijkstra, scheduling, top-K problems.

The same heap as a tree and as an array

The same heap as a tree and as an array

C++
priority_queue<int> maxHeap;                              // largest on top
priority_queue<int, vector<int>, greater<int>> minHeap;   // smallest on top

for (int x : {5, 1, 8, 3}) { maxHeap.push(x); minHeap.push(x); }
cout << maxHeap.top();   // 8
cout << minHeap.top();   // 1
55

Graph

↑ Index
Data Structure

A graph G = (V, E) is a set of vertices connected by edges. Types: directed / undirected, weighted / unweighted, cyclic / acyclic (DAG), connected / disconnected.

The same graph stored as an adjacency list

The same graph stored as an adjacency list

Adjacency list · C++
int V = 5;
vector<vector<int>> adj(V);
auto addEdge = [&](int u, int v) {
    adj[u].push_back(v);
    adj[v].push_back(u);   // remove this line for a directed graph
};
addEdge(0, 1); addEdge(0, 2); addEdge(1, 3);
addEdge(2, 3); addEdge(1, 4); addEdge(3, 4);

BFS and DFS traversal are in the Algorithm category.

56

Trie ★★☆☆☆

↑ Index
Data Structure

A trie (prefix tree) stores strings character by character. Insert and search take O(length of word). Used for autocomplete, spell check and prefix search.

C++
struct TrieNode {
    TrieNode *child[26] = {};
    bool isEnd = false;
};

void insert(TrieNode *root, const string &w) {
    for (char c : w) {
        int i = c - 'a';
        if (!root->child[i]) root->child[i] = new TrieNode();
        root = root->child[i];
    }
    root->isEnd = true;
}

bool search(TrieNode *root, const string &w) {
    for (char c : w) {
        root = root->child[c - 'a'];
        if (!root) return false;
    }
    return root->isEnd;
}
57

Time and Space Complexity (Big-O) ★★★★★

↑ Index
Algorithm

Time complexity is how the running time grows with input size n. Space complexity is how much extra memory is used. We usually give the worst case with Big-O.

  • Big-O (O) — upper bound (worst case).
  • Big-Omega (Ω) — lower bound (best case).
  • Big-Theta (Θ) — tight bound (both).

O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ)

O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ)

Recognising complexity from code · C++
x = a[5];                              // O(1)
for (int i = 1; i < n; i *= 2) {}      // O(log n)
for (int i = 0; i < n; i++) {}         // O(n)
for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) {}     // O(n^2)
sort(a, a + n);                        // O(n log n)

Rule of thumb: about 108 simple operations run in ~1 second. For n = 105, O(n²) is too slow but O(n log n) is fine.

58

Recursion

↑ Index
Algorithm

A function that calls itself. Every recursion needs a base case (stop condition) and a recursive case that moves toward it. Each call uses stack memory; without a base case you get a stack overflow.

C++
int power(int a, int b) {        // a^b
    if (b == 0) return 1;        // base case
    return a * power(a, b - 1);  // recursive case
}

long long fastPower(long long a, int b) {   // O(log b)
    if (b == 0) return 1;
    long long half = fastPower(a, b / 2);
    return (b % 2) ? half * half * a : half * half;
}

void hanoi(int n, char from, char to, char via) {   // Tower of Hanoi: 2^n - 1 moves
    if (n == 0) return;
    hanoi(n - 1, from, via, to);
    cout << "Move disk " << n << " " << from << " -> " << to << "\n";
    hanoi(n - 1, via, to, from);
}
59

Algorithm Design Techniques

↑ Index
Algorithm
TechniqueIdeaExamples
Brute forceTry every possibilityLinear search, all pairs
Divide and ConquerSplit into independent parts, solve, combineMerge sort, quick sort, binary search
GreedyTake the best choice at each stepActivity selection, Kruskal, Prim, Dijkstra, Huffman
Dynamic ProgrammingOverlapping subproblems, store answersFibonacci, knapsack, LCS, coin change
BacktrackingBuild a solution, undo when it failsN-Queens, Sudoku, subsets, permutations
Two pointers / Sliding windowMove indices over an array instead of nested loopsPair sum, longest substring

Q & A

  1. Greedy vs DP?
    Greedy makes one local choice and never looks back, so it is fast but only correct for some problems. DP tries all choices of subproblems and reuses stored answers, so it is always correct when the problem has optimal substructure.
60

BFS and DFS ★★★★★

↑ Index
Algorithm

BFS (Breadth First Search) visits level by level with a queue; it finds the shortest path in an unweighted graph. DFS (Depth First Search) goes as deep as possible with a stack / recursion; used for cycle detection, topological sort, connected components. Both are O(V + E).

BFS spreads out, DFS dives down one branch first

BFS spreads out, DFS dives down one branch first

BFS · C++
void bfs(int start, vector<vector<int>> &adj) {
    vector<bool> visited(adj.size(), false);
    queue<int> q;
    visited[start] = true;
    q.push(start);
    while (!q.empty()) {
        int u = q.front(); q.pop();
        cout << u << " ";
        for (int v : adj[u])
            if (!visited[v]) { visited[v] = true; q.push(v); }
    }
}
DFS (recursive) · C++
void dfs(int u, vector<vector<int>> &adj, vector<bool> &visited) {
    visited[u] = true;
    cout << u << " ";
    for (int v : adj[u])
        if (!visited[v]) dfs(v, adj, visited);
}
61

Dijkstra's Shortest Path

↑ Index
Algorithm

Finds the shortest distance from one source to every node in a graph with non-negative weights. Greedy: always expand the closest unvisited node, using a min-heap. Complexity O((V + E) log V).

For negative weights use Bellman-Ford O(VE); for all pairs use Floyd-Warshall O(V³).

C++
vector<int> dijkstra(int src, vector<vector<pair<int,int>>> &adj) {   // adj[u] = {v, w}
    vector<int> dist(adj.size(), INT_MAX);
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;  // {dist, node}
    dist[src] = 0;
    pq.push({0, src});
    while (!pq.empty()) {
        auto [d, u] = pq.top(); pq.pop();
        if (d > dist[u]) continue;           // outdated entry
        for (auto [v, w] : adj[u]) {
            if (dist[u] + w < dist[v]) {     // relax the edge
                dist[v] = dist[u] + w;
                pq.push({dist[v], v});
            }
        }
    }
    return dist;
}
62

Minimum Spanning Tree (Kruskal, Prim)

↑ Index
Algorithm

A spanning tree connects all V vertices with V − 1 edges and no cycle. The MST has the smallest total weight.

  • Kruskal — sort edges by weight, add an edge if it does not form a cycle (checked with Disjoint Set Union). O(E log E).
  • Prim — start from a node, repeatedly add the cheapest edge leaving the tree (min-heap). O(E log V).
Kruskal with DSU · C++
int parent[1000];
int find(int x) { return parent[x] == x ? x : parent[x] = find(parent[x]); }  // path compression
bool unite(int a, int b) {
    a = find(a); b = find(b);
    if (a == b) return false;    // same set → would make a cycle
    parent[a] = b;
    return true;
}

// edges = {w, u, v}
int kruskal(int n, vector<array<int,3>> edges) {
    for (int i = 0; i < n; i++) parent[i] = i;
    sort(edges.begin(), edges.end());
    int total = 0;
    for (auto [w, u, v] : edges)
        if (unite(u, v)) total += w;
    return total;
}
63

Dynamic Programming ★★★★★

↑ Index
Algorithm

DP solves a problem by breaking it into overlapping subproblems and storing each answer so it is computed only once. The problem must have optimal substructure.

  • Memoization (top-down) — recursion + cache.
  • Tabulation (bottom-up) — fill a table with loops.

Plain recursion recomputes f(3) and f(2) many times

Plain recursion recomputes f(3) and f(2) many times

0/1 Knapsack O(n × W) · C++
int knapsack(vector<int> &wt, vector<int> &val, int W) {
    int n = wt.size();
    vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));
    for (int i = 1; i <= n; i++)
        for (int w = 0; w <= W; w++) {
            dp[i][w] = dp[i - 1][w];                                   // skip item
            if (wt[i - 1] <= w)
                dp[i][w] = max(dp[i][w], val[i - 1] + dp[i - 1][w - wt[i - 1]]);  // take item
        }
    return dp[n][W];
}
Longest Common Subsequence · C++
int lcs(string a, string b) {
    int n = a.size(), m = b.size();
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            dp[i][j] = (a[i-1] == b[j-1]) ? dp[i-1][j-1] + 1 : max(dp[i-1][j], dp[i][j-1]);
    return dp[n][m];     // lcs("ABCBDAB", "BDCABA") = 4
}
Coin change · C++
int coinChange(vector<int> &coins, int amount) {      // minimum coins
    vector<int> dp(amount + 1, INT_MAX);
    dp[0] = 0;
    for (int a = 1; a <= amount; a++)
        for (int c : coins)
            if (c <= a && dp[a - c] != INT_MAX)
                dp[a] = min(dp[a], dp[a - c] + 1);
    return dp[amount] == INT_MAX ? -1 : dp[amount];
}
64

Two Pointers and Sliding Window

↑ Index
Algorithm

Replace a nested O(n²) loop with two indices that move through the array in O(n).

Two pointers · C++
// sorted array: is there a pair with sum = target?
bool pairSum(vector<int> &a, int target) {
    int i = 0, j = a.size() - 1;
    while (i < j) {
        int s = a[i] + a[j];
        if (s == target) return true;
        if (s < target) i++; else j--;
    }
    return false;
}
Sliding window · C++
// maximum sum of any k consecutive elements
int maxWindow(vector<int> &a, int k) {
    int sum = 0;
    for (int i = 0; i < k; i++) sum += a[i];
    int best = sum;
    for (int i = k; i < a.size(); i++) {
        sum += a[i] - a[i - k];   // slide: add new, remove old
        best = max(best, sum);
    }
    return best;
}
Kadane's algorithm (maximum subarray) · C++
int maxSubArray(vector<int> &a) {
    int cur = a[0], best = a[0];
    for (int i = 1; i < a.size(); i++) {
        cur = max(a[i], cur + a[i]);
        best = max(best, cur);
    }
    return best;   // {-2,1,-3,4,-1,2,1,-5,4} → 6
}
65

Backtracking

↑ Index
Algorithm

Build a solution step by step; when a step cannot lead to a valid answer, undo it and try the next option.

All subsets (2^n) · C++
void subsets(vector<int> &a, int i, vector<int> &cur) {
    if (i == a.size()) {
        for (int x : cur) cout << x << " ";
        cout << "\n";
        return;
    }
    subsets(a, i + 1, cur);        // skip a[i]
    cur.push_back(a[i]);           // take a[i]
    subsets(a, i + 1, cur);
    cur.pop_back();                // undo
}
All permutations · C++
string s = "abc";
sort(s.begin(), s.end());
do cout << s << " "; while (next_permutation(s.begin(), s.end()));
// abc acb bac bca cab cba
66

Linear Search

↑ Index
Algorithm › Search

Check each element one by one. Works on unsorted data. Time O(n), space O(1).

C++
int linearSearch(int arr[], int n, int key) {
    for (int i = 0; i < n; i++)
        if (arr[i] == key) return i;   // found: return index
    return -1;                         // not found
}
67

Binary Search ★★★★★

↑ Index
Algorithm › Search

Works only on a sorted array. Compare with the middle element and discard half of the range each time. Time O(log n), space O(1) (iterative).

Searching 23 takes only 3 steps for 10 elements

Searching 23 takes only 3 steps for 10 elements

Iterative · C++
int binarySearch(int arr[], int n, int key) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;   // avoids overflow of (low + high)
        if (arr[mid] == key) return mid;
        if (arr[mid] < key) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}
Recursive (O(log n) stack space) · C++
int binarySearch(int arr[], int low, int high, int key) {
    if (low > high) return -1;
    int mid = low + (high - low) / 2;
    if (arr[mid] == key) return mid;
    if (arr[mid] < key) return binarySearch(arr, mid + 1, high, key);
    return binarySearch(arr, low, mid - 1, key);
}

Q & A

  1. Why mid = low + (high - low) / 2?
    low + high can overflow int when both are large; this form gives the same value safely.
68

lower_bound and upper_bound

↑ Index
Algorithm › Search

STL binary search helpers on sorted ranges. lower_bound → first element ≥ x. upper_bound → first element > x.

C++
vector<int> v = {1, 2, 4, 4, 4, 7, 9};
auto lo = lower_bound(v.begin(), v.end(), 4) - v.begin();   // 2
auto hi = upper_bound(v.begin(), v.end(), 4) - v.begin();   // 5
cout << hi - lo;                                            // 3 = count of 4
cout << binary_search(v.begin(), v.end(), 7);               // 1 (true)
69

Search Algorithms Comparison ★★☆☆☆

↑ Index
Algorithm › Search
AlgorithmNeeds sorted dataBestAverage / Worst
Linear SearchNoO(1)O(n)
Binary SearchYesO(1)O(log n)
Jump SearchYesO(1)O(√n)
Interpolation SearchYes (uniform values)O(1)O(log log n) / O(n)
Hash lookupNoO(1)O(1) / O(n)
70

Sorting Algorithms Comparison ★★★★★

↑ Index
Algorithm › Sort
AlgorithmBestAverageWorstSpaceStable
Bubble SortO(n)O(n²)O(n²)O(1)Yes
Selection SortO(n²)O(n²)O(n²)O(1)No
Insertion SortO(n)O(n²)O(n²)O(1)Yes
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick SortO(n log n)O(n log n)O(n²)O(log n)No
Heap SortO(n log n)O(n log n)O(n log n)O(1)No
Counting SortO(n + k)O(n + k)O(n + k)O(k)Yes

Stable = equal elements keep their original order. In-place = O(1) extra memory. C++ sort() uses Introsort (quick + heap + insertion), O(n log n).

71

Bubble Sort

↑ Index
Algorithm › Sort

Repeatedly swap adjacent elements that are in the wrong order; after each pass the largest element "bubbles" to the end. Stop early if a pass makes no swap.

C++
void bubbleSort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - 1 - i; j++) {
            if (a[j] > a[j + 1]) {
                swap(a[j], a[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break;   // already sorted → O(n) best case
    }
}
72

Selection Sort

↑ Index
Algorithm › Sort

Find the minimum of the unsorted part and put it at the front. Always O(n²) comparisons but at most n − 1 swaps.

C++
void selectionSort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++)
            if (a[j] < a[minIdx]) minIdx = j;
        swap(a[i], a[minIdx]);
    }
}
73

Insertion Sort

↑ Index
Algorithm › Sort

Take the next element and insert it into its correct place in the already-sorted left part, like sorting playing cards. Very fast for small or nearly-sorted arrays.

C++
void insertionSort(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];   // shift right
            j--;
        }
        a[j + 1] = key;
    }
}
74

Merge Sort ★★★★★

↑ Index
Algorithm › Sort

Divide and conquer: split the array into halves, sort each half recursively, then merge the two sorted halves. Always O(n log n), stable, needs O(n) extra space.

Split down to single elements, then merge back in order

Split down to single elements, then merge back in order

C++
void merge(vector<int> &a, int l, int m, int r) {
    vector<int> tmp;
    int i = l, j = m + 1;
    while (i <= m && j <= r)
        tmp.push_back(a[i] <= a[j] ? a[i++] : a[j++]);
    while (i <= m) tmp.push_back(a[i++]);
    while (j <= r) tmp.push_back(a[j++]);
    for (int k = 0; k < tmp.size(); k++) a[l + k] = tmp[k];
}

void mergeSort(vector<int> &a, int l, int r) {
    if (l >= r) return;
    int m = l + (r - l) / 2;
    mergeSort(a, l, m);
    mergeSort(a, m + 1, r);
    merge(a, l, m, r);
}

Recurrence: T(n) = 2T(n/2) + O(n) → O(n log n).

75

Quick Sort ★★★★★

↑ Index
Algorithm › Sort

Pick a pivot, partition the array so smaller elements are on the left and larger on the right, then sort both sides recursively. Average O(n log n), in-place. Worst case O(n²) when the pivot is always the smallest/largest (e.g. already sorted input with last-element pivot); a random pivot avoids it.

After one partition the pivot is at its final index

After one partition the pivot is at its final index

C++
int partition(vector<int> &a, int low, int high) {   // Lomuto
    int pivot = a[high];
    int i = low - 1;
    for (int j = low; j < high; j++)
        if (a[j] < pivot) swap(a[++i], a[j]);
    swap(a[i + 1], a[high]);
    return i + 1;
}

void quickSort(vector<int> &a, int low, int high) {
    if (low < high) {
        int p = partition(a, low, high);
        quickSort(a, low, p - 1);
        quickSort(a, p + 1, high);
    }
}

Q & A

  1. Merge sort vs quick sort?
    Merge sort: always O(n log n), stable, needs O(n) extra memory, good for linked lists and external sorting. Quick sort: in-place and usually faster in practice, but O(n²) in the worst case and not stable.
76

Heap Sort

↑ Index
Algorithm › Sort

Build a max-heap, then repeatedly move the root (largest) to the end and re-heapify the rest. O(n log n) always, in-place, not stable.

C++
void heapify(vector<int> &a, int n, int i) {
    int largest = i, l = 2 * i + 1, r = 2 * i + 2;
    if (l < n && a[l] > a[largest]) largest = l;
    if (r < n && a[r] > a[largest]) largest = r;
    if (largest != i) {
        swap(a[i], a[largest]);
        heapify(a, n, largest);
    }
}

void heapSort(vector<int> &a) {
    int n = a.size();
    for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i);   // build heap O(n)
    for (int i = n - 1; i > 0; i--) {
        swap(a[0], a[i]);          // largest to the end
        heapify(a, i, 0);
    }
}
77

Counting Sort

↑ Index
Algorithm › Sort

Non-comparison sort for small integer ranges: count each value, then write them back in order. O(n + k) where k is the value range.

C++
void countingSort(vector<int> &a, int maxVal) {
    vector<int> cnt(maxVal + 1, 0);
    for (int x : a) cnt[x]++;
    int idx = 0;
    for (int v = 0; v <= maxVal; v++)
        while (cnt[v]--) a[idx++] = v;
}
78

C# and .NET Basics

↑ Index
C#

C# is a modern, object-oriented, type-safe language by Microsoft that runs on .NET. Used for web (ASP.NET Core), desktop, games (Unity), cloud and mobile (MAUI).

Source → IL → JIT → native code

Source → IL → JIT → native code

Structure of a C# program · C#
using System;

namespace HelloApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter your name: ");
            string name = Console.ReadLine();
            Console.WriteLine($"Hello, {name}!");   // string interpolation
        }
    }
}

Q & A

  1. What is the CLR?
    Common Language Runtime: the .NET virtual machine that JIT-compiles IL to machine code and manages memory with the garbage collector.
  2. What is managed code?
    Code that runs under the CLR, so memory, security and exceptions are managed by the runtime.
79

Value Types vs Reference Types ★★★★★

↑ Index
C#
Value typeReference type
Stores the data itselfStores a reference (address) to the data
int, double, bool, char, struct, enumclass, string, array, interface, delegate
Usually on the stackObject lives on the heap
Assignment copies the valueAssignment copies the reference (both point to the same object)

Copying a value type vs copying a reference

Copying a value type vs copying a reference

C#
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a);   // 10

var p1 = new Person { Name = "Rahim" };
var p2 = p1;
p2.Name = "Karim";
Console.WriteLine(p1.Name);   // Karim

Boxing = value type → object (heap). Unboxing = object → value type. string is a reference type but immutable.

80

Classes, Properties and Constructors

↑ Index
C#
C#
public class Student
{
    public string Name { get; set; }            // auto-property
    private int _age;
    public int Age                              // property with validation
    {
        get => _age;
        set => _age = value >= 0 ? value : 0;
    }
    public static int Count { get; private set; }

    public Student(string name, int age)        // constructor
    {
        Name = name;
        Age = age;
        Count++;
    }

    public override string ToString() => $"{Name} ({Age})";
}

var s = new Student("Rahim", 21);
Console.WriteLine(s);                 // Rahim (21)
Console.WriteLine(Student.Count);     // 1
  • Access modifiers: public, private (default for members), protected, internal (same assembly), protected internal.
  • readonly fields can be set only in the constructor; const is a compile-time constant.
  • struct is a value type; record gives value-based equality for data classes.
81

Inheritance, Interface and Abstract Class in C# ★★★★★

↑ Index
C#

C# supports single class inheritance but a class can implement many interfaces. Use virtual + override for polymorphism, abstract for methods without a body, sealed to stop further inheritance.

C#
public interface IShape { double Area(); }

public abstract class Shape : IShape
{
    public abstract double Area();
    public virtual string Describe() => $"Area = {Area():F2}";
}

public class Circle : Shape
{
    public double R { get; }
    public Circle(double r) => R = r;
    public override double Area() => Math.PI * R * R;
}

public sealed class Square : Shape
{
    public double A { get; }
    public Square(double a) => A = a;
    public override double Area() => A * A;
    public override string Describe() => "Square, " + base.Describe();
}

List<Shape> shapes = new() { new Circle(2), new Square(3) };
foreach (var s in shapes) Console.WriteLine(s.Describe());
82

Collections and Generics

↑ Index
C#
CollectionUse
List<T>Dynamic array
Dictionary<K,V>Key → value (hash table)
HashSet<T>Unique items
Queue<T> / Stack<T>FIFO / LIFO
Array (T[])Fixed size
C#
var nums = new List<int> { 5, 2, 8 };
nums.Add(1);
nums.Sort();                       // 1 2 5 8

var ages = new Dictionary<string, int>();
ages["Rahim"] = 25;
if (ages.TryGetValue("Rahim", out int age))
    Console.WriteLine(age);

// generic method
static T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) > 0 ? a : b;
83

LINQ

↑ Index
C#

LINQ (Language Integrated Query) lets you filter, sort and transform collections (and databases through Entity Framework) with SQL-like methods.

C#
var students = new List<Student> {
    new("Rahim", 21), new("Karim", 19), new("Sumi", 23)
};

var adults = students
    .Where(s => s.Age >= 20)
    .OrderBy(s => s.Name)
    .Select(s => s.Name)
    .ToList();                         // Rahim, Sumi

double avg = students.Average(s => s.Age);
var first = students.FirstOrDefault(s => s.Name.StartsWith("K"));
var groups = students.GroupBy(s => s.Age >= 20);

// query syntax
var q = from s in students where s.Age > 20 select s.Name;

LINQ uses deferred execution: the query runs only when you enumerate it (foreach, ToList, Count ...).

84

Exception Handling in C#

↑ Index
C#
C#
try
{
    int x = int.Parse("abc");
}
catch (FormatException ex)
{
    Console.WriteLine("Invalid number: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("Other error: " + ex.Message);
}
finally
{
    Console.WriteLine("Always runs");   // cleanup
}

// using disposes the object automatically (calls Dispose)
using var reader = new StreamReader("data.txt");

Catch specific exceptions first. Use throw; (not throw ex;) to re-throw and keep the stack trace.

85

Delegates, Events and Lambdas

↑ Index
C#

A delegate is a type-safe function pointer. Func<> returns a value, Action<> returns void, Predicate<T> returns bool. An event is a delegate that others can subscribe to.

C#
Func<int, int, int> add = (a, b) => a + b;
Action<string> log = msg => Console.WriteLine(msg);
log(add(2, 3).ToString());     // 5

public class Button
{
    public event Action? Clicked;
    public void Click() => Clicked?.Invoke();
}

var btn = new Button();
btn.Clicked += () => Console.WriteLine("Button clicked");
btn.Click();
86

async and await

↑ Index
C#

async/await runs slow I/O work (web calls, files, database) without blocking the thread. An async method returns Task or Task<T>.

C#
public async Task<string> DownloadAsync(string url)
{
    using var client = new HttpClient();
    string html = await client.GetStringAsync(url);   // thread is free while waiting
    return html;
}

// run several tasks at the same time
var t1 = DownloadAsync("https://a.com");
var t2 = DownloadAsync("https://b.com");
string[] pages = await Task.WhenAll(t1, t2);

Avoid .Result / .Wait() on tasks: they block and can deadlock.

87

Garbage Collection in .NET

↑ Index
C#

The GC frees heap objects that are no longer referenced. It is generational: Gen 0 (new, collected often), Gen 1, Gen 2 (long-lived). Large objects (> 85 KB) go to the Large Object Heap.

Unmanaged resources (files, sockets, DB connections) are not handled by the GC: implement IDisposable and use using.

88

C# Keywords Quick Reference

↑ Index
C#
KeywordMeaning
varType inferred at compile time (still strongly typed)
dynamicType checked at run time
ref / out / inPass by reference; out must be assigned inside; in is read-only
staticBelongs to the class, not an object
sealedClass cannot be inherited
partialClass split across files
?? / ?.Null-coalescing / null-conditional operators
is / asType check / safe cast (null if it fails)
C#
string? name = null;
Console.WriteLine(name?.Length ?? 0);   // 0

void Divide(int a, int b, out int q, out int r) { q = a / b; r = a % b; }
Divide(17, 5, out int q, out int r);    // q = 3, r = 2
89

JDK, JRE and JVM ★★★★★

↑ Index
Java

Java source code is compiled by javac into bytecode (.class). The JVM runs that bytecode on any operating system, which makes Java platform independent.

JDK contains the JRE, the JRE contains the JVM

JDK contains the JRE, the JRE contains the JVM

Structure of a Java program · Java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}
// javac Hello.java   → Hello.class
// java Hello         → runs on the JVM

Q & A

  1. Why is main public static void?
    public: the JVM must call it from outside. static: it runs without creating an object. void: it returns nothing to the JVM.
  2. Is Java fully object oriented?
    Not 100%, because it has primitive types (int, char, ...) and static members.
90

Java Data Types and Wrapper Classes

↑ Index
Java
PrimitiveSizeWrapper
byte1 byteByte
short2 bytesShort
int4 bytesInteger
long8 bytesLong
float4 bytesFloat
double8 bytesDouble
char2 bytes (Unicode)Character
booleanJVM specificBoolean

Autoboxing converts a primitive to its wrapper automatically (int → Integer); unboxing is the reverse. Collections can only store objects, so they use wrappers.

Java
Integer a = 5;              // autoboxing
int b = a;                  // unboxing
int n = Integer.parseInt("42");
String s = String.valueOf(99);

Integer x = 127, y = 127;
System.out.println(x == y);          // true  (cached -128..127)
Integer p = 128, q = 128;
System.out.println(p == q);          // false (different objects)
System.out.println(p.equals(q));     // true
91

String, StringBuilder and StringBuffer ★★★★★

↑ Index
Java
StringStringBuilderStringBuffer
ImmutableMutableMutable
Thread-safe (because immutable)Not thread-safeThread-safe (synchronized)
Slow for many changesFastestSlower than StringBuilder
Java
String s1 = "hello";               // string pool
String s2 = "hello";               // same pool object
String s3 = new String("hello");   // new heap object
System.out.println(s1 == s2);      // true  (same reference)
System.out.println(s1 == s3);      // false
System.out.println(s1.equals(s3)); // true  (same content)

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i);
System.out.println(sb.reverse());  // 43210

Q & A

  1. == vs equals()?
    == compares references (same object?). equals() compares content. Always use equals() for strings.
  2. Why is String immutable?
    For security (class names, URLs, passwords), string pool sharing, thread safety and caching the hashCode.
92

OOP in Java

↑ Index
Java
Java
abstract class Animal {
    protected String name;
    Animal(String name) { this.name = name; }
    abstract void sound();                       // must be overridden
    void sleep() { System.out.println(name + " sleeps"); }
}

interface Pet { void play(); }

class Dog extends Animal implements Pet {
    Dog(String name) { super(name); }            // call parent constructor
    @Override void sound() { System.out.println("Woof"); }
    public void play() { System.out.println(name + " plays"); }
}

Animal a = new Dog("Tommy");   // upcasting → run-time polymorphism
a.sound();                     // Woof
  • extends — one class only; implements — many interfaces.
  • super — parent constructor or method; this — current object.
  • final class cannot be extended, final method cannot be overridden, final variable cannot be reassigned.
  • All non-static, non-final, non-private methods are virtual by default in Java.
93

Exception Handling in Java ★★★★★

↑ Index
Java
Checked exceptionUnchecked exception
Checked at compile timeHappens at run time
Must be caught or declared with throwsNot forced
IOException, SQLException, FileNotFoundExceptionNullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException

Hierarchy: Throwable → Error (OutOfMemoryError, StackOverflowError — do not catch) and Exception → RuntimeException (unchecked).

Java
try {
    int[] arr = new int[3];
    arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Bad index: " + e.getMessage());
} finally {
    System.out.println("finally always runs");
}

// try-with-resources closes the reader automatically
try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
    System.out.println(br.readLine());
} catch (IOException e) {
    e.printStackTrace();
}

class InsufficientBalanceException extends Exception {     // custom checked exception
    InsufficientBalanceException(String msg) { super(msg); }
}

Q & A

  1. throw vs throws?
    throw actually throws one exception object inside a method. throws in the method signature declares which checked exceptions the method may throw.
  2. final vs finally vs finalize?
    final: keyword for constants / no override / no inheritance. finally: block that always runs after try-catch. finalize(): old GC hook, deprecated.
94

Java Collections Framework ★★★★★

↑ Index
Java

List, Set, Queue and Map with their common implementations

List, Set, Queue and Map with their common implementations

ClassOrderDuplicatesLookup
ArrayListInsertionYesget(i) O(1)
LinkedListInsertionYesget(i) O(n)
HashSetNoneNoO(1)
TreeSetSortedNoO(log n)
HashMapNoneKeys uniqueO(1)
TreeMapSorted by keyKeys uniqueO(log n)
Java
List<Integer> list = new ArrayList<>(List.of(5, 2, 8));
Collections.sort(list);                      // [2, 5, 8]

Map<String, Integer> freq = new HashMap<>();
for (String w : "a b a c a".split(" "))
    freq.put(w, freq.getOrDefault(w, 0) + 1);
System.out.println(freq);                    // {a=3, b=1, c=1}

Set<String> set = new TreeSet<>(List.of("b", "a", "b"));   // [a, b]

Q & A

  1. HashMap vs Hashtable?
    HashMap is not synchronized, allows one null key, faster. Hashtable is synchronized (legacy) and allows no null. For threads use ConcurrentHashMap.
  2. How does HashMap work?
    hashCode() picks a bucket; entries in the same bucket form a linked list (a red-black tree after 8 entries); equals() finds the exact key.
95

Multithreading in Java

↑ Index
Java

A thread is a lightweight unit of execution inside a process. Create one by extending Thread or implementing Runnable (preferred).

New → Runnable → Running → Terminated

New → Runnable → Running → Terminated

Java
class Counter {
    private int count = 0;
    public synchronized void increment() { count++; }   // one thread at a time
    public int get() { return count; }
}

Counter c = new Counter();
Runnable task = () -> { for (int i = 0; i < 1000; i++) c.increment(); };
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start();
t1.join();  t2.join();            // wait for both
System.out.println(c.get());      // 2000

ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("from the pool"));
pool.shutdown();

start() creates a new thread and calls run(); calling run() directly just runs it on the current thread.

96

static and final in Java

↑ Index
Java
  • static variable — one copy for the whole class.
  • static method — called with the class name; cannot use this or instance members.
  • static block — runs once when the class loads.
  • final — constant variable, method that cannot be overridden, class that cannot be extended (e.g. String).
Java
class Config {
    static final double PI = 3.1416;   // constant
    static int instances;
    static { System.out.println("class loaded"); }
    Config() { instances++; }
}
97

Java 8 Features: Lambda and Streams

↑ Index
Java

Java 8 added lambda expressions, functional interfaces (one abstract method), the Stream API, Optional, default methods in interfaces and the new Date/Time API.

Java
List<String> names = List.of("Rahim", "Karim", "Sumi", "Ria");

List<String> result = names.stream()
    .filter(n -> n.length() > 3)
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());    // [KARIM, RAHIM, SUMI]

int sum = IntStream.rangeClosed(1, 100).sum();   // 5050

Optional<String> first = names.stream().filter(n -> n.startsWith("Z")).findFirst();
System.out.println(first.orElse("none"));
98

Java Memory and Garbage Collection

↑ Index
Java
  • Stack — method calls and local variables, one per thread.
  • Heap — all objects; shared by threads; divided into Young generation (Eden, Survivor) and Old generation.
  • Method area / Metaspace — class metadata and static variables.
  • An object becomes eligible for GC when no reference points to it. System.gc() is only a request.
99

DBMS and RDBMS

↑ Index
Database

A database is an organised collection of data. A DBMS (Database Management System) is software to store, retrieve and manage it (MySQL, PostgreSQL, Oracle, SQL Server, MongoDB).

DBMSRDBMS
Data may be stored as files / documentsData stored in tables (rows and columns)
Relationships not enforcedRelationships through keys (foreign keys)
May not support ACID fullySupports ACID transactions and normalization
File system, XML DBMySQL, PostgreSQL, Oracle
  • Table (relation), row (tuple / record), column (attribute / field).
  • Degree = number of columns; cardinality = number of rows.
  • Schema = structure of the database; instance = data at a moment.

Q & A

  1. Advantages of DBMS over a file system?
    Less redundancy, consistency, concurrent access, security, backup and recovery, and easy querying with SQL.
100

Keys in DBMS ★★★★★

↑ Index
Database
KeyMeaning
Super keyAny set of columns that uniquely identifies a row
Candidate keyMinimal super key (no extra column)
Primary keyThe chosen candidate key: unique and NOT NULL, one per table
Alternate keyCandidate keys that were not chosen as primary
Foreign keyColumn that refers to the primary key of another table
Composite keyPrimary key made of two or more columns
Unique keyUnique values but NULL is allowed
SQL
CREATE TABLE departments (
    id   INT PRIMARY KEY,
    name VARCHAR(50) NOT NULL UNIQUE
);

CREATE TABLE students (
    roll    INT PRIMARY KEY,
    email   VARCHAR(100) UNIQUE,
    name    VARCHAR(100) NOT NULL,
    dept_id INT,
    FOREIGN KEY (dept_id) REFERENCES departments(id)
);

CREATE TABLE enrollments (
    roll      INT,
    course_id INT,
    grade     CHAR(2),
    PRIMARY KEY (roll, course_id)       -- composite key
);
101

ER Diagram

↑ Index
Database

An Entity-Relationship diagram models the database before building tables: entities (things), attributes (properties) and relationships.

A student can take many courses and a course has many students (M:N)

A student can take many courses and a course has many students (M:N)

  • Cardinality: one-to-one (1:1), one-to-many (1:N), many-to-many (M:N).
  • Weak entity — cannot be identified by its own attributes (double rectangle), e.g. Dependent of an Employee.
  • Derived attribute (dashed ellipse), e.g. Age from DOB; multi-valued (double ellipse), e.g. Phone numbers.
102

Normalization (1NF, 2NF, 3NF, BCNF) ★★★★★

↑ Index
Database

Normalization splits tables to remove redundancy and anomalies (insert, update, delete). It is based on functional dependency: A → B means A decides B.

Each normal form builds on the previous one

Each normal form builds on the previous one

FormRuleExample fix
1NFEvery cell holds one atomic value; no repeating groupsPhone = "017.., 018.." → one row per phone
2NF1NF and no non-key column depends on only part of a composite key(Roll, CourseID) → CourseName depends only on CourseID → move to Course table
3NF2NF and no non-key column depends on another non-key columnRoll → DeptID → DeptName → move DeptName to Department table
BCNFFor every A → B, A must be a super keyStricter version of 3NF

Q & A

  1. What is denormalization?
    Adding some redundancy back on purpose (for example, storing a total) to make reads faster, at the cost of harder updates.
103

SQL Command Types

↑ Index
Database
TypeFull nameCommands
DDLData Definition LanguageCREATE, ALTER, DROP, TRUNCATE, RENAME
DMLData Manipulation LanguageINSERT, UPDATE, DELETE
DQLData Query LanguageSELECT
DCLData Control LanguageGRANT, REVOKE
TCLTransaction Control LanguageCOMMIT, ROLLBACK, SAVEPOINT
SQL
INSERT INTO students (roll, name, dept_id) VALUES (1, 'Rahim', 10);
UPDATE students SET name = 'Karim' WHERE roll = 1;
DELETE FROM students WHERE roll = 1;

ALTER TABLE students ADD COLUMN cgpa DECIMAL(3,2);

SELECT name, cgpa
FROM students
WHERE cgpa >= 3.5 AND name LIKE 'R%'
ORDER BY cgpa DESC
LIMIT 5;

DELETE vs TRUNCATE vs DROP

DELETETRUNCATEDROP
DML, removes chosen rows (WHERE)DDL, removes all rowsDDL, removes the whole table
Can be rolled backUsually cannot be rolled backCannot be rolled back
Slower, row by rowFast, resets auto incrementStructure is gone too
104

SQL Joins ★★★★★

↑ Index
Database

A JOIN combines rows from two tables using a related column.

Shaded area = rows returned

Shaded area = rows returned

SQL
-- INNER JOIN: only students that have a department
SELECT s.name, d.name AS dept
FROM students s
INNER JOIN departments d ON s.dept_id = d.id;

-- LEFT JOIN: every student, dept is NULL when missing
SELECT s.name, d.name AS dept
FROM students s
LEFT JOIN departments d ON s.dept_id = d.id;

-- Students without a department
SELECT s.name
FROM students s
LEFT JOIN departments d ON s.dept_id = d.id
WHERE d.id IS NULL;

-- SELF JOIN: employee with their manager
SELECT e.name, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

CROSS JOIN returns every combination (rows A × rows B). MySQL has no FULL OUTER JOIN: use LEFT JOIN UNION RIGHT JOIN.

105

Aggregate Functions, GROUP BY and HAVING ★★★★★

↑ Index
Database

Aggregate functions: COUNT, SUM, AVG, MIN, MAX. GROUP BY makes one row per group. WHERE filters rows before grouping; HAVING filters groups after.

SQL
SELECT dept_id, COUNT(*) AS total, AVG(cgpa) AS avg_cgpa
FROM students
WHERE cgpa IS NOT NULL
GROUP BY dept_id
HAVING COUNT(*) > 10
ORDER BY avg_cgpa DESC;
Most asked SQL queries · SQL
-- 2nd highest salary
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

-- Nth highest (N = 3)
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;

-- Duplicate emails
SELECT email, COUNT(*) FROM users
GROUP BY email HAVING COUNT(*) > 1;

-- Highest paid employee in each department
SELECT * FROM employees e
WHERE salary = (SELECT MAX(salary) FROM employees WHERE dept_id = e.dept_id);

Order of execution: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT.

106

Transactions and ACID ★★★★★

↑ Index
Database

A transaction is a group of operations that must succeed or fail together, e.g. a money transfer.

PropertyMeaning
AtomicityAll or nothing: if one step fails, everything is rolled back
ConsistencyThe database moves from one valid state to another (rules and constraints hold)
IsolationConcurrent transactions do not see each other's half-done work
DurabilityOnce committed, data survives crashes (written to disk / log)
SQL
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;          -- or ROLLBACK; if anything went wrong

Isolation levels

Isolation levelDirty readNon-repeatable readPhantom read
Read UncommittedPossiblePossiblePossible
Read CommittedNoPossiblePossible
Repeatable Read (MySQL default)NoNoPossible
SerializableNoNoNo
107

Indexing

↑ Index
Database

An index is a separate data structure (usually a B+ tree) that lets the database find rows without scanning the whole table, like the index at the back of a book. It speeds up SELECT/WHERE/JOIN/ORDER BY but slows down INSERT/UPDATE/DELETE and uses extra space.

  • Clustered index — the table rows are physically stored in index order; only one per table (the primary key in InnoDB).
  • Non-clustered index — separate structure pointing to rows; many per table.
  • Composite index on (a, b) helps queries on a, or a and b, but not on b alone (leftmost prefix rule).
SQL
CREATE INDEX idx_students_name ON students(name);
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);
EXPLAIN SELECT * FROM students WHERE name = 'Rahim';   -- check if the index is used
108

Views, Stored Procedures and Triggers

↑ Index
Database
SQL
-- View: a saved query that behaves like a table
CREATE VIEW top_students AS
SELECT name, cgpa FROM students WHERE cgpa >= 3.75;

-- Stored procedure: saved, reusable SQL with parameters
DELIMITER //
CREATE PROCEDURE get_dept_students(IN d INT)
BEGIN
    SELECT * FROM students WHERE dept_id = d;
END //
DELIMITER ;
CALL get_dept_students(10);

-- Trigger: runs automatically on INSERT / UPDATE / DELETE
CREATE TRIGGER before_student_insert
BEFORE INSERT ON students
FOR EACH ROW SET NEW.name = UPPER(NEW.name);
109

SQL vs NoSQL

↑ Index
Database
SQL (relational)NoSQL
Tables with a fixed schemaFlexible schema: document, key-value, column, graph
Scales vertically (bigger server)Scales horizontally (more servers, sharding)
Strong ACID transactionsOften BASE / eventual consistency
Complex joins and queriesFast simple reads/writes at huge scale
MySQL, PostgreSQL, OracleMongoDB, Redis, Cassandra, Neo4j

CAP theorem: a distributed system can guarantee only two of Consistency, Availability and Partition tolerance at the same time.

110

OSI Model ★★★★★

↑ Index
Computer Network

The OSI (Open Systems Interconnection) model splits network communication into 7 layers. Each layer serves the layer above it. Mnemonic (top → bottom): All People Seem To Need Data Processing.

OSI layers, example protocols, PDU names and the matching TCP/IP layers

OSI layers, example protocols, PDU names and the matching TCP/IP layers

LayerJobDevice
ApplicationNetwork services to the user (web, mail)Gateway
PresentationTranslation, encryption, compression—
SessionOpen, manage and close sessions—
TransportEnd-to-end delivery, ports, segmentation, flow and error controlFirewall
NetworkLogical addressing (IP) and routingRouter
Data LinkPhysical addressing (MAC), framing, error detectionSwitch, Bridge
PhysicalTransmit raw bits over the mediumHub, Repeater, Cable

Q & A

  1. What is encapsulation?
    Each layer adds its own header while data goes down (data → segment → packet → frame → bits). The receiver removes them going up (decapsulation).
111

TCP/IP Model

↑ Index
Computer Network
TCP/IP layerOSI layersProtocols
ApplicationApplication + Presentation + SessionHTTP, HTTPS, FTP, SMTP, DNS, SSH
TransportTransportTCP, UDP
InternetNetworkIP, ICMP, ARP
Network Access (Link)Data Link + PhysicalEthernet, Wi-Fi

OSI is a theoretical reference model; TCP/IP is the practical model the internet uses.

112

TCP vs UDP ★★★★★

↑ Index
Computer Network
TCPUDP
Connection-oriented (handshake first)Connectionless
Reliable: acknowledgement, retransmissionUnreliable: no guarantee of delivery
Data arrives in orderNo ordering
Flow and congestion controlNone
Slower, 20-byte headerFaster, 8-byte header
Web (HTTP), email, file transfer, SSHVideo streaming, gaming, VoIP, DNS

SYN → SYN-ACK → ACK

SYN → SYN-ACK → ACK

113

Common Ports and Protocols

↑ Index
Computer Network
ProtocolPortUse
HTTP80Web pages
HTTPS443Secure web (TLS)
FTP20, 21File transfer
SSH22Secure remote login
Telnet23Remote login (plain text)
SMTP25 / 587Send email
POP3110Download email
IMAP143Read email on server
DNS53Domain name → IP
DHCP67, 68Automatic IP address
MySQL3306Database
RDP3389Remote desktop
114

IP Address and Subnetting ★★★★★

↑ Index
Computer Network

An IPv4 address is 32 bits written as four octets (192.168.1.10). IPv6 is 128 bits written in hex (2001:db8::1).

ClassFirst octetDefault maskPrivate range
A1 – 126255.0.0.0 (/8)10.0.0.0 – 10.255.255.255
B128 – 191255.255.0.0 (/16)172.16.0.0 – 172.31.255.255
C192 – 223255.255.255.0 (/24)192.168.0.0 – 192.168.255.255
D224 – 239—Multicast
E240 – 255—Experimental

127.0.0.1 is the loopback (localhost) address.

Subnetting

Subnetting example: 192.168.1.0/26

  • Mask /26 = 255.255.255.192 → host bits = 32 − 26 = 6
  • Addresses per subnet = 26 = 64, usable hosts = 64 − 2 = 62 (network and broadcast are reserved)
  • Number of subnets from a /24 = 22 = 4 → .0, .64, .128, .192
  • First subnet: network 192.168.1.0, hosts .1 – .62, broadcast 192.168.1.63

Q & A

  1. What is CIDR?
    Classless Inter-Domain Routing: writes the mask as /prefix length (for example /26), so networks are not limited to classes A, B and C.
  2. What is NAT?
    Network Address Translation lets many devices with private IPs share one public IP through the router.
115

DNS

↑ Index
Computer Network

DNS (Domain Name System) converts a domain name into an IP address, like the phone book of the internet. It mainly uses UDP port 53.

Recursive resolver asks root → TLD → authoritative server

Recursive resolver asks root → TLD → authoritative server

RecordMeaning
ADomain → IPv4 address
AAAADomain → IPv6 address
CNAMEAlias of another domain
MXMail server
NSName server of the domain
TXTText (SPF, verification)
116

HTTP and HTTPS ★★★★★

↑ Index
Computer Network

HTTP is a stateless request/response protocol for the web. HTTPS = HTTP over TLS: data is encrypted, the server is verified by a certificate, and it uses port 443.

MethodUse
GETRead data
POSTCreate / submit data
PUTReplace a resource
PATCHUpdate part of a resource
DELETERemove a resource

HTTP status codes

CodeMeaning
1xxInformational
200 OKSuccess
201 CreatedResource created
301 / 302Moved permanently / temporarily (redirect)
304Not modified (use cache)
400Bad request
401Unauthorised (login needed)
403Forbidden
404Not found
500Internal server error
502 / 503Bad gateway / service unavailable

Q & A

  1. What happens when you type a URL and press Enter?
    DNS lookup gives the IP → TCP handshake (and TLS handshake for HTTPS) → browser sends an HTTP request → server sends the response → browser parses HTML, loads CSS/JS/images and renders the page.
  2. Why is HTTP stateless and how do sites remember you?
    Each request is independent. Sites use cookies, sessions or tokens (JWT) to keep state.
117

Network Devices

↑ Index
Computer Network
DeviceLayerWorks withWhat it does
HubPhysical (1)BitsSends data to every port (one collision domain)
RepeaterPhysical (1)BitsRegenerates the signal to extend distance
SwitchData Link (2)MAC addressSends the frame only to the correct port
BridgeData Link (2)MAC addressConnects two LAN segments
RouterNetwork (3)IP addressConnects different networks, chooses the best path
GatewayAll layersProtocolsConnects networks using different protocols
ModemPhysicalSignalsConverts digital ↔ analog
118

Network Topologies and Types

↑ Index
Computer Network

Bus, star, ring, mesh and tree

Bus, star, ring, mesh and tree

TopologyAdvantageDisadvantage
BusCheap, easyBackbone cable fails → whole network fails
StarEasy to manage, one cable failure affects one deviceCentral switch is a single point of failure
RingOrderly data flowOne break can stop the ring
MeshVery reliable (many paths)Expensive, many cables

Network types by size: PAN (Bluetooth) < LAN (office) < MAN (city) < WAN (country / internet).

119

ARP, DHCP and ICMP

↑ Index
Computer Network
  • ARP (Address Resolution Protocol) — finds the MAC address for a known IP address inside the LAN (broadcast "who has 192.168.1.5?").
  • DHCP — gives a device an IP address, mask, gateway and DNS automatically. Steps: DORA — Discover, Offer, Request, Acknowledge.
  • ICMP — error and diagnostic messages; used by ping and traceroute.
Useful commands · Bash / Shell
ping google.com          # is the host reachable? (ICMP echo)
tracert google.com       # path of routers (Windows; traceroute on Linux)
ipconfig /all            # IP, MAC, gateway, DNS (Windows; ip a on Linux)
nslookup example.com     # DNS lookup
arp -a                   # ARP cache
120

Network Security Basics

↑ Index
Computer Network
  • Firewall — allows or blocks traffic by rules (IP, port, protocol).
  • Symmetric encryption (AES) — one shared key, fast. Asymmetric (RSA) — public/private key pair, used to exchange keys and for digital signatures.
  • Hashing (SHA-256) — one-way fingerprint for integrity and password storage.
  • VPN — encrypted tunnel over a public network.
  • Common attacks: DoS/DDoS, man-in-the-middle, phishing, SQL injection, XSS.
121

What is an Operating System ★★★★★

↑ Index
Operating System

An operating system is system software that manages computer hardware and provides services to programs. Examples: Windows, Linux, macOS, Android.

The OS is the layer between programs and hardware

The OS is the layer between programs and hardware

Main functions: process management, memory management, file system management, device (I/O) management, security and protection, user interface.

TypeIdeaExample
BatchJobs grouped and run without interactionEarly mainframes
MultiprogrammingSeveral programs in memory, CPU switches when one waits for I/O—
Time-sharing (multitasking)CPU time is sliced between users/programsUnix, Windows
Real-timeMust respond within a strict deadlineAir-bag controller, RTOS
DistributedMany computers act like one systemCluster systems

Q & A

  1. What is the kernel?
    The core part of the OS that runs in privileged mode and directly controls CPU, memory and devices.
  2. Monolithic vs microkernel?
    Monolithic: all services (drivers, file system) run inside the kernel, fast (Linux). Microkernel: only minimal services in the kernel, the rest in user space, more stable and secure but slower (Minix, QNX).
122

Process vs Thread ★★★★★

↑ Index
Operating System

A process is a program in execution, with its own memory space. A thread is the smallest unit of execution inside a process; threads of the same process share its memory.

ProcessThread
HeavyweightLightweight
Own memory (code, data, heap, stack)Shares code, data and heap; has its own stack and registers
Context switch is slowContext switch is fast
Communicate via IPC (pipes, sockets, shared memory)Communicate directly through shared memory
One crashing does not affect othersOne crashing thread can crash the whole process

PCB (Process Control Block) stores everything about a process: PID, state, program counter, registers, memory info, open files, priority.

Context switch: saving the state of the running process in its PCB and loading the next one.

123

Process States

↑ Index
Operating System

New → Ready → Running → Waiting → Terminated

New → Ready → Running → Waiting → Terminated

  • New — being created.
  • Ready — waiting for the CPU.
  • Running — instructions are executing.
  • Waiting / Blocked — waiting for I/O or an event.
  • Terminated — finished.

Zombie process: finished but its parent has not read its exit status. Orphan process: its parent ended first (adopted by init).

124

CPU Scheduling Algorithms ★★★★★

↑ Index
Operating System

Terms: Burst time (CPU time needed), Arrival time, Completion time, Turnaround time = Completion − Arrival, Waiting time = Turnaround − Burst, Response time = first run − arrival.

AlgorithmTypeIdeaProblem
FCFSNon-preemptiveFirst come, first servedConvoy effect (short jobs wait behind a long one)
SJFNon-preemptiveShortest burst first; minimum average waiting timeStarvation of long jobs; burst time must be known
SRTFPreemptive SJFShortest remaining time firstStarvation
PriorityEitherHighest priority firstStarvation → fixed by aging
Round RobinPreemptiveEach process gets a time quantum in turnToo small quantum = many context switches
Multilevel QueueEitherSeparate queues (system, interactive, batch)Rigid

Round Robin example with its waiting and turnaround times

Round Robin example with its waiting and turnaround times

FCFS average waiting time · C++
// FCFS waiting time: each process waits for all bursts before it
int burst[] = {24, 3, 3}, n = 3, wait = 0, total = 0;
for (int i = 0; i < n; i++) {
    total += wait;
    wait += burst[i];
}
cout << "Average waiting = " << (double)total / n;   // (0 + 24 + 27) / 3 = 17
125

Process Synchronization ★★★★★

↑ Index
Operating System

When processes/threads share data, a race condition happens if the result depends on the order they run. The code that touches shared data is the critical section.

A correct solution needs: Mutual exclusion (one at a time), Progress and Bounded waiting.

MutexSemaphore
Lock with owner: only the thread that locked can unlockInteger counter changed by wait() / signal()
Binary: locked / unlockedBinary (0/1) or counting (0..n)
Protect one critical sectionAlso limits access to n identical resources
Semaphore operations · C
// wait (P) and signal (V) — both are atomic
wait(S) {
    while (S <= 0) ;   // busy wait
    S--;
}
signal(S) {
    S++;
}

// usage
wait(mutex);
/* critical section */
signal(mutex);

Classic problems: Producer–Consumer (bounded buffer), Readers–Writers, Dining Philosophers.

126

Deadlock ★★★★★

↑ Index
Operating System

A deadlock is a state where a set of processes wait forever, each holding a resource the other needs.

Resource allocation graph with a cycle

Resource allocation graph with a cycle

Four necessary conditions (Coffman) — all must hold:

  • Mutual exclusion — a resource is used by one process at a time.
  • Hold and wait — a process holds one resource and waits for another.
  • No preemption — a resource cannot be taken away forcibly.
  • Circular wait — P1 waits for P2, P2 waits for P1 (a cycle).

Handling: Prevention (break one condition), Avoidance (Banker's algorithm, only grant requests that keep the system in a safe state), Detection and recovery (kill a process / preempt resources), or Ignore it (Ostrich approach, used by most desktop OSes).

Q & A

  1. Deadlock vs starvation?
    Deadlock: processes wait for each other forever and none progresses. Starvation: one process waits a very long time because others keep getting priority; the system still progresses.
127

Memory Management and Paging ★★★★★

↑ Index
Operating System
  • Contiguous allocation — each process gets one block; strategies First fit, Best fit, Worst fit; causes external fragmentation.
  • Paging — logical memory split into fixed-size pages, physical memory into frames of the same size; a page table maps them.
  • Segmentation — memory divided by logical units (code, stack, data) of different sizes.
  • TLB — fast cache of recent page-table entries.

Pages do not need to be next to each other in physical memory

Pages do not need to be next to each other in physical memory

Internal fragmentationExternal fragmentation
Wasted space inside an allocated blockFree space is split into small holes between blocks
Happens in paging (last page)Happens in contiguous allocation / segmentation
Fix: smaller blocksFix: compaction or paging
128

Virtual Memory and Page Replacement ★★★★★

↑ Index
Operating System

Virtual memory lets a program use more memory than physically available by keeping only the needed pages in RAM (demand paging). Accessing a page that is not in RAM causes a page fault. Too many page faults = thrashing.

Example: reference string 7 0 1 2 0 3 0 4, 3 frames

AlgorithmIdeaPage faults
FIFOReplace the page that came in first7
LRUReplace the least recently used page6
OptimalReplace the page not needed for the longest time (theoretical best)6

Belady's anomaly: with FIFO, adding more frames can sometimes increase page faults.

LRU page faults · C++
int lruFaults(vector<int> refs, int frames) {
    list<int> cache;                       // front = most recently used
    int faults = 0;
    for (int p : refs) {
        auto it = find(cache.begin(), cache.end(), p);
        if (it != cache.end()) cache.erase(it);          // hit
        else {
            faults++;
            if (cache.size() == frames) cache.pop_back(); // evict LRU
        }
        cache.push_front(p);
    }
    return faults;
}
129

System Calls and User/Kernel Mode

↑ Index
Operating System

A program runs in user mode. To use hardware (files, network, new process) it makes a system call, which switches the CPU to kernel mode.

CategoryExamples (Linux)
Process controlfork(), exec(), exit(), wait()
File managementopen(), read(), write(), close()
Device managementioctl()
Informationgetpid(), time()
Communicationpipe(), socket(), shmget()
fork() · C
#include <unistd.h>
#include <stdio.h>

int main() {
    pid_t pid = fork();          // creates a child process
    if (pid == 0) printf("Child, pid = %d\n", getpid());
    else          printf("Parent, child pid = %d\n", pid);
    return 0;
}
// fork() returns 0 in the child and the child's pid in the parent
130

File System and Disk Scheduling

↑ Index
Operating System
  • File allocation: contiguous (fast, fragmentation), linked (no fragmentation, slow random access), indexed (index block holds pointers, e.g. inodes).
  • Disk access time = seek time + rotational latency + transfer time.
AlgorithmIdea
FCFSServe requests in arrival order
SSTFShortest seek time first (nearest track)
SCAN (elevator)Move to one end serving requests, then reverse
C-SCANServe in one direction only, jump back to the start
LOOK / C-LOOKLike SCAN / C-SCAN but turn at the last request, not the disk end
131

Software Engineering and SDLC ★★★★★

↑ Index
Software Engineering

Software engineering is the systematic, disciplined approach to developing, operating and maintaining software. The SDLC (Software Development Life Cycle) is the series of phases a project goes through.

The seven SDLC phases

The seven SDLC phases

PhaseOutput
PlanningFeasibility study, cost and time estimate
Requirement analysisSRS (Software Requirements Specification)
DesignArchitecture, database design, UI design (HLD / LLD)
ImplementationSource code
TestingBug reports, tested build
DeploymentReleased product
MaintenanceBug fixes, updates, enhancements

Q & A

  1. What is software crisis?
    The problems of the 1960s-70s where projects went over budget, were late, unreliable and hard to maintain, which led to software engineering as a discipline.
132

Waterfall Model

↑ Index
Software Engineering

A linear, sequential model: each phase must finish before the next begins.

Phases flow down like a waterfall

Phases flow down like a waterfall

AdvantagesDisadvantages
Simple and easy to manageHard to go back and change requirements
Clear milestones and documentationWorking software only at the end
Good for small projects with fixed, clear requirementsHigh risk for large or changing projects
133

Agile and Scrum ★★★★★

↑ Index
Software Engineering

Agile builds software in short iterations, delivering working software often and welcoming changing requirements.

Agile Manifesto values:

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan

Product backlog → sprint → increment

Product backlog → sprint → increment

Artifacts: Product Backlog, Sprint Backlog, Increment. Events: Sprint Planning, Daily Scrum, Sprint Review, Sprint Retrospective. Requirements are written as user stories: "As a <user>, I want <goal> so that <reason>".

Q & A

  1. Agile vs Waterfall?
    Waterfall: sequential, fixed requirements, delivery at the end, heavy documentation. Agile: iterative, requirements can change, frequent delivery, continuous customer feedback.
  2. Scrum vs Kanban?
    Scrum uses fixed-length sprints and defined roles. Kanban is a continuous flow on a board (To Do → Doing → Done) with limits on work in progress.
134

Other SDLC Models

↑ Index
Software Engineering
ModelIdeaBest for
Iterative / IncrementalBuild the system in small parts, each adding featuresLarge projects with clear core needs
SpiralIterations with risk analysis in every loop (Plan → Risk → Engineer → Evaluate)Large, high-risk projects
V-ModelWaterfall where every development phase has a matching test phaseSafety-critical systems
PrototypeBuild a quick model to understand requirements, then the real systemUnclear requirements
RADRapid development with reusable components and user feedbackShort deadlines
DevOpsDevelopment + operations, CI/CD automationFrequent releases
135

Requirements Engineering

↑ Index
Software Engineering
Functional requirementsNon-functional requirements
What the system should doHow well the system should do it
User can log in, place an order, download a reportPerformance, security, usability, reliability, scalability
Tested with feature testsMeasured with metrics (response < 2 s, 99.9% uptime)

Steps: elicitation (interviews, surveys, observation) → analysis → specification (SRS) → validation → management.

A good SRS is correct, complete, unambiguous, consistent, verifiable and traceable.

136

Software Testing ★★★★★

↑ Index
Software Engineering

Unit → Integration → System → Acceptance

Unit → Integration → System → Acceptance

Black box testingWhite box testing
Tests behaviour without seeing the codeTests internal code, paths and logic
Done by testersDone by developers
Equivalence partitioning, boundary value analysisStatement, branch and path coverage
  • Regression testing — re-test after a change to make sure nothing old broke.
  • Smoke testing — quick check that the main features work in a new build.
  • Alpha testing (inside the company) vs Beta testing (real users).
  • Verification = are we building the product right? Validation = are we building the right product?
A tiny unit test · C++
// Function under test
int maxOf(int a, int b) { return a > b ? a : b; }

// Unit tests (boundary and normal cases)
assert(maxOf(3, 5) == 5);
assert(maxOf(5, 3) == 5);
assert(maxOf(-1, -1) == -1);
assert(maxOf(INT_MAX, 0) == INT_MAX);

Q & A

  1. What is boundary value analysis?
    Testing at the edges of valid ranges. For an age field 18–60, test 17, 18, 19, 59, 60 and 61, because bugs often hide at boundaries.
  2. Error vs defect vs failure?
    Error: a human mistake. Defect (bug): the fault in the code caused by it. Failure: the wrong behaviour seen when the defective code runs.
137

UML Diagrams

↑ Index
Software Engineering

UML (Unified Modeling Language) is a standard way to visualise a system design.

StructuralBehavioural
Class diagram — classes, attributes, methods, relationshipsUse case diagram — actors and what they can do
Object diagram — objects at one momentSequence diagram — messages between objects over time
Component diagramActivity diagram — workflow, like a flowchart
Deployment diagram — hardware nodesState machine diagram — states of an object
  • Class relationships: association (line), inheritance (hollow triangle), aggregation (hollow diamond), composition (filled diamond), dependency (dashed arrow).
  • Visibility: + public, - private, # protected.
138

Coupling and Cohesion

↑ Index
Software Engineering

Good design has low coupling and high cohesion.

CouplingCohesion
How much modules depend on each otherHow closely the parts inside one module belong together
Want it LOWWant it HIGH
Worst: content coupling; best: data couplingWorst: coincidental; best: functional

Low coupling means a change in one module rarely breaks another; high cohesion means each module has one clear job.

139

Design Patterns

↑ Index
Software Engineering
CategoryPatterns
Creational (object creation)Singleton, Factory, Abstract Factory, Builder, Prototype
Structural (composition)Adapter, Decorator, Facade, Proxy, Composite
Behavioural (communication)Observer, Strategy, Command, Iterator, State
Singleton: exactly one object · C++
class Database {
private:
    Database() {}                          // no outside construction
public:
    static Database& instance() {
        static Database db;                // created once, thread-safe (C++11)
        return db;
    }
    Database(const Database&) = delete;    // no copies
    void operator=(const Database&) = delete;
};

Database &db = Database::instance();
Factory: hide which class is created · C++
class Shape { public: virtual void draw() = 0; virtual ~Shape() {} };
class Circle : public Shape { public: void draw() override { cout << "Circle\n"; } };
class Square : public Shape { public: void draw() override { cout << "Square\n"; } };

unique_ptr<Shape> createShape(const string &type) {   // factory
    if (type == "circle") return make_unique<Circle>();
    return make_unique<Square>();
}
createShape("circle")->draw();
Observer: notify all subscribers · C++
class Observer { public: virtual void update(const string &msg) = 0; };

class Channel {
    vector<Observer*> subs;
public:
    void subscribe(Observer *o) { subs.push_back(o); }
    void publish(const string &msg) { for (auto *o : subs) o->update(msg); }
};
140

Software Metrics and Estimation

↑ Index
Software Engineering
  • LOC — lines of code (simple size measure).
  • Function Point — size by inputs, outputs, inquiries, files and interfaces (language independent).
  • Cyclomatic complexity = E − N + 2 (edges − nodes + 2) = number of decisions + 1; the number of independent paths to test.
  • COCOMO — estimates effort: Effort = a × (KLOC)b person-months (organic, semi-detached, embedded).
141

Git and Version Control

↑ Index
Software Engineering

Version control records every change so a team can work together, review history and roll back. Git is distributed: every developer has the full history.

Bash / Shell
git init                       # new repository
git clone <url>                # copy a remote repository
git status                     # what changed
git add .                      # stage changes
git commit -m "Add login page" # save a snapshot
git log --oneline              # history
git branch feature-x           # create a branch
git checkout -b feature-x      # create and switch
git merge feature-x            # merge into the current branch
git pull                       # fetch + merge from remote
git push origin main           # upload commits
git revert <commit>            # undo a commit with a new commit

merge keeps both histories with a merge commit; rebase replays your commits on top of another branch for a straight history.

142

Length of an Array

↑ Index
Problem Solving
Problem: Find the number of elements in an array.
C++
int arr[] = {1,2,3,4,5};
int len = sizeof(arr) / sizeof(arr[0]);
cout << len;   // 5
143

Length (count digits) of a number

↑ Index
Problem Solving
Problem: Count the digits of a number (1234 -> 4).

A do-while loop is used so that the number 0 is counted as 1 digit.

Solution 1: do-while loop · C++
int main() {
    int num = 1234;
    int len = 0;
    do{
        num = num / 10;
        len++;
    }while(num != 0);
    cout << len;   // 4
}
Solution 2: String method · C++
int num = 1234;
int len = to_string(num).length();
cout << len;
144

Power (x^n)

↑ Index
Problem Solving
Problem: Calculate x raised to the power n.
Solution 1: Loop O(n) · C++
int x = 2, n = 5;
long long result = 1;
for(int i = 0; i < n; i++){
    result = result * x;
}
cout << result;   // 32
// STL: cout << pow(2, 5);
145

Largest & Smallest Digit of a Number

↑ Index
Problem Solving
Problem: Find the largest and the smallest digit of a number.
Largest digit · C++
int num = 234515;
int lrg = 0;
do{
    int digit = num % 10;
    if(digit > lrg) lrg = digit;
    num = num / 10;
}while(num != 0);
cout << lrg;   // 5
Smallest digit · C++
int num = 234515;
int small = 9;
do{
    int digit = num % 10;
    if(digit < small) small = digit;
    num = num / 10;
}while(num != 0);
cout << small;   // 1
146

Bit Manipulation (common)

↑ Index
Problem Solving
Problem: Power of 2 check and counting set bits.
Power of 2 check · C++
bool isPow2(int n){
    return n > 0 && (n & (n - 1)) == 0;
}
Count set bits · C++
int n = 13, count = 0;
while(n){
    count += n & 1;
    n >>= 1;
}
// or: __builtin_popcount(13)
147

Palindrome String

↑ Index
Problem Solving
Problem: Check whether a string is a palindrome (madam).
Solution 1: Two pointer (O(1) space) · C++
string s = "madam";
int l = 0, r = s.length() - 1;
bool ok = true;
while(l < r){
    if(s[l] != s[r]){ ok = false; break; }
    l++; r--;
}
cout << (ok ? "Palindrome" : "Not Palindrome");
Solution 2: Reverse & compare · C++
string s = "madam";
string r = s;
reverse(r.begin(), r.end());
cout << (s == r ? "Palindrome" : "Not Palindrome");
148

Largest & Smallest Element of an Array ★★★★★

↑ Index
Problem Solving
Problem: Find the largest and the smallest element of an array.
Solution 1: Single loop (interview best) · C++
int arr[] = {10, 2, 4, 2, 10, 1};
int len = sizeof(arr) / sizeof(arr[0]);

int lrg = arr[0];
int small = arr[0];
for(int i = 1; i < len; i++){
    if(arr[i] > lrg) lrg = arr[i];
    if(arr[i] < small) small = arr[i];
}
cout << lrg << " " << small;   // 10 1
149

Reverse an Array ★★★★★

↑ Index
Problem Solving
Problem: Reverse the elements of an array.
Solution 1: Two pointer [BEST] · C++
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int l = 0, r = n - 1;
while(l < r){
    swap(arr[l], arr[r]);
    l++; r--;
}
for(int i = 0; i < n; i++) cout << arr[i] << " ";
Solution 2: STL reverse · C++
reverse(arr, arr + n);
150

Missing Number (1 to N)

↑ Index
Problem Solving
Problem: Find the missing number in an array containing numbers from 1 to N.
Solution 1: Sum formula [BEST] · C++
int arr[] = {1, 2, 4, 5, 6};
int n = 6;   // range 1..6
int expected = n * (n + 1) / 2;
int actual = 0;
for(int i = 0; i < 5; i++) actual += arr[i];
cout << expected - actual;   // 3
151

Fundamentals

↑ Index
Artificial Intelligence

What is Artificial Intelligence?

It is a technique that makes computers able to think, learn, and make decisions like humans.


What is Machine Learning?

Machine Learning is a subset of AI where a system learns patterns from data and uses those patterns to make predictions or decisions.


What is Deep Learning?

Deep Learning is a subset of Machine Learning that uses multiple neural networks layers to learn more complex patterns from data.


Machine Learning vs Deep Learning?

Traditional Machine Learning often depends more on manually designed features, while Deep Learning can automatically learn useful features from raw data using neural networks.


What is supervised learning?

The model learns from input output pairs. Classification and regression are examples.


What is unsupervised learning?

The model finds hidden structure in data without labels. Clustering and dimensionality reduction are examples.


Classification vs regression? ⭐⭐⭐⭐⭐

Classification predicts a category or class, like pneumonia or normal. Regression predicts a continuous number, like house price.

152

Classical ML Algorithms

↑ Index
Artificial Intelligence

What is linear regression?

It fits a straight line between input features and a numeric output.


What is logistic regression?

It is a classification algorithm. It uses the sigmoid function to output a probability between 0 and 1.


What is a decision tree?

It splits data step by step using questions on features, like a flowchart, until it reaches a prediction.


What is a random forest?

It builds many decision trees on random parts of the data and combines their votes. This reduces overfitting.


What is SVM?

Support Vector Machine finds the boundary that separates classes with the largest possible margin.


What is KNN?

K-Nearest Neighbors classifies a sample by looking at the majority class of its K closest samples.


What is Naive Bayes?

It is a probability-based classifier that uses Bayes' theorem. It assumes features are independent.


What is K-Means clustering?

It groups data into K clusters by moving cluster centers until each point is close to its nearest center.


What is PCA?

Principal Component Analysis reduces the number of features while keeping most of the information (variance).


What is an ensemble method?

It combines multiple models to get better results than a single model. Examples are bagging, boosting, and voting.


Bagging vs boosting?

Bagging trains models in parallel on random samples (Random Forest). Boosting trains models one after another, each fixing the previous errors (XGBoost).


What is feature engineering?

Creating or selecting useful input features to help the model perform better.


What is feature selection?

Choosing only the most useful features and removing irrelevant ones.

153

Neural Network Basics

↑ Index
Artificial Intelligence

What is a neural network?

A neural network is a machine learning model inspired by the structure of the human brain. It consists of interconnected neurons organized into layers that learn patterns from data.


What is a perceptron?

The simplest neural unit. It takes inputs, multiplies them by weights, adds a bias, and applies an activation function.


What is a weight and a bias?

Weights decide how important an input is. Bias shifts the output so the model can fit data better.


What is a hidden layer?

A layer between the input and output layers where the network learns features.


What is a fully connected (dense) layer?

A layer where every neuron is connected to all neurons of the previous layer.


What is an activation function?

An activation function introduces non-linearity into a neural network, allowing it to learn complex patterns. Examples include ReLU, sigmoid, and softmax.


Why ReLU instead of sigmoid in hidden layers?

ReLU is computationally simple and generally provides better gradient behavior for deep networks than sigmoid.


What is Softmax?

Softmax converts a set of model outputs into probabilities whose total sum is 1. It is commonly used for multi-class classification.


What is Sigmoid?

Sigmoid converts an input into a value between 0 and 1. It is commonly used for binary classification or independently predicting multiple labels.


Softmax vs Sigmoid?

Softmax is generally used when choosing one class from multiple mutually exclusive classes. Sigmoid is commonly used for binary classification or multi-label classification where multiple labels can be true at the same time.


What is forward propagation?

Passing input through the network layer by layer to get the output.


What is a gradient?

A gradient tells us how the loss changes with respect to the model's parameters. It is used by optimization algorithms to update the parameters.


What is backpropagation?

Backpropagation calculates how much each model parameter contributed to the prediction error and uses gradients to update the parameters.


What is the vanishing gradient problem?

Gradients become very small in deep networks, so early layers learn very slowly.


What is the exploding gradient problem?

Gradients become very large and make training unstable.


What is weight initialization?

Setting the starting values of weights. Good initialization helps training start well.


What is the difference between parameter and hyperparameter?

Parameters are learned automatically during training, such as neural network weights. Hyperparameters are settings chosen before or during training, such as learning rate, batch size, and number of epochs.


What is a parameter count and why does it matter?

It is the total number of learnable weights. Fewer parameters means a smaller, faster model that is easier to deploy.


What are FLOPs?

The number of floating-point operations needed for one forward pass. It measures computational cost.


What is inference time?

The time the model takes to make a prediction for one sample.

154

Training and Optimization

↑ Index
Artificial Intelligence

What is an epoch?

One epoch means the model has processed the entire training dataset once.


What is batch size?

Batch size is the number of training samples processed before the model updates its parameters.


What is learning rate?

Learning rate controls how much the model's parameters are updated during each optimization step. A very high learning rate can make training unstable, while a very low learning rate can make training very slow.


What is an optimizer?

An optimizer is an algorithm used to update the model's parameters to minimize the loss function. Examples include SGD and Adam.


What is Adam?

Adam is an optimization algorithm that combines ideas from momentum and adaptive learning rates. It is widely used for training deep learning models.


What is AdamW?

A version of Adam that applies weight decay correctly. It is widely used for training transformers.


What is gradient descent?

An optimization method that updates parameters in the direction that reduces the loss.


Batch vs mini-batch vs stochastic gradient descent?

Batch uses all data per update. Stochastic uses one sample. Mini-batch uses a small group (like 32) and is the most common.


What is SGD?

Stochastic Gradient Descent. It updates parameters using one sample or a small batch of data at a time.


What is momentum?

It uses past gradients to make updates smoother and faster.


What is a loss function?

A loss function measures how different the model's prediction is from the actual target. The optimizer tries to minimize this loss during training.


What is cross-entropy loss?

Cross-entropy is commonly used for classification problems. It measures the difference between the actual class distribution and the probability distribution predicted by the model.


Why categorical cross-entropy?

Categorical cross-entropy is suitable for multi-class classification where each sample belongs to one class among multiple classes.


What is label smoothing?

Instead of hard labels like 1 and 0, it uses soft labels like 0.9 and 0.1. This stops the model from being overconfident.


What is a learning rate scheduler?

A method that changes the learning rate during training, usually reducing it over time.


What is ReduceLROnPlateau?

It reduces the learning rate when the validation performance stops improving. It can help the model converge more effectively.


What is early stopping?

Early stopping stops training when validation performance stops improving. It can reduce unnecessary training and help prevent overfitting.


What is a checkpoint?

A saved copy of the model at a certain point in training, usually the best one.


What is gradient clipping?

Limiting the size of gradients to avoid exploding gradients. We used this in the thesis paper.


What is hyperparameter tuning?

Searching for the best settings, like learning rate and batch size. Common methods are grid search and random search.


What is an auxiliary classifier?

An extra classifier attached to an inner part of the model. It gives additional training signals and helps stabilize training. We used it in the thesis paper.

155

Overfitting, Regularization and Transfer Learning

↑ Index
Artificial Intelligence

What is overfitting?

Overfitting occurs when a model learns the training data too closely, including noise, and therefore performs poorly on unseen data.


How do you reduce overfitting?

•        Use more training data

•        Data augmentation

•        Dropout

•        Regularization

•        Early stopping

•        Reduce model complexity

•        Cross-validation

•        Proper train-validation-test splitting


What is underfitting?

Underfitting occurs when the model is too simple to learn the important patterns in the data. As a result, it performs poorly on both training and unseen data.


What is the bias-variance tradeoff?

High bias means the model is too simple (underfitting). High variance means the model is too sensitive to training data (overfitting). We aim for a balance.


What is regularization?

Regularization is a technique used to reduce overfitting by preventing the model from becoming unnecessarily complex. Examples include L1/L2 regularization and dropout.


What is L1 vs L2 regularization?

L1 pushes some weights to exactly zero. L2 makes weights small but not zero.


What is weight decay?

A penalty on large weights. It works as regularization to reduce overfitting.


What is dropout?

Dropout randomly deactivates some neurons during training. It helps prevent the model from depending too much on specific neurons and reduces overfitting.


What is batch normalization?

It normalizes the inputs of a layer across the batch. This makes training faster and more stable.


What is layer normalization?

It normalizes across the features of each single sample. It is used in transformers.


Batch norm vs layer norm?

Batch norm depends on batch statistics and is common in CNNs. Layer norm works per sample and is common in transformers.


What is normalization (of input data)?

Normalization scales input values into a consistent range. For example, in our traffic sign paper, pixel values were normalized between 0 and 1.


What is data augmentation?

Data augmentation creates modified versions of training data to increase data diversity. For images, examples include rotation, zoom, shifting, cropping, and flipping.


Why use data augmentation?

It helps the model learn more robust features and can reduce overfitting by exposing the model to different variations of the training data.


What is transfer learning?

Transfer learning means using knowledge learned from one task or dataset as a starting point for another related task. For example, using an ImageNet-pretrained CNN for traffic sign recognition.


What is fine-tuning?

Fine-tuning means taking a pre-trained model and continuing its training on a target dataset so that it adapts to the new task.


What is feature extraction?

Feature extraction means identifying useful patterns or representations from raw data that help the model perform the target task.

156

Data Splitting and Experiment Setup

↑ Index
Artificial Intelligence

What is validation data?

Validation data is used during model development to monitor performance and tune model settings without using the test set.


What is test data?

Test data is used at the end to evaluate how well the final model performs on unseen data.


Why should test data not be used during training?

If the test data influences model training or tuning, the evaluation becomes biased. The test set should represent unseen data.


What is generalization?

Generalization is the ability of a model to perform well on new, unseen data, not just on the training data.


What is data leakage?

Data leakage happens when information from outside the training data, especially validation or test data, unintentionally influences the training process. It can produce unrealistically high performance.


What is cross-validation?

The data is split into K parts. The model trains on K-1 parts and tests on the remaining part, and this repeats K times. It gives a more reliable estimate of performance.


K-fold vs stratified k-fold?

Stratified k-fold keeps the class ratio the same in every fold. It is useful for imbalanced data.


What is stratified splitting?

It splits the data so each subset has the same class proportion as the original dataset. We used this in our thesis paper.


What is a class imbalance problem?

Some classes have many more samples than others. The model may favor the majority class.


How do you handle class imbalance?

Use class-weighted loss, oversampling, undersampling, data augmentation, and better metrics like F1 and recall. We used class-weighted loss in the pneumonia paper.


What is a baseline model?

A simple or standard model used as a reference to show that the proposed model is better.


What is an ablation study?

Removing or changing parts of the model one by one to see how much each part contributes.

157

Evaluation Metrics

↑ Index
Artificial Intelligence

What is accuracy?

Correct predictions divided by total predictions.


Why is accuracy not enough?

With imbalanced data, a model that always predicts the majority class can still get high accuracy. So we also use precision, recall, and F1.


What is precision?

Precision tells us, among all the samples predicted as positive, how many were actually positive.


What is recall?

Recall tells us, among all the actual positive samples, how many were correctly identified by the model.


What is F1-score?

F1-score is the harmonic mean of precision and recall. It provides a balance between precision and recall.


What is a confusion matrix?

A confusion matrix is a table that shows how many samples were correctly and incorrectly classified for each class. It helps us understand which classes the model confuses with each other.


What is TP?

True Positive means the model predicted positive and the actual class was also positive.


What is FP?

False Positive means the model predicted positive, but the actual class was negative.


What is FN?

False Negative means the model predicted negative, but the actual class was positive.


What is TN?

True Negative means the model predicted negative and the actual class was also negative.


What is specificity?

Among all actual negatives, how many the model correctly identified as negative. Formula: TN / (TN + FP).


What is sensitivity?

Another name for recall. It is how many actual positives were found.


Precision vs recall: which is more important?

It depends on the task. In disease screening, recall is more important because missing a patient is dangerous. In spam detection, precision may matter more.


Macro average vs weighted average?

Macro average takes a simple average over classes. Weighted average gives more weight to classes with more samples.


What are top-1 and top-5 accuracy?

Top-1 means the correct class must be the model's first choice. Top-5 means the correct class must be within the model's five best guesses.


What is the ROC curve?

It plots the true positive rate against the false positive rate at different thresholds.


What is AUC?

Area Under the ROC Curve. A value near 1 means a good model. A value of 0.5 means random guessing.

158

CNN and Computer Vision

↑ Index
Artificial Intelligence

What is CNN?

CNN stands for Convolutional Neural Network. It is a deep learning architecture mainly used for image and computer vision tasks.


Why is CNN good for images?

CNN can automatically learn features such as edges, shapes, textures, and patterns from images.


What is a convolution?

A small filter slides over the image and produces a feature map that highlights patterns.


What is a kernel or filter?

A small matrix of learnable weights (like 3×3) used in convolution.


What is a feature map?

The output of a convolution. It shows where a certain pattern was found.


What is stride?

How many pixels the filter moves at each step.


What is padding?

Adding extra pixels around the image border so the output size is kept or controlled.


What is CNN pooling?

Pooling reduces the spatial dimensions of feature maps while retaining important information. Max pooling keeps the maximum value from a local region.


Max pooling vs average pooling?

Max pooling keeps the largest value in a region. Average pooling keeps the average value.


What is global average pooling?

It takes the average of each entire feature map and gives one value per channel. It reduces parameters and overfitting.


What is flatten?

Converting a multi-dimensional feature map into a 1D vector for dense layers.


What is 1D convolution?

Convolution over a sequence, like text or signals. In our ICCIT paper, we used 1D CNN with kernel sizes 3, 5, and 7.


What is VGG?

A CNN with many stacked 3×3 conv layers. It is simple but has a large number of parameters.


What is ResNet?

A CNN that uses skip (residual) connections, which allow very deep networks to train well.


What is a skip connection?

A shortcut that adds a layer's input to its output. It helps solve the vanishing gradient problem.


What is DenseNet?

A CNN where each layer receives features from all previous layers. This encourages feature reuse.


What is EfficientNet?

A CNN family that scales depth, width, and image resolution together in a balanced way.


What is MobileNet?

A lightweight CNN designed for mobile and low-resource devices. It uses depthwise separable convolutions.


What is ImageNet?

A very large image dataset with over 1000 classes. Many models are pre-trained on it.


Image classification vs detection vs segmentation?

Classification labels the whole image. Detection finds objects and their locations. Segmentation labels each pixel.


What is image resizing and why is it needed?

Making all images the same size, because neural networks need a fixed input size.


What is a spatial attention mechanism?

It gives each location in the feature map a weight between 0 and 1, so the model focuses on important regions. We used it in the pneumonia paper.


What is attention gating?

Multiplying features by the attention map so that unimportant areas are suppressed.


What is feature fusion?

Combining features from different sources, usually by concatenation, to get a richer representation.


What is concatenation?

Joining feature vectors together one after another.

159

Sequence Models, Transformers and BERT

↑ Index
Artificial Intelligence

What is an RNN?

A neural network for sequences. It keeps a hidden state that remembers previous inputs.


What is the problem with RNN?

It struggles with long sequences because of vanishing gradients, and it processes tokens one by one, which is slow.


What is LSTM?

An RNN with gates (input, forget, output) that can remember information for a long time.


What is GRU?

A simpler version of LSTM with fewer gates. It is faster to train.


What is BiLSTM?

An LSTM that reads the sequence in both forward and backward directions.


What is a Transformer?

A Transformer is a neural network architecture that uses attention mechanisms to process relationships between different parts of an input. It is widely used in natural language processing and many other domains.


What is self-attention?

Self-attention allows a model to determine which parts of an input are important in relation to other parts of the same input. In simple terms, it helps the model understand the relationship between different words or tokens in the input.


What is multi-head attention?

Multi-head attention uses multiple attention mechanisms, called heads, to learn different relationships or representations from the input simultaneously.


What are Query, Key, and Value in attention?

Query is what a token is looking for. Key is what each token offers. Value is the actual information. Attention compares the Query with Keys to weight the Values.


What is positional encoding?

Extra information added to embeddings so the Transformer knows the order of tokens.


What are the encoder and decoder in a Transformer?

The encoder understands the input. The decoder generates the output.


What is a feed-forward network in a Transformer?

Two dense layers applied to each token after attention to add more non-linearity.


What is a residual connection in a Transformer?

The input of a sublayer is added to its output. This helps stable training.


Why are Transformers better than RNNs?

They process all tokens in parallel, capture long-range relationships using attention, and train faster.


What is BERT?

BERT stands for Bidirectional Encoder Representations from Transformers. It is a Transformer-based language model designed to learn contextual representations of text.


Why is BERT called bidirectional?

Because it considers information from both the left and right context of a token when learning its representation.


What is masked language modeling?

BERT hides some words in a sentence and learns to predict them. This is how BERT is pre-trained.


What is the [CLS] token?

A special token at the start of the input. Its final representation is often used for classification.


What is pooled output in BERT?

A single vector for the whole sentence, usually made from the [CLS] token.


What is BioBERT?

BioBERT is a BERT-based language model that is pre-trained on biomedical text. It is designed for biomedical natural language processing tasks.


What is ClinicalBERT?

A BERT model pre-trained on clinical notes, such as hospital records.


What is DistilBERT?

A smaller and faster version of BERT made by knowledge distillation. It keeps most of the performance.


What is GPT and how is it different from BERT?

GPT is a decoder-based model that generates text left to right. BERT is encoder-based and learns from both directions.


What is a pre-trained language model?

A model trained on a large text corpus, then adapted to a specific task.


Pre-training vs fine-tuning?

Pre-training learns general language knowledge from huge data. Fine-tuning adapts the model to a specific task using a smaller dataset.


What is domain adaptation?

Adjusting a model so it works well in a specific field, like biomedical text.


What is knowledge distillation?

A small "student" model learns to mimic a large "teacher" model. This makes the model smaller.


What is model compression?

Reducing model size using pruning, quantization, or distillation.


What is quantization?

Using lower-precision numbers (like 8-bit instead of 32-bit) to make the model smaller and faster.


What is pruning?

Removing unimportant weights or neurons from a model.

160

Natural Language Processing Basics

↑ Index
Artificial Intelligence

What is NLP?

Natural Language Processing is the field of AI that helps computers understand and generate human language.


What is tokenization?

Splitting text into smaller units (tokens) such as words or subwords.


What is WordPiece tokenization?

A subword method used by BERT. Rare words are split into smaller pieces, so unknown words can still be handled.


What is a vocabulary?

The set of all tokens a model knows.


What are padding and truncation in NLP?

Padding adds special tokens to short sequences. Truncation cuts long sequences to a fixed length (we used 128 tokens).


What is an attention mask?

A tensor that tells the model which tokens are real (1) and which are padding (0).


What is an embedding?

An embedding is a numerical representation of an object such as a word, token, or image feature. It allows the model to work with meaningful numerical representations.


Static vs contextual embeddings?

Static embeddings (Word2Vec, GloVe) give one vector per word. Contextual embeddings (BERT) give different vectors depending on the sentence.


What is Word2Vec?

A method that learns word vectors so similar words are close together.


What is GloVe?

Word embeddings learned from word co-occurrence statistics across a large text corpus.


What is Bag of Words?

Represents text by word counts, ignoring order.


What is TF-IDF?

A score that gives high weight to words that are frequent in one document but rare across all documents.


What is an n-gram?

A sequence of n consecutive words, like a bigram (2 words).


What are stop words?

Very common words like "the", "is", "and" that are sometimes removed.


Stemming vs lemmatization?

Stemming cuts words to a rough root ("running" → "run"). Lemmatization uses a dictionary to get the proper base form ("better" → "good").


What is Named Entity Recognition (NER)?

Finding and labeling names, such as diseases, genes, or drugs, in text.


What is text classification?

Assigning a category label to a text, such as symptom text to a disease.


What is WordNet?

A large English database that groups words into sets of synonyms.


What is synonym replacement in text augmentation?

Replacing words with their synonyms (using WordNet) to create new training samples with the same meaning.


What is random word swap?

Randomly changing the position of words in a sentence to create variation.

161

Explainable AI

↑ Index
Artificial Intelligence

What is XAI?

XAI stands for Explainable Artificial Intelligence. It helps us understand why an AI model makes a particular prediction.


Why is XAI important?

XAI improves transparency and helps researchers understand the model's behavior. It is especially useful in sensitive domains such as healthcare and safety-critical systems.


What is model interpretability?

Model interpretability refers to how easily humans can understand how or why a model produces its predictions.


What is a black-box model?

A model whose internal decision process is hard for humans to understand.


What is a post-hoc explanation?

An explanation created after the model is trained, without changing the model.


What is a model-agnostic method?

A method that works with any model type, such as LIME and SHAP.


Global vs local explanation?

Global explains the overall model behavior. Local explains one single prediction.


What is Grad-CAM?

Grad-CAM generates a heatmap showing the image regions that contributed most to a CNN's prediction.


What is LIME?

LIME explains an individual prediction by perturbing parts of the input and observing how the prediction changes.


What is SHAP?

SHAP explains predictions by giving each feature a score based on its contribution. It is based on Shapley values from game theory.


LIME vs SHAP?

LIME builds a simple local model around one prediction. SHAP gives a fairer, theory-based feature contribution. SHAP is usually slower but more consistent.


What is a gradient-based explanation?

It uses the gradient of the output with respect to the input to see which input parts affect the prediction the most.


What is a heatmap in XAI?

A colored overlay that shows which regions of an image were most important for the prediction.


What does a negative SHAP or LIME score mean?

That feature decreases the probability of the predicted class.


Does explainability mean the model is correct?

No. Explanations show what the model used, not whether it is medically or causally correct.