Docsity

CS Master Study Guide 2026: Data Structures, Algorithms, OOP & AI/ML, Study notes of Computer Science

Toggle sidebar
bg1
■ COMPUTER SCIENCE
MASTER STUDY GUIDE
Complete Notes for Data Structures, Algorithms, OOP, OS & AI/ML
✦ DATA STRUCTURES & ALGORITHMS ✦ OBJECT-ORIENTED PROGRAMMING
✦ OPERATING SYSTEMS ✦ ARTIFICIAL INTELLIGENCE & ML
✦ SYSTEMS DESIGN ✦ EXAM PREP & CHEAT SHEETS
2026 Edition | University-Level Comprehensive Notes | Exam-Ready Format
FEATURES INCLUDED
✓ Visual diagrams & flowcharts for every concept
✓ Time & space complexity analysis (Big-O)
✓ Python & pseudocode examples
✓ Common exam questions with model answers
✓ Cheat sheets & quick reference tables
✓ Real-world application examples
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download CS Master Study Guide 2026: Data Structures, Algorithms, OOP & AI/ML and more Study notes Computer Science in PDF only on Docsity!

n COMPUTER SCIENCE

MASTER STUDY GUIDE

Complete Notes for Data Structures, Algorithms, OOP, OS & AI/ML

F DATA STRUCTURES & ALGORITHMS F OBJECT-ORIENTED PROGRAMMING

F OPERATING SYSTEMS F ARTIFICIAL INTELLIGENCE & ML

F SYSTEMS DESIGN F EXAM PREP & CHEAT SHEETS

2026 Edition | University-Level Comprehensive Notes | Exam-Ready Format

FEATURES INCLUDED

3 Visual diagrams & flowcharts for every concept

3 Time & space complexity analysis (Big-O)

3 Python & pseudocode examples

3 Common exam questions with model answers

3 Cheat sheets & quick reference tables

3 Real-world application examples

n TABLE OF CONTENTS

    1. Data Structures & Algorithms
    • 1.1 Arrays & Linked Lists
    • 1.2 Stacks & Queues
    • 1.3 Trees & Binary Search Trees
    • 1.4 Heaps & Priority Queues
    • 1.5 Hash Tables
    • 1.6 Graphs & Graph Algorithms
    • 1.7 Sorting Algorithms
    • 1.8 Searching Algorithms
    1. Object-Oriented Programming
    • 2.1 OOP Principles (SOLID)
    • 2.2 Design Patterns
    • 2.3 UML Diagrams
    1. Operating Systems
    • 3.1 Process Management
    • 3.2 Memory Management
    • 3.3 File Systems & I/O
    1. Artificial Intelligence & Machine Learning
    • 4.1 AI Fundamentals
    • 4.2 Machine Learning Algorithms
    • 4.3 Deep Learning & Neural Networks
    1. Systems Design & Architecture
    1. Exam Cheat Sheets & Quick Reference

KEY CONCEPT — Queue Variants:

Standard Queue: enqueue at rear, dequeue at front — O(1) both Deque (Double-ended): O(1) add/remove at both ends Priority Queue: Elements ordered by priority (usually implemented with a heap) Circular Queue: Fixed-size array with wrap-around to avoid wasted space

Python — Stack using list:

stack = [] stack.append(10) # push stack.append(20) top = stack[-1] # peek element = stack.pop() # pop — returns 20

Python — Queue using collections.deque:

from collections import deque queue = deque() queue.append(10) # enqueue at rear queue.append(20) front = queue.popleft() # dequeue from front — returns 10 # deque provides O(1) for both ends! nn COMMON MISTAKE: Using a regular Python list as a queue (queue.pop(0)) is O(n) because all elements must shift. Always use collections.deque for queues.

1.3 Trees & Binary Search Trees

A tree is a hierarchical structure with a root and children. A Binary Search Tree (BST) is a binary tree where left < node < right, enabling O(log n) search in balanced trees.

