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

All Topics

4+ stars · 48 topics · 28 Nov 2026
1

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;
}
2

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

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

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

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.

6

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
7

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

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

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
10

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

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

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

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);
    }
}
14

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.

15

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.

16

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);
}
17

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];
}
18

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

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

20

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

21

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

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.

23

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());
24

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

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

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

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

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
);
29

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

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.

31

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.

32

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
33

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

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

35

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

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

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

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.

39

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
40

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.

41

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

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
43

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;
}
44

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

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

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

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
48

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);