Show 25 50 100
PDF

Index

  1. Hash Table
  2. Binary Tree and Traversals
  3. Binary Search Tree (BST)
  4. Heap and Priority Queue
  5. Graph
  6. Trie
  7. Time and Space Complexity (Big-O)
  8. Recursion
  9. Algorithm Design Techniques
  10. BFS and DFS
  11. Dijkstra's Shortest Path
  12. Minimum Spanning Tree (Kruskal, Prim)
  13. Dynamic Programming
  14. Two Pointers and Sliding Window
  15. Backtracking
  16. Linear Search
  17. Binary Search
  18. lower_bound and upper_bound
  19. Search Algorithms Comparison
  20. Sorting Algorithms Comparison
  21. Bubble Sort
  22. Selection Sort
  23. Insertion Sort
  24. Merge Sort
  25. Quick Sort
  26. Heap Sort
  27. Counting Sort
  28. C# and .NET Basics
  29. Value Types vs Reference Types
  30. Classes, Properties and Constructors
  31. Inheritance, Interface and Abstract Class in C#
  32. Collections and Generics
  33. LINQ
  34. Exception Handling in C#
  35. Delegates, Events and Lambdas
  36. async and await
  37. Garbage Collection in .NET
  38. C# Keywords Quick Reference
  39. JDK, JRE and JVM
  40. Java Data Types and Wrapper Classes
  41. String, StringBuilder and StringBuffer
  42. OOP in Java
  43. Exception Handling in Java
  44. Java Collections Framework
  45. Multithreading in Java
  46. static and final in Java
  47. Java 8 Features: Lambda and Streams
  48. Java Memory and Garbage Collection
  49. DBMS and RDBMS
  50. Keys in DBMS
51 Index

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++ 4 lines
unordered_map<string, int> freq;
for (string w : {"a", "b", "a", "c", "a"})
    freq[w]++;
cout << freq["a"];   // 3
52 Index

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++ 22 lines
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 Index

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++ 14 lines
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 Index

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++ 6 lines
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 Index

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++ 8 lines
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 Index

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++ 21 lines
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 Index

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++ 6 lines
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 Index

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++ 17 lines
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 Index
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 Index

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++ 12 lines
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++ 6 lines
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 Index

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++ 17 lines
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 Index

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++ 18 lines
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 Index

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++ 11 lines
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++ 8 lines
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++ 9 lines
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 Index

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

Two pointers C++ 10 lines
// 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++ 11 lines
// 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++ 8 lines
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 Index

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++ 11 lines
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++ 4 lines
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 Index

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

C++ 5 lines
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 Index

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++ 10 lines
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++ 7 lines
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 Index

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

C++ 5 lines
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)
70 Index
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 Index

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++ 12 lines
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 Index

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

C++ 8 lines
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 Index

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++ 11 lines
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 Index

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++ 17 lines
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 Index

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++ 16 lines
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 Index

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++ 18 lines
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 Index

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

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# 14 lines
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 Index
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# 9 lines
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 Index
C# 24 lines
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 Index

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# 25 lines
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 Index
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# 11 lines
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 Index

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

C# 16 lines
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 Index
C# 19 lines
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 Index

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# 13 lines
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 Index

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

C# 11 lines
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 Index

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 Index
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# 5 lines
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 Index

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 7 lines
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 Index
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 10 lines
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 Index
StringStringBuilderStringBuffer
ImmutableMutableMutable
Thread-safe (because immutable)Not thread-safeThread-safe (synchronized)
Slow for many changesFastestSlower than StringBuilder
Java 10 lines
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 Index
Java 17 lines
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 Index
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 19 lines
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 Index

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 9 lines
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 Index

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 16 lines
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 Index
  • 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 6 lines
class Config {
    static final double PI = 3.1416;   // constant
    static int instances;
    static { System.out.println("class loaded"); }
    Config() { instances++; }
}
97 Index

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 12 lines
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 Index
  • 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 Index

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 Index
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 19 lines
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
);