KEY CONCEPT — BST Properties:

  • Left subtree contains only values < node • Right subtree contains only values > node • Both subtrees are also BSTs • In-order traversal yields sorted sequence Time Complexity (balanced BST): Search: O(log n) | Insert: O(log n) | Delete: O(log n) Time Complexity (skewed/degenerate): All operations: O(n) — becomes a linked list!

Python — BST Insert & Search:

class TreeNode: def init(self, val): self.val = val self.left = None self.right = None def insert(root, val): if not root: return TreeNode(val) if val < root.val: root.left = insert(root.left, val) else: root.right = insert(root.right, val) return root def search(root, val): if not root or root.val == val: return root if val < root.val: return search(root.left, val) return search(root.right, val) # O(log n) avg, O(n) worst

Tree Traversals (memorize these!):

Pre-order: Root → Left → Right (used for copying trees) In-order: Left → Root → Right (gives sorted order for BST) Post-order: Left → Right → Root (used for deleting trees) Level-order: BFS using queue (used for shortest path in unweighted trees)

n EXAM TIP: For BST deletion, remember the 3 cases: (1) leaf node — just remove, (2) one child — replace with child, (3) two children — replace with in-order successor (smallest in right subtree) or predecessor (largest in left subtree).

1.4 Heaps & Priority Queues

A heap is a complete binary tree satisfying the heap property: Max Heap — parent ≥ children; Min Heap — parent ≤ children. Used for priority queues, heap sort, and finding k-th largest elements.

KEY CONCEPT — Heap Operations:

Operation Time Description

Insert O(log n) Add at end, bubble up (heapify-up)

Extract Max/Min O(log n) Remove root, replace with last, bubble down

Peek Max/Min O(1) Root is always max/min

Build Heap O(n) Heapify all elements (not n log n!)

Heap Sort O(n log n) Extract all elements one by one

Python — Heap using heapq (min-heap by default):

1.5 Hash Tables

Hash tables provide average O(1) insert, delete, and lookup by mapping keys to array indices using a hash function. The key challenge is collision resolution.

KEY CONCEPT — Collision Resolution Methods:

1. Chaining: Each bucket is a linked list. Simple, but degrades to O(n) if many collisions. 2. Open Addressing: Find next empty slot using probing: • Linear probing: h(k) + i — causes clustering • Quadratic probing: h(k) + i² — reduces clustering • Double hashing: h(k) + i·hn(k) — best distribution Load Factor ( α ) = n/m where n = items, m = buckets • Chaining: keep α < 1 for good performance • Open addressing: keep α < 0.75 to avoid excessive probing

Python — Dictionary (hash table):

Python dict is a hash table with open addressing my_dict = {} my_dict['key'] = 'value'

val = my_dict.get('key', 'default') # O(1) average # Hash function behavior hash('hello')

Deterministic for strings in a session # Set is also a hash table (only keys, no

values) my_set = set() my_set.add(10) # O(1) average # Important: mutable objects (lists, dicts) CANNOT be keys! # my_dict[[1,2]] = 'x' # TypeError: unhashable type nn COMMON MISTAKE: Assuming hash table operations are always O(1). In the worst case (all keys collide), complexity degrades to O(n). Good hash functions and load factor management are critical.

1.6 Graphs & Graph Algorithms

Graphs model relationships between objects. Directed vs Undirected , Weighted vs Unweighted , Cyclic vs Acyclic (DAG). Represented as Adjacency Matrix or Adjacency List.

KEY CONCEPT — Graph Representations:

Representation Space Add Edge Check Edge Iterate Neighbors

Adjacency Matrix O(V²) O(1) O(1) O(V)

Adjacency List O(V + E) O(1) O(degree(v)) O(degree(v))

BFS vs DFS — When to use each:

BFS (Breadth-First Search): • Uses a queue — explores level by level • Finds shortest path in unweighted graphs • Use for: shortest path, level-order traversal, web crawling DFS (Depth-First Search): • Uses a stack (recursion) — explores deep before wide • Good for: topological sort, cycle detection, connected components • Use for: maze solving, backtracking problems

Python — BFS & DFS:

from collections import deque, defaultdict # BFS — shortest path in unweighted graph def bfs(graph, start, target): visited = set([start]) queue = deque([(start, 0)]) # (node, distance) while queue: node, dist = queue.popleft() if node == target: return dist for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append((neighbor, dist + 1)) return -1 # Not found # DFS — with recursion def dfs(graph, node, visited): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: dfs(graph, neighbor, visited)

Dijkstra's Algorithm — shortest path in weighted graphs with non-negative edges. Uses a priority queue (min-heap). Time: O((V + E) log V).

import heapq def dijkstra(graph, start): dist = {node: float('inf') for node in graph} dist[start] = 0 pq = [(0, start)] # (distance, node) while pq: d, node = heapq.heappop(pq) if d > dist[node]: continue # Skip outdated entries for neighbor, weight in graph[node]: new_dist = d + weight if new_dist < dist[neighbor]: dist[neighbor] = new_dist heapq.heappush(pq, (new_dist, neighbor)) return dist n EXAM TIP: Dijkstra fails with negative edge weights! Use Bellman-Ford (O(VE)) for graphs with negative edges, or Floyd-Warshall (O(V³)) for all-pairs shortest paths.

1.8 Searching Algorithms

Linear Search: O(n) — check every element. Binary Search: O(log n) — requires sorted array. Binary Search is the most important search algorithm for interviews.

Python — Binary Search (iterative):

def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left) // 2 # Avoid overflow! if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 # Not found # Variation: find first occurrence def binary_search_first(arr, target): left, right = 0, len(arr) - 1 result = -1 while left <= right: mid = left + (right - left) // 2 if arr[mid] == target: result = mid right = mid - 1 # Keep searching left elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return result n EXAM TIP: Use left + (right - left) // 2 instead of (left + right) // 2 to prevent integer overflow in languages with fixed-size integers (Java, C++). Python handles big ints, but interviewers expect the safe version.

Binary Search on Answer (Advanced):

Many problems can be solved by binary searching the answer space rather than the array itself. Examples: finding minimum maximum subarray sum, allocating books to students, aggressive cows problem.

def is_valid(arr, max_sum, k): # Can we split arr into k subarrays with max sum <= max_sum? count = 1 current_sum = 0 for num in arr: if current_sum + num <= max_sum: current_sum += num else: count += 1 current_sum = num return count <= k def split_array(arr, k): left, right = max(arr), sum(arr) while left < right: mid = left + (right - left) // 2 if is_valid(arr, mid, k): right = mid else: left = mid + 1 return left nn COMMON MISTAKE: Off-by-one errors in binary search. Remember: while left <= right for finding exact match; while left < right for finding boundary (lower/upper bound).

2. OBJECT-ORIENTED PROGRAMMING

OOP is the dominant programming paradigm. Master these principles for software design

interviews and architecture questions.

2.1 OOP Principles (SOLID)

The SOLID principles are the foundation of clean, maintainable object-oriented design. Every software engineer should know these.

Principle Definition Key Idea

S - Single Responsibility A class should have one reason to change One class = one job

O - Open/Closed Open for extension, closed for modification Use inheritance/interfaces

L - Liskov Substitution Subtypes must be substitutable for base typesSquare IS-NOT-A Rectangle!

I - Interface Segregation Clients should not depend on unused interfacesSplit fat interfaces

D - Dependency Inversion Depend on abstractions, not concretions Use interfaces/abstract classes

Python - Demonstrating SOLID Principles:

from abc import ABC, abstractmethod # S - Single Responsibility: Report class only generates reports class Report: def generate(self, data): return f"Report: {data}" # O - Open/Closed: Extend via inheritance, do not modify class PDFReport(Report): def generate(self, data): return f"PDF Report: {data}" class HTMLReport(Report): def generate(self, data): return f"HTML Report: {data}" # D - Dependency Inversion: Depend on abstractions class ReportPrinter: def init(self, report: Report): self.report = report def print_report(self, data): print(self.report.generate(data)) # L - Liskov Substitution: Any Report subclass works printer = ReportPrinter(PDFReport()) printer.print_report("Sales Q3") # Works!

Four Pillars of OOP:

1. Encapsulation: Bundle data and methods; hide internal state using private/protected access modifiers. 2. Abstraction: Show only essential features; hide implementation details (abstract classes, interfaces). 3. Inheritance: Create new classes from existing ones (IS-A relationship). Promotes code reuse. 4. Polymorphism: Same interface, different implementations. Method overriding (runtime) vs method overloading (compile-time).

EXAM TIP: Know the difference between composition (HAS-A) and inheritance (IS-A). Favor composition over inheritance - it is more flexible and avoids fragile base class problems.

2.2 Design Patterns

call - Dashed arrow: Return message - Activation bar: Object is active/processing Use Case Diagram: Shows system functionality from user perspective. - Actor (stick figure) -> Use Case (oval) -> System boundary (rectangle) Activity Diagram: Shows workflow/process flow. Like a flowchart with swimlanes.

Common UML Relationships:

Relationship Symbol Meaning Example

Inheritance -->> IS-A relationship Dog IS-A Animal

Association -- Uses/knows about Student knows Professor

Aggregation o-- Weak HAS-A (can exist alone) Department HAS Professors

Composition *-- Strong HAS-A (cannot exist alone) Car HAS Engine

Dependency .->> Uses temporarily Person uses Calculator

Realization .->> Implements interface Printer implements IPrintable

3. OPERATING SYSTEMS

OS manages hardware resources and provides services to applications. Critical for system

design interviews and understanding how computers work at the low level.

3.1 Process Management

A process is a program in execution. A thread is the smallest unit of execution within a process. Understanding the difference is crucial.

KEY CONCEPT - Process vs Thread:

Aspect Process Thread

Memory Separate address space Shares address space

Overhead High (context switch expensive) Low (context switch cheap)

Communication IPC (pipes, sockets, shared memory) Direct shared memory

Crash Impact Isolated - does not affect others Can crash entire process

Creation Slow (fork/CreateProcess) Fast (pthread_create)

Data Sharing Must use IPC mechanisms Automatic via shared memory

Process States:

New -> Ready: Process created, waiting for CPU Ready -> Running: Scheduler dispatches process Running -> Waiting: Process requests I/O or resource Waiting -> Ready: I/O completes, resource available Running -> Ready: Time quantum expires (preemption) Running -> Terminated: Process completes or is killed Scheduler Types: - FCFS (First Come First Served): Simple, but convoy effect (short jobs wait behind long ones) - SJF (Shortest Job First): Optimal for average waiting time, but needs prediction - Priority Scheduling: Higher priority runs first; starvation possible - Round Robin: Time quantum q; each process gets q time; good for time-sharing - Multilevel Queue: Different queues for different job types - Multilevel Feedback Queue: Processes can move between queues based on behavior

Python - Multithreading (GIL limits true parallelism):

import threading import time def worker(num): print(f"Thread {num} starting") time.sleep(1) print(f"Thread {num} done") threads = [] for i in range(5): t = threading.Thread(target=worker, args=(i,)) threads.append(t) t.start() for t in threads: t.join() # Wait for all to complete # For CPU-bound tasks, use multiprocessing instead! from multiprocessing import Pool def cpu_task(n): return sum(i * i for i in range(n)) with Pool(4) as p: results = p.map(cpu_task, [1000000] * 4) WARNING: Python's Global Interpreter Lock (GIL) prevents true parallel execution of threads for CPU-bound tasks. Use multiprocessing for CPU-bound work and threading only for I/O-bound tasks.

FCFS: First Come First Served - fair, but poor performance SSTF: Shortest Seek Time First - minimizes head movement; starvation possible SCAN (Elevator): Moves back and forth across disk - good average, no starvation C-SCAN: Circular SCAN - returns to start without servicing; more uniform wait times LOOK: Like SCAN but only goes to last request in each direction - more efficient C-LOOK: Circular LOOK - most practical modern algorithm

EXAM TIP: SCAN/Elevator is the classic answer for disk scheduling. C-LOOK is the most practical modern choice. Remember: seek time dominates, so minimizing head movement is the goal.

4. ARTIFICIAL INTELLIGENCE & MACHINE

LEARNING

AI and ML are the fastest-growing fields in CS. These notes cover fundamentals that appear

in every AI course and technical interview.

4.1 AI Fundamentals

Artificial Intelligence is the simulation of human intelligence by machines. Machine Learning is a subset of AI where systems learn from data without explicit programming. Deep Learning uses neural networks with many layers.

KEY CONCEPT - Types of Machine Learning:

Type Description Examples Algorithms

Supervised Labeled data: input-output pairs Spam detection, price prediction Linear Regression, SVM, Decision Trees, Neur

Unsupervised Unlabeled data: find patterns Customer segmentation, anomaly detectionK-Means, PCA, DBSCAN, Autoencoders

Reinforcement Agent learns via rewards/penalties Game playing, robotics, self-driving Q-Learning, Policy Gradient, DQN

Semi-Supervised Mix of labeled and unlabeled When labeling is expensive Self-training, Co-training

Key AI Concepts:

Agent: An entity that perceives its environment and acts upon it. Components: sensors (perceive), actuators (act), and agent function (decision making). Search Algorithms: - Uninformed: BFS, DFS, UCS (Uniform Cost Search), DLS (Depth-Limited), IDS (Iterative Deepening) - Informed: A* (best for pathfinding), Greedy Best-First, IDA* A Algorithm:* f(n) = g(n) + h(n) - g(n) = cost from start to n - h(n) = heuristic estimate from n to goal - Admissible heuristic: h(n) never overestimates (guarantees optimal) - Consistent heuristic: h(n) <= cost(n to n') + h(n') (guarantees optimal with graph search) Knowledge Representation: - Propositional Logic: True/False statements with AND, OR, NOT, IMPLIES - First-Order Logic: Adds quantifiers (FORALL, EXISTS) and predicates - Bayesian Networks: Probabilistic graphical models for reasoning under uncertainty

Python - A Search:*

import heapq def astar(graph, start, goal, heuristic): open_set = [(0, start)] # (f_score, node) g_score = {start: 0} came_from = {} while open_set: _, current = heapq.heappop(open_set) if current == goal: # Reconstruct path path = [current] while current in came_from: current = came_from[current] path.append(current) return path[::-1] for neighbor, cost in graph[current]: tentative_g = g_score[current] + cost if neighbor not in g_score or tentative_g < g_score[neighbor]: came_from[neighbor] = current g_score[neighbor] = tentative_g f_score = tentative_g + heuristic(neighbor, goal) heapq.heappush(open_set, (f_score, neighbor)) return None EXAM TIP: A* is optimal if the heuristic is admissible. The better the heuristic, the faster A* runs. A perfect heuristic would make A* run in O(d) where d is the solution depth.

Overfitting: - Cross-validation: K-fold CV to estimate generalization - Regularization: L1 (Lasso - sparse), L (Ridge - small weights), Elastic Net (both) - More data: Reduces variance - Feature selection: Remove irrelevant features - Early stopping: Stop training when validation loss increases - Dropout: Randomly disable neurons during training (neural networks) - Ensemble methods: Bagging (Random Forest), Boosting (XGBoost, AdaBoost)

WARNING: Always split data into train/validation/test sets. Never evaluate on test data during model selection. Use validation set for hyperparameter tuning. Test set is only for final evaluation.

4.3 Deep Learning & Neural Networks

Neural Networks are inspired by biological neurons. Deep Learning uses networks with many hidden layers to learn hierarchical representations.

KEY CONCEPT - Neural Network Basics:

Perceptron: y = activation(w*x + b) - Input layer: receives features - Hidden layers: learn representations - Output layer: produces predictions Activation Functions: - Sigmoid: 1/(1+e^-x) - maps to (0,1). Vanishing gradient problem. - ReLU: max(0, x) - most popular. Fast, no vanishing gradient. Dying ReLU problem. - Leaky ReLU: max(ax, x) where a=0.01 - fixes dying ReLU. - Tanh: maps to (-1,1). Zero-centered but still vanishing gradient. - Softmax: e^x_i / sum(e^x_j) - for multi-class output probabilities. Backpropagation: Chain rule applied to compute gradients through the network. 1. Forward pass: compute predictions 2. Compute loss 3. Backward pass: compute gradients (chain rule) 4. Update weights: W_new = W_old - lr * gradient Gradient Descent Variants: - Batch GD: Uses entire dataset - stable but slow - Stochastic GD (SGD): Uses one sample

  • fast but noisy - Mini-batch GD: Uses small batch (32-512) - best of both worlds - Adam: Adaptive learning rates with momentum - most popular optimizer

Python - Simple Neural Network (NumPy):

import numpy as np class NeuralNetwork: def init(self, layers): # layers = [input_size, hidden1, hidden2, ..., output_size] self.weights = [] self.biases = [] for i in range(len(layers) - 1): self.weights.append(np.random.randn(layers[i], layers[i+1]) * 0.01) self.biases.append(np.zeros((1, layers[i+1]))) def relu(self, x): return np.maximum(0, x) def relu_derivative(self, x): return (x > 0).astype(float) def softmax(self, x): exp_x = np.exp(x - np.max(x, axis=1, keepdims=True)) return exp_x / np.sum(exp_x, axis=1, keepdims=True) def forward(self, X): self.activations = [X] self.z_values = [] for i in range(len(self.weights) - 1): z = np.dot(self.activations[-1], self.weights[i]) + self.biases[i] self.z_values.append(z) self.activations.append(self.relu(z)) # Output layer z = np.dot(self.activations[-1], self.weights[-1]) + self.biases[-1] self.z_values.append(z) self.activations.append(self.softmax(z)) return self.activations[-1] def backward(self, X, y, learning_rate): m = X.shape[0] # Output layer gradient (softmax + cross-entropy) dz = self.activations[-1] - y for i in range(len(self.weights) - 1, -1, -1): dw = np.dot(self.activations[i].T, dz) / m db = np.sum(dz, axis=0, keepdims=True) / m if i > 0: dz = np.dot(dz, self.weights[i].T) * self.relu_derivative(self.z_values[i-1]) self.weights[i] -= learning_rate * dw self.biases[i] -= learning_rate * db

Key Deep Learning Architectures:

CNN (Convolutional Neural Network): - For image data - Convolution layers: detect features (edges, textures, patterns) - Pooling layers: reduce spatial dimensions - Fully connected layers: final classification - Key concepts: filters/kernels, stride, padding, feature maps RNN (Recurrent Neural Network): - For sequential data (text, time

series) - Maintains hidden state across time steps - Problems: Vanishing/exploding gradients for long sequences LSTM (Long Short-Term Memory): - Special RNN with gates (input, forget, output) - Solves vanishing gradient problem - Can remember long-term dependencies Transformer: - Attention mechanism: focuses on relevant parts of input - Self-attention: each token attends to all other tokens - Parallel processing (unlike RNNs) - Foundation of GPT, BERT, and all modern LLMs - Key components: Multi-head attention, positional encoding, feed-forward layers

EXAM TIP: Understand why each architecture exists. CNNs use locality and translation invariance for images. RNNs/LSTMs model sequential dependencies. Transformers use self-attention to capture global dependencies in parallel. This is the #1 interview question in deep learning.