# CS Fundamentals and Placement Prep roadmap

> DSA, core CS subjects (OS, networks, DBMS), OOP, low-level and system design, and interview strategy for internships and placements.

Canonical: https://www.internhack.in/roadmaps/tracks/cs-fundamentals
Last updated: 2026-11-28

18 sections, 86 topics, about 541 hours.

A complete path for students preparing for SDE internships and campus or off-campus placements. You start by mastering one language for problem solving and the math behind common tricks, then work through every major data structure and algorithm pattern asked in coding rounds, from two pointers and binary search to graphs and dynamic programming. Next you cover the core CS subjects that appear in technical interviews and online assessments: operating systems, computer networks, DBMS and (optionally) computer architecture. The design half teaches object-oriented principles, SOLID and design patterns, low-level design and machine coding rounds, and high-level system design with caching, sharding, queues and classic case studies. The track ends with the practical side of getting hired: resume, projects, online assessments, live interview technique, behavioral rounds, mock interviews and company-specific preparation.

## Outcomes

- Solve medium LeetCode-style problems in 30 minutes by recognising patterns across arrays, trees, graphs and dynamic programming
- Explain OS, computer networks and DBMS concepts confidently in technical interviews and MCQ assessments
- Write clean object-oriented code that applies SOLID and common design patterns
- Design and code LLD and machine coding problems like a parking lot, Splitwise or a rate limiter
- Lead a high-level system design discussion with estimates, caching, sharding, queues and clear trade-offs
- Present a strong resume and projects, and handle online assessments, behavioral and HR rounds
- Run a structured preparation plan with mocks and company-specific research for internships and placements

## Prerequisites

- Basic programming in any language (variables, loops, functions, arrays)
- School-level mathematics
- A computer where you can install a compiler or interpreter

## Your Problem-Solving Toolkit

Choose one language for DSA and master its standard library, learn to reason about cost with Big-O, and keep your work in Git from day one.

### C++ for DSA

recommended · beginner · about 20 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/cpp-for-dsa

Learn the slice of modern C++ that matters for interviews and contests: fast I/O, references, the STL containers and algorithms, and common gotchas.

C++ is the most common language in Indian placement rounds and competitive programming because it is fast, has a rich standard library (the **STL**) and gives you precise control over memory. You do not need all of C++; you need a focused subset that you can write without thinking.

#### What to actually learn
- Basics: types (`int`, `long long`, `double`, `char`, `bool`), overflow limits (int is about 2.1e9, long long about 9.2e18), loops, functions.
- **References vs copies**: pass big containers as `const vector<int>& v`. Passing by value copies the whole vector and can turn an O(n) solution into TLE.
- STL containers: `vector`, `string`, `pair`, `array`, `stack`, `queue`, `deque`, `priority_queue`, `set`/`map` (balanced BST, O(log n)), `unordered_set`/`unordered_map` (hash, O(1) average).
- STL algorithms: `sort` with custom comparators or lambdas, `lower_bound`/`upper_bound`, `reverse`, `accumulate`, `max_element`, `next_permutation`.
- Fast I/O: `ios::sync_with_stdio(false); cin.tie(nullptr);` for contests.

#### Common pitfalls
- Computing `a * b` in `int` before assigning to `long long` still overflows; cast first.
- `v.size()` is unsigned, so `v.size() - 1` on an empty vector wraps to a huge number.
- `map[key]` inserts a default value if the key is missing; use `count` or `find` to test membership.

Good enough to move on: you can implement a frequency count with `unordered_map`, sort pairs by second element with a lambda, and use a min-heap via `priority_queue<int, vector<int>, greater<int>>` without looking anything up.

Key concepts: Types, overflow and long long, References and const correctness, vector, string, pair, set, map, multiset, unordered_map and unordered_set, stack, queue, deque, priority_queue, sort, lambdas and comparators, lower_bound and upper_bound, Fast I/O and contest template, Iterators and auto.

Mini project: Write a reusable contest template, then solve 6 warm-ups using only STL: count word frequencies, sort students by marks then name, find the k largest numbers with a heap, remove duplicates with set, check anagrams with a frequency array, and answer 'first element >= x' queries with lower_bound.

Self-check: Why can passing a vector<int> by value inside a recursive function cause a Time Limit Exceeded verdict, and how do you fix it?

Resources:
- [LearnCpp.com](https://www.learncpp.com/) (LearnCpp)
- [C++ reference](https://en.cppreference.com/w/) (cppreference)
- [Competitive Programmer's Handbook (Ch. 1, 4)](https://cses.fi/book/book.pdf) (CSES)

### Java for DSA

alternative · beginner · about 20 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/java-for-dsa

Use Java and its Collections Framework for DSA: ArrayList, HashMap, TreeMap, PriorityQueue, ArrayDeque, plus fast input and common boxing traps.

Java is a solid choice if your college teaches it or you are targeting Java backend roles. It is verbose but predictable, and the **Collections Framework** covers everything interviews need.

#### What to actually learn
- Primitives vs wrappers: `int` vs `Integer`. Collections store objects, so values are **boxed**. Compare Integers with `.equals()`, never `==` (it works only for small cached values, which makes the bug intermittent).
- Core collections: `ArrayList`, `HashMap`/`HashSet`, `TreeMap`/`TreeSet` (sorted, with `floorKey`, `ceilingKey`), `ArrayDeque` (use it for both stack and queue), `PriorityQueue` (min-heap by default).
- Sorting: `Arrays.sort` for primitives, `Collections.sort` or `list.sort((a, b) -> ...)` with comparators. Prefer `Integer.compare(a, b)` over `a - b`, which can overflow.
- Strings are immutable. Build strings in loops with `StringBuilder`, otherwise concatenation becomes O(n^2).
- Fast input: `BufferedReader` plus `StringTokenizer` instead of `Scanner` for large inputs.

#### Pitfalls
- `HashMap.get` returns `null` for missing keys; use `getOrDefault` or `merge(key, 1, Integer::sum)`.
- Recursion depth is limited by the thread stack; very deep DFS may need an explicit stack.
- Use `long` for sums of large values.

Good enough to move on: you can write a max-heap with a comparator, a sorted map query like "largest key <= x", and a BFS using ArrayDeque, all from memory.

Key concepts: Primitives, wrappers and autoboxing, ArrayList and arrays, HashMap and HashSet, TreeMap and TreeSet, ArrayDeque as stack and queue, PriorityQueue with comparators, StringBuilder, Fast I/O with BufferedReader, Generics basics.

Mini project: Solve 6 warm-ups in Java: word frequency with HashMap.merge, sort a list of intervals by start, top-k frequent elements with PriorityQueue, a sliding maximum with ArrayDeque, 'largest key <= x' queries with TreeMap, and reverse words using StringBuilder.

Self-check: Why might comparing two Integer values from a HashMap with == pass small tests but fail on large inputs?

Resources:
- [The Java Tutorials: Collections](https://docs.oracle.com/javase/tutorial/collections/) (Oracle)
- [The Java Tutorials](https://docs.oracle.com/javase/tutorial/) (Oracle)
- [GeeksforGeeks Java](https://www.geeksforgeeks.org/java/) (GeeksforGeeks)

### Python for DSA

alternative · beginner · about 15 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/python-for-dsa

Use Python's concise syntax and built-ins (list, dict, set, heapq, deque, bisect, Counter) to solve interview problems quickly, while knowing its performance limits.

Python lets you express an algorithm in very few lines, which is great in interviews where clarity matters. The trade-off is speed: Python is often 10-50x slower than C++, so some contest problems with tight limits are hard to pass. For interviews and most online assessments it is perfectly fine.

#### What to actually learn
- Built-ins: `list` (dynamic array), `dict`, `set`, `tuple`, slicing, list comprehensions, `enumerate`, `zip`, `sorted(key=...)`.
- `collections`: `deque` (O(1) pops from both ends; `list.pop(0)` is O(n)), `Counter`, `defaultdict`.
- `heapq`: a **min-heap** on a plain list. For a max-heap, push negated values or tuples.
- `bisect`: `bisect_left`/`bisect_right` for binary search on sorted lists.
- `functools.lru_cache` (or `cache`) for quick memoization in DP.

#### Pitfalls
- Recursion limit defaults to about 1000; call `sys.setrecursionlimit` or convert deep DFS to iterative.
- `[[0] * m] * n` creates n references to the same row. Use `[[0] * m for _ in range(n)]`.
- Strings are immutable; build with a list and `"".join(parts)`.
- Use `sys.stdin.readline` for large input.

Good enough to move on: you can write BFS with deque, Dijkstra with heapq, and a memoized recursive DP, and you know which operations are O(1) versus O(n).

Key concepts: Lists, slicing and comprehensions, dict and set, collections.deque, Counter and defaultdict, heapq (min-heap), bisect for binary search, lru_cache for memoization, Recursion limit and fast input.

Mini project: Solve 6 warm-ups in Python: group anagrams with defaultdict, top-k frequent with Counter and heapq, BFS on a grid with deque, count elements in a range with bisect, memoized Fibonacci with lru_cache, and a max-heap of tasks using negated priorities.

Self-check: What is wrong with grid = [[0] * 3] * 3, and why does using list.pop(0) inside a BFS loop hurt performance?

Resources:
- [The Python Tutorial](https://docs.python.org/3/tutorial/) (Python.org)
- [collections module](https://docs.python.org/3/library/collections.html) (Python.org)
- [heapq module](https://docs.python.org/3/library/heapq.html) (Python.org)

### Complexity Analysis

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/complexity-analysis

Reason about how running time and memory grow with input size using Big-O, Theta and Omega, amortized analysis and recursion recurrences.

Complexity analysis lets you predict whether a solution will pass before you write it. Interviewers expect you to state time and space complexity for every solution you propose.

#### The notations
- **Big-O** is an upper bound on growth, **Omega** a lower bound, **Theta** a tight bound. In interviews "O" is used loosely to mean the tight worst case.
- Drop constants and lower-order terms: 3n^2 + 5n is O(n^2).
- Common classes in order: O(1), O(log n), O(n), O(n log n), O(n^2), O(2^n), O(n!).

#### Estimating from constraints
A typical judge does roughly 10^8 simple operations per second. So:
- n <= 10^5 or 10^6: aim for O(n) or O(n log n).
- n <= 5000: O(n^2) is fine.
- n <= 20: exponential like O(2^n) or bitmask DP is acceptable.

Reading constraints this way is one of the most useful habits you can build.

#### Beyond simple loops
- **Amortized** cost: a dynamic array doubles its capacity occasionally, but push_back is O(1) amortized because the total copying work over n pushes is O(n).
- **Recurrences**: merge sort is T(n) = 2T(n/2) + O(n) = O(n log n). Learn the Master Theorem intuition rather than memorizing cases.
- **Space**: count auxiliary memory, including the recursion stack. A recursive DFS on a path-shaped tree uses O(n) stack.

#### Pitfalls
Hidden costs: string concatenation in a loop, `substr`/slicing (O(k)), and `list.pop(0)`. Nested loops are not always O(n^2): the two-pointer pattern moves each pointer at most n times, so it is O(n).

Key concepts: Big-O, Omega and Theta, Best, average and worst case, Estimating from constraints, Space complexity and call stack, Amortized analysis, Recurrences and Master Theorem, Harmonic series O(n log n) loops.

Mini project: Take 10 short code snippets (nested loops, halving loops, recursion like fib and merge sort, sieve-style j += i loops) and write their time and space complexity with a one-line justification; then time a O(n^2) and O(n log n) solution on n = 10^5 to see the difference.

Self-check: The loop 'for i in 1..n: for j = i; j <= n; j += i' looks nested. What is its actual complexity and why?

Resources:
- [Big-O Cheat Sheet](https://www.bigocheatsheet.com/) (bigocheatsheet.com)
- [Competitive Programmer's Handbook (Ch. 2)](https://cses.fi/book/book.pdf) (CSES)
- [MIT 6.006 Introduction to Algorithms](https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/) (MIT OCW)

### Git and GitHub Workflow

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/git-version-control

Track your solutions and projects with Git: commits, branches, merging, remotes and pull requests, the workflow every internship team uses.

Every software team uses version control, and recruiters look at your GitHub. Start using Git now for your DSA solutions and projects so it becomes muscle memory before your internship.

#### The mental model
Git stores **snapshots** of your project. A commit is a snapshot plus a message and a pointer to its parent. A **branch** is just a movable label pointing at a commit. Understanding this makes merge, rebase and reset much less scary.

#### Daily commands
- `git init`, `git clone`, `git status`, `git add`, `git commit -m`, `git log --oneline`.
- `git branch`, `git switch -c feature`, `git merge`.
- Remotes: `git remote add origin`, `git push -u origin main`, `git pull`, `git fetch`.
- Undo: `git restore` (discard working changes), `git revert` (safe undo of a pushed commit), `git reset` (move a branch; dangerous on shared branches).

#### Team workflow
Create a branch per feature, commit small focused changes with clear messages, push, and open a **pull request** for review. Resolve **merge conflicts** by editing the marked regions, then add and commit. Use `.gitignore` for build output, secrets and `node_modules`.

#### Interview angle
Be ready to explain merge vs rebase, what a detached HEAD is, and how you would undo a bad commit that is already pushed (revert, not reset).

Key concepts: Commits, snapshots and history, Staging area and .gitignore, Branching and merging, Remotes, push, pull, fetch, Merge conflicts, Pull requests and code review, revert vs reset, Rebase and interactive history edits.

Mini project: Create a public 'dsa-journal' repo, push each solved problem in a folder per topic, create a feature branch that adds a README with your progress table, deliberately cause and resolve a merge conflict, and merge via a pull request.

Self-check: A teammate already pulled your last commit, which broke the build. Why should you use git revert instead of git reset --hard?

Resources:
- [Pro Git book](https://git-scm.com/book/en/v2) (git-scm.com)
- [Learn Git Branching](https://learngitbranching.js.org/) (learngitbranching)
- [Missing Semester: Version Control](https://missing.csail.mit.edu/2020/version-control/) (MIT)

## Math You Need for Problem Solving

The number theory, counting and bit tricks that show up again and again in coding rounds and contests.

### Modular Arithmetic and Counting

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/modular-arithmetic-combinatorics

Handle huge answers 'modulo 1e9+7' correctly, compute fast powers and inverses, and count arrangements with nCr and basic combinatorics.

Many problems ask for an answer "modulo 10^9 + 7" because the true count is astronomically large. You need to know which operations are safe under a modulus and how to compute counts efficiently.

#### Modular rules
- (a + b) mod m, (a - b) mod m and (a * b) mod m can be applied at every step. For subtraction add m before taking mod to avoid negatives: `((a - b) % m + m) % m`.
- Division is **not** direct. Multiply by the **modular inverse** instead. When m is prime, inverse of a is a^(m-2) mod m (Fermat's little theorem).
- Multiply in 64-bit: two values below 1e9+7 multiply to about 1e18, which fits in long long but not in int.

#### Fast exponentiation
Binary exponentiation computes a^b in O(log b) by squaring: if the current bit of b is set, multiply the result by a, then square a and shift b right. It powers modular inverses, matrix exponentiation and hashing.

#### Counting basics
- Permutations n!, combinations nCr = n! / (r! (n-r)!).
- For many nCr queries, precompute factorials and inverse factorials up to n in O(n), then each query is O(1).
- Pascal's triangle C[n][r] = C[n-1][r-1] + C[n-1][r] works for small n without inverses.
- Stars and bars, inclusion-exclusion and the pigeonhole principle appear in medium-hard problems.

Good enough to move on: you can write modpow and a precomputed nCr table without bugs and explain why the subtraction fix is needed.

Key concepts: Mod rules for +, -, *, Binary exponentiation, Modular inverse via Fermat, Factorial and inverse factorial tables, nCr and Pascal's triangle, Inclusion-exclusion, Stars and bars, Extended Euclid for inverses.

Mini project: Implement modpow and an nCr helper with precomputed factorials, then solve: Pow(x, n), Count Good Numbers, Unique Paths via nCr, CSES Binomial Coefficients, CSES Exponentiation II, and a 'count strings of length n with no two adjacent equal chars' problem mod 1e9+7.

Self-check: Why can you not compute (a / b) mod m as (a mod m) / (b mod m), and what do you do instead when m is prime?

Resources:
- [Binary Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html) (cp-algorithms)
- [Modular Multiplicative Inverse](https://cp-algorithms.com/algebra/module-inverse.html) (cp-algorithms)
- [Competitive Programmer's Handbook (Ch. 21-22)](https://cses.fi/book/book.pdf) (CSES)

### Primes, Divisors and GCD

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/primes-and-gcd

Test primality, generate primes with the Sieve of Eratosthenes, factorize numbers and use GCD/LCM, the core number theory of coding rounds.

Number theory questions in online assessments are usually about primes, divisors and GCD. A few standard techniques cover most of them.

#### Primality and divisors
- Trial division up to sqrt(n): if n has a divisor greater than sqrt(n), it also has one smaller. This gives O(sqrt n) primality tests and divisor enumeration.
- Divisors come in pairs (d, n/d), so loop d from 1 while d * d <= n.

#### Sieve of Eratosthenes
To find all primes up to N, mark multiples of each prime starting from p * p. Complexity is O(N log log N). A **smallest prime factor (SPF)** sieve stores the smallest prime dividing each number, letting you factorize any number up to N in O(log n).

#### GCD and LCM
Euclid's algorithm: gcd(a, b) = gcd(b, a mod b), running in O(log min(a, b)). Then lcm(a, b) = a / gcd(a, b) * b (divide first to avoid overflow). Use built-ins like `std::gcd` or `math.gcd` in real code.

#### Where it appears
Counting coprime pairs, simplifying fractions, "make array elements equal" problems, and GCD of a subarray. Pitfalls: forgetting that 1 is not prime, overflowing i * i in the sieve loop, and sieving past memory limits (a sieve to 10^7 is fine, 10^9 is not).

Key concepts: Trial division up to sqrt(n), Enumerating divisors, Sieve of Eratosthenes, Smallest prime factor sieve, Prime factorization, Euclid GCD and LCM, Segmented sieve, Euler's totient.

Mini project: Solve 7 problems: Count Primes, check prime in O(sqrt n), print all divisors, prime factorization with an SPF sieve, GCD of Strings, Find Greatest Common Divisor of Array, and CSES Counting Divisors.

Self-check: Why does the sieve start crossing out multiples of p from p * p rather than from 2 * p?

Resources:
- [Sieve of Eratosthenes](https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html) (cp-algorithms)
- [Euclidean algorithm for GCD](https://cp-algorithms.com/algebra/euclid-algorithm.html) (cp-algorithms)
- [CSES Problem Set (Mathematics)](https://cses.fi/problemset/) (CSES)

### Bit Manipulation

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/bit-manipulation

Use binary representation and bitwise operators to test, set and clear bits, solve XOR puzzles and enumerate subsets with bitmasks.

Integers are stored in binary, and bitwise operators work on all bits at once in O(1). This enables elegant tricks that interviewers love and that make subset enumeration practical.

#### Operators and core tricks
- AND `&`, OR `|`, XOR `^`, NOT `~`, shifts `<<` and `>>`.
- Check bit i: `(x >> i) & 1`. Set: `x | (1 << i)`. Clear: `x & ~(1 << i)`. Toggle: `x ^ (1 << i)`.
- `x & (x - 1)` removes the lowest set bit, so `x > 0 && (x & (x - 1)) == 0` tests powers of two.
- `x & -x` isolates the lowest set bit (used by Fenwick trees).
- Count set bits: `__builtin_popcount`, `Integer.bitCount`, or `bin(x).count("1")`.

#### XOR properties
a ^ a = 0 and a ^ 0 = a, and XOR is commutative. So XOR of all elements cancels pairs, which solves "find the single non-repeated number" in O(1) space. Prefix XOR works just like prefix sums.

#### Subsets as bitmasks
For n <= 20, every subset of n items is an integer from 0 to 2^n - 1. Loop over masks and check which bits are set to enumerate all subsets. This is the basis of bitmask DP later.

#### Pitfalls
`1 << 40` overflows a 32-bit int; use `1LL << 40` in C++. Operator precedence: `x & 1 == 0` parses as `x & (1 == 0)`, so always use parentheses. Right shift of negative numbers is implementation-sensitive in some languages.

Key concepts: Binary and two's complement, Get, set, clear, toggle a bit, x & (x - 1) and x & -x, XOR tricks, Counting set bits, Enumerating subsets with masks, Iterating submasks of a mask.

Mini project: Solve 8 problems: Single Number, Single Number II, Number of 1 Bits, Counting Bits, Power of Two, Missing Number, Subsets (via bitmask), and Minimum Flips to Make a OR b Equal to c.

Self-check: How does XOR let you find the one element that appears once when every other element appears exactly twice, using O(1) extra space?

Resources:
- [Bit manipulation](https://cp-algorithms.com/algebra/bit-manipulation.html) (cp-algorithms)
- [Competitive Programmer's Handbook (Ch. 10)](https://cses.fi/book/book.pdf) (CSES)
- [LeetCode Explore](https://leetcode.com/explore/) (LeetCode)

## Arrays, Strings and Hashing Patterns

The highest-frequency interview territory: array and string manipulation plus the patterns (two pointers, sliding window, prefix sums, hashing) that turn O(n^2) into O(n).

### Array and String Fundamentals

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/arrays-and-strings

Understand contiguous memory, dynamic arrays and string representation, and practise in-place manipulation such as reversal, rotation and partitioning.

Arrays store elements in **contiguous memory**, which gives O(1) indexed access and excellent cache performance. Inserting or deleting in the middle costs O(n) because elements must shift. Dynamic arrays (vector, ArrayList, Python list) grow by doubling, which makes appends O(1) amortized.

Strings are arrays of characters. In Java and Python they are immutable, so each modification creates a new string; in C++ `std::string` is mutable. Know how your language handles characters: `c - 'a'` gives an index 0-25, which enables fixed-size frequency arrays that are faster than hash maps.

#### Techniques to practise
- In-place reversal with two indices.
- Rotation by k using three reversals.
- Partitioning (Dutch National Flag) to sort 0s, 1s and 2s in one pass.
- Kadane's algorithm for maximum subarray sum: keep the best sum ending at the current index.
- Matrix traversal: spiral order, transpose, rotate 90 degrees.
- Simulation carefully following rules without off-by-one errors.

#### Pitfalls
Off-by-one errors at boundaries, modifying a collection while iterating over it, and forgetting empty or single-element inputs. Always test with n = 0, n = 1 and all-equal elements.

Good enough to move on: you can solve easy array problems in under 15 minutes and explain the complexity of each operation you use.

Key concepts: Static vs dynamic arrays, Character arithmetic and frequency arrays, In-place reversal and rotation, Dutch National Flag partition, Kadane's algorithm, 2D matrix traversal, String immutability and builders.

Mini project: Solve 10 problems: Rotate Array, Sort Colors, Maximum Subarray, Best Time to Buy and Sell Stock, Move Zeroes, Spiral Matrix, Rotate Image, Valid Palindrome, Longest Common Prefix, and Product of Array Except Self.

Self-check: How does Kadane's algorithm decide whether to extend the current subarray or start a new one, and what happens when all numbers are negative?

Resources:
- [LeetCode Explore: Arrays 101](https://leetcode.com/explore/) (LeetCode)
- [NeetCode Roadmap](https://neetcode.io/roadmap) (NeetCode)
- [Array data structure](https://www.geeksforgeeks.org/array-data-structure/) (GeeksforGeeks)

### Hash Tables and Hashing Patterns

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/hash-tables

Learn how hash maps and sets work internally and apply them to frequency counting, complement lookups, grouping and de-duplication.

A hash table maps keys to values with O(1) average insert, delete and lookup. It is the single most useful tool for turning brute-force O(n^2) searches into O(n).

#### How it works
A **hash function** converts a key to an integer, which is reduced to a bucket index. Different keys can land in the same bucket (**collisions**). Two common resolutions:
- **Chaining**: each bucket holds a list of entries (Java HashMap, C++ unordered_map).
- **Open addressing**: probe for the next free slot (Python dict).
When the **load factor** grows, the table resizes and rehashes, which is O(n) but rare, so operations stay O(1) amortized. The worst case is O(n) if many keys collide; this is why contest solutions sometimes get hacked with anti-hash tests and use custom hashes.

#### Patterns
- **Frequency counting**: anagrams, majority element, first unique character.
- **Complement lookup**: Two Sum stores seen values and checks target - x.
- **Grouping by a canonical key**: sorted string or character counts for Group Anagrams.
- **Seen set**: detect duplicates, cycles or longest consecutive sequence.
- **Prefix sum + hashmap**: count subarrays with a given sum (see the prefix sums topic).

#### Ordered vs unordered
Use a hash map when you only need lookups. Use an ordered map (TreeMap, std::map) when you need sorted iteration or "nearest key" queries, at O(log n) per operation.

Pitfall: mutable objects as keys, and assuming iteration order in a hash map.

Key concepts: Hash functions and buckets, Chaining vs open addressing, Load factor and rehashing, Frequency counting, Complement lookup (Two Sum), Grouping by canonical key, Ordered vs unordered maps, Anti-hash tests and custom hashes.

Mini project: Implement a tiny hash map with chaining and resizing, then solve 8 problems: Two Sum, Valid Anagram, Group Anagrams, Top K Frequent Elements, Longest Consecutive Sequence, Contains Duplicate II, First Unique Character, and Isomorphic Strings.

Self-check: Why is hash map lookup O(1) on average but O(n) in the worst case, and when would you prefer a TreeMap instead?

Resources:
- [Hashing data structure](https://www.geeksforgeeks.org/hashing-data-structure/) (GeeksforGeeks)
- [MIT 6.006 (Hashing lectures)](https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/) (MIT OCW)
- [NeetCode Roadmap](https://neetcode.io/roadmap) (NeetCode)

### Two Pointers

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/two-pointers

Move two indices through a sequence, from both ends or at different speeds, to solve pair-sum, partition and in-place problems in linear time.

The two-pointer technique uses two indices that move through the data in a coordinated way. Because each pointer moves at most n steps, the total work is O(n) even though it can look like a nested loop.

#### Three flavours
- **Opposite ends** on a sorted array: start `l = 0`, `r = n - 1`. If the sum is too small move l right, if too large move r left. Solves pair sum, 3Sum (fix one element, two-pointer the rest), Container With Most Water and palindrome checks.
- **Same direction (read/write)**: a slow pointer marks where to write, a fast pointer scans. Solves Remove Duplicates, Move Zeroes and partitioning in place.
- **Two sequences**: one pointer per array, as in merging two sorted arrays or checking if one string is a subsequence of another.

#### Why it works
On a sorted array, moving the pointer that cannot possibly be part of a better answer safely discards candidates. Being able to state this argument ("if the sum is too big, no pair using r can work with any larger l") is what interviewers look for.

#### Pitfalls
- Forgetting to sort first, or sorting when original indices are needed (then use a hash map instead).
- Duplicate handling in 3Sum: skip equal neighbours after recording a triple.
- Infinite loops when neither pointer moves in some branch.

Fast and slow pointers on linked lists are a cousin of this pattern and appear in the linked list topic.

Key concepts: Opposite-end pointers on sorted data, Read/write pointers for in-place edits, Merging two sorted sequences, 3Sum and k-sum reduction, Duplicate skipping, Correctness argument.

Mini project: Solve 8 problems: Two Sum II, 3Sum, Container With Most Water, Remove Duplicates from Sorted Array, Merge Sorted Array, Valid Palindrome II, Is Subsequence, and Trapping Rain Water (two-pointer version).

Self-check: In Container With Most Water, why is it always safe to move the pointer at the shorter line inward?

Resources:
- [NeetCode Roadmap (Two Pointers)](https://neetcode.io/roadmap) (NeetCode)
- [Two pointers technique](https://www.geeksforgeeks.org/two-pointers-technique/) (GeeksforGeeks)
- [LeetCode Problem Set](https://leetcode.com/problemset/) (LeetCode)

### Sliding Window

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/sliding-window

Maintain a window over a contiguous range and update it incrementally, solving longest/shortest subarray and substring problems in O(n).

Sliding window is two pointers specialised for **contiguous** subarrays or substrings. Instead of recomputing each window from scratch, you add the element entering on the right and remove the one leaving on the left.

#### Fixed-size window
For "max sum of any k consecutive elements", compute the first window, then slide: add `a[i]`, subtract `a[i - k]`. O(n) instead of O(nk).

#### Variable-size window
The general template:
- Expand `r` one step at a time, adding `a[r]` to the window state (a sum, a count map, a set).
- While the window is **invalid**, shrink from the left by removing `a[l]` and incrementing l.
- Record the answer (longest valid window) after shrinking, or record the shortest while the window is still valid.

This solves Longest Substring Without Repeating Characters, Minimum Window Substring, Longest Repeating Character Replacement and "at most k distinct" problems.

#### When it works
The window condition must be **monotonic**: if a window is invalid, every larger window containing it is also invalid. With negative numbers, "sum >= target" is not monotonic and you need prefix sums or a deque instead.

#### Tricks
"Exactly k" is often computed as atMost(k) - atMost(k - 1). For window maximums, combine the window with a monotonic deque (covered later).

Key concepts: Fixed-size window, Variable window expand/shrink template, Window state with count maps, Monotonic validity condition, Exactly k = atMost(k) - atMost(k-1), When windows fail (negative numbers).

Mini project: Solve 8 problems: Maximum Average Subarray I, Longest Substring Without Repeating Characters, Longest Repeating Character Replacement, Permutation in String, Minimum Size Subarray Sum, Minimum Window Substring, Fruit Into Baskets, and Subarrays with K Different Integers.

Self-check: Why does the variable sliding window fail for 'shortest subarray with sum at least k' when the array contains negative numbers?

Resources:
- [NeetCode Roadmap (Sliding Window)](https://neetcode.io/roadmap) (NeetCode)
- [Window sliding technique](https://www.geeksforgeeks.org/window-sliding-technique/) (GeeksforGeeks)
- [LeetCode Problem Set](https://leetcode.com/problemset/) (LeetCode)

### Prefix Sums and Difference Arrays

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/prefix-sums

Precompute running totals to answer range-sum queries in O(1), count subarrays with a target sum, and apply range updates with difference arrays.

A prefix sum array stores `pre[i] = a[0] + ... + a[i-1]`. Then the sum of any range [l, r] is `pre[r + 1] - pre[l]` in O(1) after O(n) preprocessing. Using a leading zero (size n + 1) removes most boundary special cases.

#### Patterns
- **Range sum queries** on a static array.
- **Subarray sum equals k**: as you scan, keep a hash map of how many times each prefix sum has occurred. At index i, the number of subarrays ending here with sum k equals `count[pre - k]`. Initialise `count[0] = 1`. This works with negative numbers, unlike sliding window.
- **Divisibility**: subarrays with sum divisible by k use prefix sums modulo k.
- **Balance tricks**: map 0 to -1 and find the longest subarray with equal 0s and 1s (longest prefix-sum repeat).
- **2D prefix sums** for sub-rectangle sums using inclusion-exclusion.

#### Difference arrays
To add v to every element in [l, r] many times, do `d[l] += v; d[r + 1] -= v`, then take a prefix sum at the end. This is the offline version of range updates and powers problems like Car Pooling and Corporate Flight Bookings.

Other prefix variants: prefix XOR, prefix max/min, and prefix products (Product of Array Except Self uses prefix and suffix products).

Pitfall: prefix sums can overflow int; use 64-bit.

Key concepts: 1D prefix sums with leading zero, Prefix sum + hash map counting, Prefix sums modulo k, 2D prefix sums, Difference arrays for range updates, Prefix XOR and products.

Mini project: Solve 8 problems: Range Sum Query Immutable, Subarray Sum Equals K, Continuous Subarray Sum, Contiguous Array, Subarray Sums Divisible by K, Range Sum Query 2D, Car Pooling, and Corporate Flight Bookings.

Self-check: In Subarray Sum Equals K, why must the hash map start with count[0] = 1?

Resources:
- [USACO Guide: Prefix Sums](https://usaco.guide/silver/prefix-sums) (USACO Guide)
- [Competitive Programmer's Handbook (Ch. 9)](https://cses.fi/book/book.pdf) (CSES)
- [Prefix sum array](https://www.geeksforgeeks.org/prefix-sum-array-implementation-applications-competitive-programming/) (GeeksforGeeks)

### String Matching Algorithms

optional · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/string-algorithms

Go beyond brute force substring search with KMP's prefix function, the Z-algorithm and Rabin-Karp rolling hashes.

Naive substring search compares the pattern at every position, costing O(n * m). Specialised algorithms find all occurrences in O(n + m). These are asked less often than core patterns but appear in harder rounds and contests.

#### KMP and the prefix function
The **prefix function** pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix. When a mismatch happens, KMP jumps using pi instead of restarting, so no character of the text is examined more than a constant number of times. Trick: compute pi on `pattern + "#" + text` and every position where pi equals the pattern length is a match.

#### Z-algorithm
z[i] is the length of the longest substring starting at i that matches a prefix of the string. It solves the same matching problem and is often easier to reason about.

#### Rabin-Karp rolling hash
Treat a string as a number in base b modulo a large prime. Sliding the window updates the hash in O(1). Hash equality suggests a match; verify or use double hashing to avoid collisions. Rolling hashes also solve "longest duplicate substring" when combined with binary search.

#### Also useful
Palindromes: expand around centre (O(n^2)) is usually enough; Manacher's algorithm gives O(n).

Good enough to move on: you can implement the prefix function and explain what pi means for a small example like "aabaaab".

Key concepts: Prefix function and KMP, Z-algorithm, Rabin-Karp rolling hash, Expand around centre palindromes, Manacher's algorithm, Double hashing against collisions.

Mini project: Implement KMP, Z-function and Rabin-Karp and cross-check them on random strings, then solve: Find the Index of the First Occurrence, Repeated Substring Pattern, Shortest Palindrome, Longest Palindromic Substring, and Longest Happy Prefix.

Self-check: What does pi[i] represent in KMP, and why does it guarantee the text pointer never moves backwards?

Resources:
- [Prefix function and KMP](https://cp-algorithms.com/string/prefix-function.html) (cp-algorithms)
- [Z-function](https://cp-algorithms.com/string/z-function.html) (cp-algorithms)
- [String hashing](https://cp-algorithms.com/string/string-hashing.html) (cp-algorithms)

## Recursion, Sorting and Searching

Think recursively, explore solution spaces with backtracking, understand how sorting algorithms work, and master binary search including searching over the answer.

### Recursion and Divide and Conquer

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/recursion

Break problems into smaller copies of themselves with a clear base case, trace the call stack, and apply divide and conquer.

Recursion solves a problem by solving smaller instances of the same problem. It is the foundation for trees, graphs, backtracking and dynamic programming, so time spent here pays off everywhere.

#### The recipe
- **Base case**: the smallest input you can answer directly.
- **Recursive case**: assume the function already works for smaller inputs (the "leap of faith") and combine those results.
- **Progress**: every call must move toward a base case, or you get infinite recursion and a stack overflow.

#### Tracing and cost
Draw the **recursion tree**. Time is roughly the number of nodes times the work per node; space is the maximum depth of the call stack. Naive Fibonacci has about 2^n nodes, which is why it is slow and why memoization (later, in DP) helps so much.

#### Divide and conquer
Split the input, solve each part recursively, combine. Examples: merge sort, quick sort, binary search, fast power, counting inversions, and closest pair of points. The combine step usually determines the complexity.

#### Pitfalls
- Returning nothing from a branch in a function that should return a value.
- Mutating shared state without undoing it (a classic backtracking bug).
- Very deep recursion (10^5 levels) can overflow the stack in Java and Python; switch to iteration if needed.

Good enough to move on: you can write recursive power, reverse a string, generate all subsets and print the recursion tree for small inputs by hand.

Key concepts: Base case and recursive case, Call stack and recursion tree, Time and space of recursive code, Divide and conquer paradigm, Tail recursion and iteration, Counting inversions.

Mini project: Solve 7 problems recursively: Pow(x, n), Reverse Linked List (recursive), Fibonacci with and without memo, Tower of Hanoi, K-th Symbol in Grammar, Merge Two Sorted Lists, and Count Inversions of an array.

Self-check: What is the space complexity of a recursive function that makes one recursive call on n - 1, and why is it not O(1)?

Resources:
- [LeetCode Explore: Recursion I](https://leetcode.com/explore/) (LeetCode)
- [Jeff Erickson, Algorithms (Ch. 1)](https://jeffe.cs.illinois.edu/teaching/algorithms/) (UIUC)
- [Introduction to recursion](https://www.geeksforgeeks.org/introduction-to-recursion-2/) (GeeksforGeeks)

### Backtracking

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/backtracking

Systematically build candidates choice by choice, undo choices that fail, and prune early to generate subsets, permutations and constrained solutions.

Backtracking is recursion over **choices**. At each step you pick an option, recurse, then undo the pick and try the next one. It enumerates all subsets, permutations or combinations, and with pruning it solves constraint puzzles like N-Queens and Sudoku.

#### The template
```
solve(state):
  if state is complete: record answer; return
  for each choice valid in state:
    make choice
    solve(next state)
    undo choice
```
The **undo** step is what keeps a single shared path correct across branches.

#### Three shapes to know
- **Subsets**: for each element, include or exclude (2^n results).
- **Permutations**: choose any unused element for the next position (n! results), tracked with a used array.
- **Combinations / combination sum**: pass a start index so you never go backwards, which avoids duplicate orderings.

#### Handling duplicates
Sort the input, then skip an element if it equals the previous one at the same recursion level (`i > start && a[i] == a[i-1]`).

#### Pruning
Stop early when the partial state cannot lead to a valid answer: sum already exceeds target, a queen is attacked, a word does not match the grid. Good pruning is the difference between TLE and AC.

Backtracking is exponential by nature. If you notice the same subproblem recurring, that is your cue to switch to dynamic programming.

Key concepts: Choose, explore, unchoose template, Subsets, Permutations, Combinations and combination sum, Skipping duplicates, Pruning, Grid search (Word Search), N-Queens and Sudoku.

Mini project: Solve 8 problems: Subsets, Subsets II, Permutations, Combination Sum, Combination Sum II, Letter Combinations of a Phone Number, Word Search, and N-Queens.

Self-check: In Subsets II, why does the duplicate-skip condition check i > start rather than i > 0?

Resources:
- [NeetCode Roadmap (Backtracking)](https://neetcode.io/roadmap) (NeetCode)
- [Jeff Erickson, Algorithms (Ch. 2)](https://jeffe.cs.illinois.edu/teaching/algorithms/) (UIUC)
- [Backtracking algorithms](https://www.geeksforgeeks.org/backtracking-algorithms/) (GeeksforGeeks)

### Sorting Algorithms

core · beginner · about 7 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/sorting-algorithms

Understand how bubble, insertion, selection, merge, quick, heap and counting sort work, their complexities and stability, and when sorting simplifies a problem.

You will almost always call the library sort in real code, but interviews and university exams test whether you understand how sorting works and what guarantees each algorithm gives.

#### The algorithms
- **Bubble, selection, insertion**: O(n^2). Insertion sort is fast on nearly sorted data and small arrays.
- **Merge sort**: O(n log n) always, stable, needs O(n) extra memory. Great for linked lists and external sorting.
- **Quick sort**: O(n log n) average, O(n^2) worst case with bad pivots, in place. Random pivots make the worst case unlikely.
- **Heap sort**: O(n log n) worst case, in place, not stable.
- **Counting / radix sort**: O(n + k) for small integer ranges, not comparison-based.

Comparison sorts cannot beat O(n log n) in the worst case, which is a classic theory question.

#### Properties to remember
- **Stable**: equal elements keep their original order. Matters when sorting by multiple keys.
- **In place**: uses O(1) or O(log n) extra memory.

#### Sorting as a technique
Sorting first often unlocks simpler solutions: two pointers for pair sums, merging intervals, greedy scheduling, grouping duplicates. Custom comparators let you sort by any rule, like "largest number formed by concatenation".

#### Quickselect
Partitioning (from quick sort) finds the k-th smallest element in O(n) average without fully sorting.

Key concepts: Bubble, selection, insertion sort, Merge sort, Quick sort and partitioning, Heap sort, Counting and radix sort, Stability and in-place sorting, Custom comparators, Quickselect.

Mini project: Implement merge sort, quick sort (random pivot) and counting sort and benchmark them, then solve: Sort an Array, Merge Intervals, Kth Largest Element (quickselect), Largest Number, Sort Colors, and Meeting Rooms.

Self-check: Why is quick sort usually faster than merge sort in practice despite having a worse worst case?

Resources:
- [VisuAlgo: Sorting](https://visualgo.net/en/sorting) (VisuAlgo)
- [Sorting algorithms](https://www.geeksforgeeks.org/sorting-algorithms/) (GeeksforGeeks)
- [MIT 6.006 Introduction to Algorithms](https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/) (MIT OCW)

### Binary Search

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/binary-search

Halve the search space each step to find elements, boundaries and insertion points in sorted or rotated data, with a bug-free template.

Binary search finds a target in a sorted array in O(log n) by comparing with the middle and discarding half. It is simple in idea and notorious for off-by-one bugs, so pick one template and use it consistently.

#### Think in terms of a predicate
Most binary search problems become: find the **first index** where a condition becomes true, given the condition is false...false, true...true. For example "first element >= x" is lower_bound. A reliable template:
```
lo = 0, hi = n        // answer in [lo, hi]
while lo < hi:
  mid = lo + (hi - lo) / 2
  if condition(mid): hi = mid
  else: lo = mid + 1
return lo
```
Using `lo + (hi - lo) / 2` avoids overflow.

#### Variations
- First and last occurrence of a value (two boundary searches).
- Search insert position.
- **Rotated sorted array**: one half is always sorted; decide which half the target lies in.
- Peak element: compare mid with mid + 1 to move toward a larger neighbour.
- 2D matrix treated as a flattened sorted array.
- Binary search on real numbers: loop a fixed number of times (like 100) instead of checking equality.

#### Pitfalls
Infinite loops when `lo = mid` is used with a floor midpoint, forgetting the "not found" case, and using binary search on data that is not monotonic.

Key concepts: Classic search in sorted array, Predicate / first-true template, lower_bound and upper_bound, First and last occurrence, Rotated sorted array, Peak finding, Binary search on reals.

Mini project: Solve 8 problems: Binary Search, Search Insert Position, Find First and Last Position, Search in Rotated Sorted Array, Find Minimum in Rotated Sorted Array, Find Peak Element, Search a 2D Matrix, and Sqrt(x).

Self-check: In a rotated sorted array, how do you decide which half is sorted, and what breaks when duplicates are allowed?

Resources:
- [LeetCode Explore: Binary Search](https://leetcode.com/explore/) (LeetCode)
- [Binary search](https://cp-algorithms.com/num_methods/binary_search.html) (cp-algorithms)
- [USACO Guide: Binary Search](https://usaco.guide/silver/binary-search) (USACO Guide)

### Binary Search on the Answer

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/binary-search-on-answer

When feasibility is monotonic in the answer, binary search over possible answers and check each with a greedy function.

A powerful pattern: instead of searching an array, search the **range of possible answers**. If you can write a function `feasible(x)` that says whether answer x works, and feasibility is monotonic (if x works, every larger x also works), binary search finds the smallest working x.

#### Recognising it
Look for phrases like "minimise the maximum", "maximise the minimum", "smallest capacity such that", or "minimum speed to finish in time". The answer lives in a numeric range [low, high], and checking a single candidate is easier than finding the optimum directly.

#### Structure
- Choose bounds: for Koko Eating Bananas, speed is in [1, max pile].
- Write `feasible(mid)`, usually a greedy O(n) scan: "with speed mid, how many hours does it take?".
- Binary search with the first-true template. Total cost O(n log range).

#### Classic problems
- Koko Eating Bananas, Capacity to Ship Packages Within D Days.
- Split Array Largest Sum, Book Allocation, Painter's Partition (very common in Indian interviews).
- Aggressive Cows / Magnetic Force Between Two Balls (maximise minimum distance).
- Minimum Number of Days to Make m Bouquets.

#### Pitfalls
Wrong bounds (low must be feasible-or-not correctly, high must be definitely feasible), overflow when summing inside the check, and using it where feasibility is not monotonic. Always write one sentence proving monotonicity before coding.

Key concepts: Monotonic feasibility, Choosing search bounds, Greedy check function, Minimise the maximum, Maximise the minimum, k-th smallest via counting.

Mini project: Solve 7 problems: Koko Eating Bananas, Capacity to Ship Packages, Split Array Largest Sum, Book Allocation, Aggressive Cows, Minimum Days to Make m Bouquets, and Kth Smallest Number in Multiplication Table.

Self-check: For Capacity to Ship Packages, why is the lower bound max(weights) and the upper bound sum(weights)?

Resources:
- [USACO Guide: Binary Search](https://usaco.guide/silver/binary-search) (USACO Guide)
- [NeetCode Roadmap (Binary Search)](https://neetcode.io/roadmap) (NeetCode)
- [Striver's DSA resources](https://takeuforward.org/) (takeUforward)

## Linked Lists, Stacks and Queues

Pointer-based lists and the LIFO/FIFO structures behind expression parsing, BFS and the monotonic stack and deque patterns.

### Linked Lists

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/linked-lists

Manipulate singly and doubly linked lists with pointer rewiring, dummy nodes and fast/slow pointers for cycles and middles.

A linked list stores elements in nodes that point to the next node. Insertion and deletion at a known node are O(1), but access by index is O(n) and cache performance is poor. Interviewers use linked lists mainly to test **careful pointer manipulation**.

#### Core techniques
- **Dummy (sentinel) head**: create a fake node before the head so inserting or deleting the first node needs no special case.
- **Iterative reversal**: keep `prev`, `curr`, `next`; point `curr.next` to prev and advance. Practise until you can write it in one go.
- **Fast and slow pointers**: slow moves one step, fast moves two. When fast reaches the end, slow is at the middle. If they ever meet, there is a cycle (Floyd's algorithm), and resetting one pointer to head finds the cycle start.
- **Two-pointer gap**: advance one pointer n steps first to find the n-th node from the end.
- **Merge**: merge two sorted lists with a dummy node; merge sort works naturally on lists.

#### Doubly linked lists
Each node has prev and next. Combined with a hash map this gives an O(1) **LRU cache**, one of the most asked design-flavoured coding questions.

#### Pitfalls
Losing the rest of the list by overwriting `next` too early, null pointer dereference on `fast.next.next`, and forgetting to update the tail. Draw boxes and arrows before coding.

Key concepts: Singly vs doubly linked lists, Dummy head node, Iterative and recursive reversal, Fast and slow pointers, Floyd's cycle start, Merging and sorting lists, LRU cache with hash map + DLL.

Mini project: Implement a singly linked list class, then solve 9 problems: Reverse Linked List, Merge Two Sorted Lists, Linked List Cycle II, Middle of the Linked List, Remove Nth Node From End, Reorder List, Palindrome Linked List, Add Two Numbers, and LRU Cache.

Self-check: In Floyd's algorithm, after slow and fast meet inside the cycle, why does moving one pointer back to head and stepping both by one find the cycle's start?

Resources:
- [LeetCode Explore: Linked List](https://leetcode.com/explore/) (LeetCode)
- [VisuAlgo: Linked List](https://visualgo.net/en/list) (VisuAlgo)
- [Linked list data structure](https://www.geeksforgeeks.org/linked-list-data-structure/) (GeeksforGeeks)

### Stacks

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/stacks

Use last-in-first-out stacks for matching brackets, evaluating expressions, undo history and simulating recursion.

A stack supports push, pop and peek at one end in O(1). It is the right structure whenever the **most recent** unfinished item must be handled first.

#### Where stacks appear
- **Bracket matching**: push opening brackets, pop and compare on closing ones.
- **Expression evaluation**: evaluate postfix (Reverse Polish) directly; convert infix to postfix with operator precedence (shunting-yard), or evaluate a basic calculator with a stack of partial results and signs.
- **Nested decoding**: Decode String ("3[a2[c]]") uses a stack of counts and partial strings.
- **Simulating recursion**: an explicit stack turns recursive DFS into iterative DFS, which avoids stack overflow.
- **Min stack**: store the current minimum alongside each element to get min in O(1).
- **Path simplification**: Simplify Path pushes directory names and pops on "..".

#### Implementation
Use a dynamic array or `std::stack`, `ArrayDeque` in Java (not the legacy `Stack` class), or a Python list with append/pop. Implementing a stack with an array and with a linked list is a common viva and exam question.

#### Pitfalls
Popping from an empty stack, forgetting leftover elements at the end (unmatched brackets), and mixing up operand order for subtraction and division in RPN.

Key concepts: LIFO operations and implementations, Balanced brackets, Postfix evaluation and infix conversion, Min stack, Nested decoding, Iterative DFS with explicit stack.

Mini project: Solve 7 problems: Valid Parentheses, Min Stack, Evaluate Reverse Polish Notation, Decode String, Simplify Path, Basic Calculator II, and Asteroid Collision.

Self-check: How does Min Stack return the minimum in O(1) even after the current minimum is popped?

Resources:
- [Stack data structure](https://www.geeksforgeeks.org/stack-data-structure/) (GeeksforGeeks)
- [LeetCode Explore: Queue and Stack](https://leetcode.com/explore/) (LeetCode)
- [NeetCode Roadmap (Stack)](https://neetcode.io/roadmap) (NeetCode)

### Queues and Deques

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/queues-and-deques

Use first-in-first-out queues for BFS and scheduling, circular buffers for fixed capacity, and double-ended queues for flexible access.

A queue processes items in the order they arrive (FIFO): enqueue at the back, dequeue from the front, both O(1). A **deque** (double-ended queue) allows O(1) push and pop at both ends.

#### Where queues appear
- **Breadth-first search**: the queue holds the frontier, which is why BFS finds shortest paths in unweighted graphs.
- **Level order traversal** of trees.
- **Scheduling and simulation**: round-robin CPU scheduling, task processing, "Number of Recent Calls".
- **Producer-consumer** buffers in operating systems and message queues in system design.

#### Implementations
- **Circular array**: keep head and tail indices modulo capacity. Design Circular Queue is a common interview and lab exercise; the tricky part is distinguishing full from empty (track a count or leave one slot unused).
- Linked list with head and tail pointers.
- Library: `std::queue`/`std::deque`, `ArrayDeque` in Java, `collections.deque` in Python.

#### Related puzzles
Implement a queue using two stacks (amortized O(1) per operation) and a stack using queues. These test whether you understand amortized analysis.

Pitfall: using a Python list with `pop(0)` or a Java `ArrayList.remove(0)` as a queue, which is O(n) per dequeue.

Key concepts: FIFO operations, Circular queue on an array, Deque operations, Queue using two stacks, Queues in BFS and scheduling.

Mini project: Implement a circular queue from scratch, then solve: Design Circular Queue, Implement Queue using Stacks, Implement Stack using Queues, Number of Recent Calls, Dota2 Senate, and Time Needed to Buy Tickets.

Self-check: Why does implementing a queue with two stacks give amortized O(1) dequeue even though a single dequeue can move n elements?

Resources:
- [Queue data structure](https://www.geeksforgeeks.org/queue-data-structure/) (GeeksforGeeks)
- [LeetCode Explore: Queue and Stack](https://leetcode.com/explore/) (LeetCode)
- [VisuAlgo: Linked List, Stack, Queue, Deque](https://visualgo.net/en/list) (VisuAlgo)

### Monotonic Stack and Deque

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/monotonic-stack-deque

Keep a stack or deque in sorted order to find next greater elements, largest rectangles and sliding window maximums in linear time.

A monotonic stack keeps its elements in increasing or decreasing order by popping anything that would break the order before pushing. Each element is pushed and popped at most once, so the whole scan is O(n).

#### Next greater element
Scan left to right with a stack of indices whose next greater element is not yet known, kept in decreasing order of value. When a new value is larger than the top, the top has found its answer: pop it and record. This single idea solves:
- Next Greater Element, Daily Temperatures.
- Previous smaller / next smaller element (flip the comparison or the scan direction).
- **Largest Rectangle in Histogram**: for each bar, the nearest smaller bars on the left and right bound its widest rectangle.
- Sum of Subarray Minimums: count how many subarrays each element is the minimum of.
- Stock Span, Remove K Digits, and Trapping Rain Water (stack version).

#### Monotonic deque
For **sliding window maximum**, keep a deque of indices with decreasing values. Pop from the back while the new value is larger (those can never be the maximum again), and pop from the front when the index leaves the window. The front is always the window maximum. It also speeds up some DP transitions (for example "jump game with window").

#### Tips
Store **indices**, not values, so you can compute distances and check window bounds. Decide carefully between strict and non-strict comparisons when duplicates exist, or you will double-count.

Key concepts: Next greater / smaller element, Previous greater / smaller element, Largest rectangle in histogram, Contribution counting with stacks, Sliding window maximum deque, Handling duplicates strictly, Deque-optimised DP.

Mini project: Solve 8 problems: Next Greater Element I, Daily Temperatures, Online Stock Span, Largest Rectangle in Histogram, Maximal Rectangle, Sum of Subarray Minimums, Remove K Digits, and Sliding Window Maximum.

Self-check: Why is the monotonic stack solution O(n) even though there is a while loop inside the for loop?

Resources:
- [Minimum stack / minimum queue](https://cp-algorithms.com/data_structures/stack_queue_modification.html) (cp-algorithms)
- [NeetCode Roadmap (Stack)](https://neetcode.io/roadmap) (NeetCode)
- [LeetCode Problem Set](https://leetcode.com/problemset/) (LeetCode)

## Trees and Heaps

Hierarchical data structures: binary tree traversals and recursion, BSTs, heaps for priority, tries for prefixes, and range-query trees for advanced problems.

### Binary Trees and Traversals

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/binary-trees

Traverse binary trees depth-first and breadth-first, and solve tree problems by combining answers returned from left and right subtrees.

A binary tree node has up to two children. Tree problems are the best place to become fluent with recursion, because almost every solution follows the same shape: **ask the left and right subtrees for something, then combine**.

#### Traversals
- **Preorder** (node, left, right): copying or serialising a tree.
- **Inorder** (left, node, right): sorted order for a BST.
- **Postorder** (left, right, node): when a node needs its children's results first, like height or deleting a tree.
- **Level order** (BFS with a queue): level-by-level views, zigzag, right side view.
Know both recursive and iterative versions (iterative inorder with a stack is frequently asked).

#### Two recursion styles
- **Bottom-up (return values)**: height, diameter, balanced check, maximum path sum. Return one value upward and update a global answer along the way.
- **Top-down (pass parameters)**: pass down the current path sum, depth or allowed range.

#### Must-know problems
Maximum depth, diameter, same tree, invert tree, lowest common ancestor, path sum, construct tree from preorder + inorder, serialise/deserialise, and vertical or boundary traversal (popular in Indian interviews).

#### Pitfalls
Confusing height (edges vs nodes), null checks at leaves, and using a global variable without resetting it between test cases.

Key concepts: Tree terminology and representation, Pre, in, post-order traversal, Level order traversal (BFS), Iterative traversals with a stack, Bottom-up recursion (height, diameter), Top-down recursion (path sums), Lowest common ancestor, Build tree from traversals, Morris traversal.

Mini project: Solve 10 problems: Maximum Depth, Invert Binary Tree, Diameter of Binary Tree, Balanced Binary Tree, Binary Tree Level Order Traversal, Right Side View, Lowest Common Ancestor, Path Sum II, Construct Tree from Preorder and Inorder, and Binary Tree Maximum Path Sum.

Self-check: In Binary Tree Maximum Path Sum, why is the value you return to the parent different from the value you use to update the global answer?

Resources:
- [LeetCode Explore: Binary Tree](https://leetcode.com/explore/) (LeetCode)
- [Binary tree data structure](https://www.geeksforgeeks.org/binary-tree-data-structure/) (GeeksforGeeks)
- [NeetCode Roadmap (Trees)](https://neetcode.io/roadmap) (NeetCode)

### Binary Search Trees

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/binary-search-trees

Use the BST ordering property for O(h) search, insert and delete, validate BSTs, and understand why balanced trees guarantee O(log n).

A binary search tree keeps every value in the left subtree smaller than the node and every value in the right subtree larger. This makes search, insert and delete O(h), where h is the height.

#### Key operations
- **Search / insert**: go left or right by comparison.
- **Delete**: three cases. A leaf is removed directly, a node with one child is replaced by it, and a node with two children is replaced by its **inorder successor** (smallest in the right subtree), which is then deleted.
- **Inorder traversal yields sorted order**, which solves k-th smallest, validate BST and two-sum-in-BST.
- **Floor / ceiling, successor / predecessor** by walking and remembering the last candidate.

#### Balance
Inserting sorted data creates a linked-list-shaped tree with h = n. Self-balancing trees (**AVL**, **red-black**) rotate nodes to keep h = O(log n). You rarely implement them in interviews, but you should know that `std::map`, `TreeMap` and `std::set` are red-black trees, which is why their operations are O(log n).

#### Pitfalls
Validating a BST by only comparing a node with its direct children is wrong; you must pass down a valid (min, max) range or check that the inorder sequence is strictly increasing. Watch for duplicates and integer overflow when using INT_MIN/INT_MAX as bounds (use long or null).

Key concepts: BST property and search, Insert and delete, Validate BST with ranges, Inorder as sorted order, Floor, ceil, successor, AVL and red-black trees (concepts), BST iterator.

Mini project: Implement a BST class with insert, search, delete and inorder, then solve: Validate BST, Kth Smallest Element in a BST, LCA of a BST, Delete Node in a BST, Convert Sorted Array to BST, BST Iterator, and Two Sum IV.

Self-check: Why does checking only node.left.val < node.val < node.right.val at every node fail to validate a BST? Give a counterexample.

Resources:
- [VisuAlgo: Binary Search Tree](https://visualgo.net/en/bst) (VisuAlgo)
- [Binary search tree](https://www.geeksforgeeks.org/binary-search-tree-data-structure/) (GeeksforGeeks)
- [Data Structure Visualizations (USFCA)](https://www.cs.usfca.edu/~galles/visualization/Algorithms.html) (USFCA)

### Heaps and Priority Queues

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/heaps-priority-queues

Use binary heaps to repeatedly extract the smallest or largest item in O(log n), and apply them to top-k, merging and scheduling problems.

A **binary heap** is a complete binary tree stored in an array where each parent is smaller (min-heap) or larger (max-heap) than its children. For index i, children are 2i + 1 and 2i + 2 and the parent is (i - 1) / 2.

#### Operations
- Push: append and **sift up**, O(log n).
- Pop top: move the last element to the root and **sift down**, O(log n).
- Peek: O(1).
- Build a heap from n elements in O(n) with bottom-up heapify (a classic theory question).

A **priority queue** is the abstract type, and heaps are its usual implementation: `priority_queue` (max-heap by default in C++), `PriorityQueue` (min-heap in Java), `heapq` (min-heap in Python).

#### Patterns
- **Top k**: keep a min-heap of size k while scanning; the heap holds the k largest. O(n log k).
- **K-way merge**: merge k sorted lists by always popping the smallest head.
- **Two heaps**: a max-heap for the lower half and a min-heap for the upper half gives the running median.
- **Greedy scheduling**: always process the most urgent task (Task Scheduler, meeting rooms, IPO).
- **Dijkstra's algorithm** uses a min-heap of (distance, node).

#### Pitfalls
Forgetting that C++ and Java defaults differ, comparing pairs in the wrong order, and trying to update priorities in place (instead, push a new entry and skip stale ones when popped).

Key concepts: Array representation of a heap, Sift up, sift down, heapify, Library priority queues, Top-k with a size-k heap, K-way merge, Two heaps for running median, Lazy deletion of stale entries.

Mini project: Implement a min-heap from scratch, then solve 8 problems: Kth Largest Element in an Array, Kth Largest in a Stream, Top K Frequent Elements, K Closest Points to Origin, Merge k Sorted Lists, Last Stone Weight, Task Scheduler, and Find Median from Data Stream.

Self-check: To find the k largest elements in a stream, why do you use a min-heap of size k rather than a max-heap?

Resources:
- [VisuAlgo: Binary Heap](https://visualgo.net/en/heap) (VisuAlgo)
- [Heap data structure](https://www.geeksforgeeks.org/heap-data-structure/) (GeeksforGeeks)
- [NeetCode Roadmap (Heap)](https://neetcode.io/roadmap) (NeetCode)

### Tries (Prefix Trees)

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/tries

Store strings character by character in a tree for fast prefix lookups, autocomplete, word search and XOR maximisation.

A **trie** stores a set of strings where each edge is a character and each path from the root spells a prefix. Insert and search cost O(L) for a word of length L, independent of how many words are stored.

#### Structure
Each node holds children (an array of 26 for lowercase letters, or a hash map for larger alphabets) and a flag marking the end of a word. Optionally store a count of words passing through the node to answer "how many words start with this prefix".

#### Operations
- insert(word), search(word), startsWith(prefix).
- Delete by decrementing counts or unmarking end flags.
- Collect all words under a node for **autocomplete**.

#### Patterns
- **Prefix queries**: autocomplete, longest common prefix, replace words with their root.
- **Word Search II**: build a trie of the dictionary and DFS the grid once, pruning when the current path is not a prefix. Far faster than searching each word separately.
- **Bitwise trie**: store numbers bit by bit (from the highest bit) to find the maximum XOR pair in O(n * 32).
- **Wildcard search** ("b.d") with DFS over children.

#### Trade-offs
Tries can use a lot of memory (26 pointers per node). Hash sets are simpler when you only need exact lookups; tries win when prefixes matter.

Key concepts: Trie node design, Insert, search, startsWith, Prefix counts, Autocomplete, Trie + DFS (Word Search II), Bitwise trie for max XOR.

Mini project: Build a small autocomplete CLI backed by a trie that suggests the top 5 words for a prefix, then solve: Implement Trie, Design Add and Search Words, Replace Words, Word Search II, and Maximum XOR of Two Numbers in an Array.

Self-check: Why is Word Search II with a trie much faster than running Word Search separately for every dictionary word?

Resources:
- [Trie data structure](https://www.geeksforgeeks.org/trie-insert-and-search/) (GeeksforGeeks)
- [Aho-Corasick and tries](https://cp-algorithms.com/string/aho_corasick.html) (cp-algorithms)
- [LeetCode Explore](https://leetcode.com/explore/) (LeetCode)

### Segment Trees and Fenwick Trees

optional · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/segment-tree-fenwick

Answer range queries with point or range updates in O(log n) using segment trees and Binary Indexed Trees.

Prefix sums answer range queries in O(1) but break as soon as the array changes. When you need both **updates and range queries**, use a segment tree or a Fenwick tree for O(log n) per operation. These are mostly for contests and harder product-company rounds, so treat them as optional for most placements.

#### Fenwick tree (Binary Indexed Tree)
A compact array where index i stores the sum of a range whose length is the lowest set bit of i (`i & -i`). Point update and prefix query each walk O(log n) indices. Simple to code in about 10 lines, but limited to invertible operations like sum and XOR.

#### Segment tree
A binary tree where each node stores an aggregate (sum, min, max, gcd) of a segment. Build is O(n), point update and range query are O(log n). It supports any associative operation.
- **Lazy propagation** defers range updates ("add v to [l, r]") until needed, keeping them O(log n).
- Store it in an array of size 4n with recursive build, query and update functions.

#### Typical uses
Range sum/min with updates, counting inversions, "count of smaller numbers after self", and offline queries sorted by coordinate after **coordinate compression**.

Good enough to move on: you can code a Fenwick tree from memory and a recursive sum segment tree with point updates.

Key concepts: Fenwick tree point update, prefix query, Segment tree build, query, update, Min/max/gcd segment trees, Lazy propagation, Coordinate compression, Sparse table for static RMQ.

Mini project: Implement a Fenwick tree and a segment tree and verify both against brute force on random tests, then solve: Range Sum Query Mutable, Count of Smaller Numbers After Self, CSES Dynamic Range Sum Queries, CSES Dynamic Range Minimum Queries, and CSES Range Update Queries.

Self-check: Why can a Fenwick tree answer range sum queries but not directly answer range minimum queries with arbitrary updates?

Resources:
- [Segment Tree](https://cp-algorithms.com/data_structures/segment_tree.html) (cp-algorithms)
- [Fenwick Tree](https://cp-algorithms.com/data_structures/fenwick.html) (cp-algorithms)
- [CSES Problem Set (Range Queries)](https://cses.fi/problemset/) (CSES)

## Graph Algorithms

Model relationships as graphs and apply traversal, ordering, shortest path, connectivity and spanning tree algorithms.

### Graph Representation, BFS and DFS

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/graph-traversal

Represent graphs with adjacency lists and matrices, and explore them with BFS and DFS to find components, cycles and unweighted shortest paths.

A graph is a set of vertices connected by edges, which can be directed or undirected and weighted or unweighted. Many problems are graphs in disguise: grids, dependency lists, social networks, word ladders and state machines.

#### Representation
- **Adjacency list** (vector of vectors, list of lists): O(V + E) memory, the default choice.
- **Adjacency matrix**: O(V^2) memory, O(1) edge lookup, fine for small dense graphs.
- **Implicit graphs**: a grid where each cell connects to its 4 neighbours; generate neighbours on the fly with direction arrays.

#### BFS
Uses a queue and visits nodes in order of distance from the source. In an unweighted graph the first time you reach a node is via a shortest path. **Multi-source BFS** starts with several sources in the queue (Rotting Oranges, distance to nearest 0).

#### DFS
Uses recursion or a stack to go deep first. Useful for connected components, flood fill, cycle detection, path existence and as the base of topological sort and bridge finding.

#### Cycle detection
- Undirected: a visited neighbour that is not your parent means a cycle.
- Directed: track nodes on the current recursion path (three colours: unvisited, in progress, done). An edge to an in-progress node is a back edge, meaning a cycle.

#### Pitfalls
Marking visited when popping instead of when pushing in BFS (causes duplicates in the queue), forgetting disconnected components, and recursion depth on large grids. Both BFS and DFS run in O(V + E).

Key concepts: Adjacency list vs matrix, Grids as implicit graphs, Breadth-first search, Depth-first search, Connected components and flood fill, Multi-source BFS, Cycle detection (directed and undirected), Bipartite check, 0-1 BFS with a deque.

Mini project: Solve 10 problems: Number of Islands, Flood Fill, Max Area of Island, Rotting Oranges, 01 Matrix, Clone Graph, Pacific Atlantic Water Flow, Surrounded Regions, Is Graph Bipartite, and Word Ladder.

Self-check: Why does BFS give shortest paths in an unweighted graph but not in a weighted one?

Resources:
- [VisuAlgo: Graph Traversal](https://visualgo.net/en/dfsbfs) (VisuAlgo)
- [Breadth-first search](https://cp-algorithms.com/graph/breadth-first-search.html) (cp-algorithms)
- [Competitive Programmer's Handbook (Ch. 11-12)](https://cses.fi/book/book.pdf) (CSES)

### Topological Sort

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/topological-sort

Order the nodes of a directed acyclic graph so every edge points forward, using Kahn's algorithm or DFS finishing order.

A **topological order** lists the nodes of a directed acyclic graph (DAG) so that for every edge u -> v, u comes before v. It models dependencies: courses and prerequisites, build systems, task scheduling and spreadsheet recalculation.

#### Kahn's algorithm (BFS)
- Compute the **in-degree** of every node.
- Push all nodes with in-degree 0 into a queue.
- Pop a node, append it to the order, and decrement the in-degree of its neighbours; push any that reach 0.
- If the final order has fewer than V nodes, the graph has a **cycle**.
Using a min-heap instead of a queue gives the lexicographically smallest order.

#### DFS approach
Run DFS; when a node finishes (all descendants processed), push it to a list. Reversing the list gives a topological order. Detect cycles with the three-colour method.

#### Beyond ordering
- **DP on DAGs**: once nodes are in topological order, longest path, number of paths and earliest completion time become simple DP passes.
- **Alien Dictionary**: build edges from the first differing characters of adjacent words, then topologically sort letters.
- **Parallel courses**: BFS level count gives the minimum number of semesters.

Pitfall: an order exists only for DAGs. Always check for cycles and handle invalid inputs such as a word followed by its own prefix in Alien Dictionary.

Key concepts: DAGs and dependency graphs, Kahn's algorithm with in-degrees, DFS finishing order, Cycle detection via topo sort, DP on DAGs, Lexicographically smallest order.

Mini project: Solve 6 problems: Course Schedule, Course Schedule II, Find Eventual Safe States, Alien Dictionary, Parallel Courses, and Longest Increasing Path in a Matrix (as a DAG).

Self-check: How does Kahn's algorithm reveal that a directed graph contains a cycle?

Resources:
- [Topological sorting](https://cp-algorithms.com/graph/topological-sort.html) (cp-algorithms)
- [NeetCode Roadmap (Graphs)](https://neetcode.io/roadmap) (NeetCode)
- [CSES Problem Set (Graph Algorithms)](https://cses.fi/problemset/) (CSES)

### Shortest Path Algorithms

core · intermediate · about 7 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/shortest-paths

Find shortest paths in weighted graphs with Dijkstra, Bellman-Ford and Floyd-Warshall, and know which to use for given constraints.

When edges have weights, BFS is no longer enough. Pick the algorithm based on edge weights and whether you need one source or all pairs.

#### Dijkstra's algorithm
For **non-negative** weights from a single source. Keep a min-heap of (distance, node). Pop the closest unfinalised node and **relax** its edges: if `dist[u] + w < dist[v]`, update and push. Skip popped entries whose distance is stale. Complexity O((V + E) log V). Negative edges break it because a finalised node could later be improved.

#### Bellman-Ford
Relax every edge V - 1 times. Works with negative weights in O(V * E). A further improvement on a V-th pass means a **negative cycle** is reachable. Its "k iterations" structure also solves Cheapest Flights Within K Stops.

#### Floyd-Warshall
All-pairs shortest paths in O(V^3) with a triple loop over an intermediate node k. Great when V <= 400 and you need every distance.

#### Choosing
- Unweighted: BFS. Weights 0 or 1: 0-1 BFS.
- Non-negative weights: Dijkstra.
- Negative weights or a limit on edges used: Bellman-Ford.
- Small V, all pairs: Floyd-Warshall.
- DAG: relax in topological order in O(V + E).

#### Pitfalls
Overflow when adding to an "infinity" of INT_MAX, forgetting to skip stale heap entries, and reconstructing paths (store a parent array).

Key concepts: Edge relaxation, Dijkstra with a min-heap, Bellman-Ford and negative cycles, Floyd-Warshall all-pairs, Path reconstruction with parents, Shortest paths on DAGs, Choosing the right algorithm.

Mini project: Solve 7 problems: Network Delay Time, Path With Minimum Effort, Cheapest Flights Within K Stops, Swim in Rising Water, Find the City With the Smallest Number of Neighbours, Number of Ways to Arrive at Destination, and CSES Shortest Routes I.

Self-check: Give a small graph with a negative edge where Dijkstra returns a wrong distance, and explain why.

Resources:
- [Dijkstra's algorithm](https://cp-algorithms.com/graph/dijkstra.html) (cp-algorithms)
- [Bellman-Ford algorithm](https://cp-algorithms.com/graph/bellman_ford.html) (cp-algorithms)
- [VisuAlgo: Single-Source Shortest Paths](https://visualgo.net/en/sssp) (VisuAlgo)

### Union-Find (Disjoint Set Union)

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/union-find

Track groups of connected elements with near-constant-time union and find operations using path compression and union by rank.

Disjoint Set Union (DSU) maintains a collection of groups and supports two operations: **find(x)** returns the group representative of x, and **union(a, b)** merges two groups. It answers "are these two connected?" as edges arrive, without re-running a traversal.

#### Implementation
Store a `parent` array where each root points to itself.
- **Path compression**: during find, point every visited node directly to the root.
- **Union by rank or size**: attach the smaller tree under the larger one.
With both optimisations each operation is O(alpha(n)), effectively constant.

The whole data structure is about 15 lines, so memorise it.

#### Patterns
- **Dynamic connectivity**: number of components after each edge (Number of Provinces, islands being added).
- **Cycle detection in undirected graphs**: an edge whose endpoints already share a root creates a cycle (Redundant Connection).
- **Kruskal's MST** uses DSU to skip edges that would form a cycle.
- **Grouping by equivalence**: Accounts Merge, Satisfiability of Equality Equations, Similar String Groups.
- **Offline queries**: sort queries and edges by weight and union as you go.

#### Limits
DSU does not support splitting groups or listing a group's members efficiently (you would need extra bookkeeping), and it works on undirected connectivity only.

Key concepts: Parent array and find, Path compression, Union by rank or size, Counting components, Cycle detection with DSU, Offline queries sorted by weight.

Mini project: Implement a DSU class with size tracking, then solve 6 problems: Number of Provinces, Redundant Connection, Accounts Merge, Number of Operations to Make Network Connected, Satisfiability of Equality Equations, and Most Stones Removed with Same Row or Column.

Self-check: Without path compression or union by rank, what shape of tree makes find() O(n), and how do the two optimisations prevent it?

Resources:
- [Disjoint Set Union](https://cp-algorithms.com/data_structures/disjoint_set_union.html) (cp-algorithms)
- [VisuAlgo: Union-Find DS](https://visualgo.net/en/ufds) (VisuAlgo)
- [USACO Guide: DSU](https://usaco.guide/gold/dsu) (USACO Guide)

### Minimum Spanning Trees

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/minimum-spanning-tree

Connect all vertices at minimum total edge cost with Kruskal's and Prim's algorithms and understand the cut property behind them.

A **spanning tree** connects all V vertices of an undirected graph using exactly V - 1 edges with no cycles. A **minimum spanning tree (MST)** has the smallest possible total weight. Think of laying cable or roads to connect every city as cheaply as possible.

#### Kruskal's algorithm
Sort edges by weight, then add each edge if it connects two different components (checked with union-find). Stop after V - 1 edges. O(E log E), dominated by sorting. Easiest to code when you have an edge list.

#### Prim's algorithm
Grow the tree from a start vertex: repeatedly add the cheapest edge leaving the current tree, using a min-heap. O(E log V). Natural for adjacency lists and dense graphs (an O(V^2) array version works for complete graphs like "connect all points").

#### Why they work
The **cut property**: for any split of vertices into two groups, the lightest edge crossing the split belongs to some MST. Both algorithms repeatedly pick such an edge, which is a classic greedy proof.

#### Variations
- Min Cost to Connect All Points (complete graph, Prim's is efficient).
- Checking which edges are critical or pseudo-critical.
- Maximum spanning tree by sorting descending.

Pitfall: MST is about total weight, not shortest paths. The path between two nodes in an MST is not necessarily their shortest path.

Key concepts: Spanning tree definition, Kruskal's algorithm, Prim's algorithm, Cut property, MST vs shortest path tree, Critical edges in MST.

Mini project: Implement both Kruskal and Prim and verify they give the same total on random graphs, then solve: Min Cost to Connect All Points, Connecting Cities With Minimum Cost, CSES Road Reparation, and Find Critical and Pseudo-Critical Edges in MST.

Self-check: Why does the path between two vertices in an MST not have to be the shortest path between them?

Resources:
- [Kruskal's algorithm with DSU](https://cp-algorithms.com/graph/mst_kruskal_with_dsu.html) (cp-algorithms)
- [Prim's algorithm](https://cp-algorithms.com/graph/mst_prim.html) (cp-algorithms)
- [VisuAlgo: MST](https://visualgo.net/en/mst) (VisuAlgo)

### Advanced Graph Topics

optional · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/advanced-graphs

Strongly connected components, bridges and articulation points, and Euler paths for harder rounds and competitive programming.

These algorithms rarely appear in standard placement tests but come up at top product companies and in contests. Learn them once core graphs feel comfortable.

#### Strongly connected components
In a directed graph, an SCC is a maximal set of nodes where every node can reach every other. **Kosaraju's algorithm** runs DFS to get finishing order, reverses all edges, then runs DFS in decreasing finish order; each tree found is one SCC. **Tarjan's algorithm** finds them in one DFS using discovery times and low-links. Compressing SCCs into single nodes produces a DAG, which enables DP on top.

#### Bridges and articulation points
A **bridge** is an edge whose removal disconnects the graph; an **articulation point** is such a vertex. Both come from a DFS that tracks `tin[u]` (discovery time) and `low[u]` (earliest time reachable using one back edge). An edge u-v is a bridge if `low[v] > tin[u]`. LeetCode's Critical Connections in a Network is exactly this.

#### Euler paths
A path that uses every edge exactly once exists when zero or two vertices have odd degree (undirected). Hierholzer's algorithm constructs it; Reconstruct Itinerary is the classic interview version.

#### Others worth knowing by name
Lowest common ancestor with binary lifting, maximum flow (Ford-Fulkerson / Dinic) and bipartite matching.

Key concepts: Kosaraju's SCC algorithm, Tarjan's SCC algorithm, Bridges and articulation points, Condensation graph, Euler paths and Hierholzer, Binary lifting for LCA, Max flow basics.

Mini project: Solve 5 problems: Critical Connections in a Network, Reconstruct Itinerary, CSES Planets and Kingdoms (SCC), CSES Flight Routes Check, and CSES Company Queries I (binary lifting).

Self-check: What do tin[u] and low[u] represent in the bridge-finding DFS, and why does low[v] > tin[u] mean u-v is a bridge?

Resources:
- [Strongly connected components](https://cp-algorithms.com/graph/strongly-connected-components.html) (cp-algorithms)
- [Finding bridges](https://cp-algorithms.com/graph/bridge-searching.html) (cp-algorithms)
- [CSES Problem Set](https://cses.fi/problemset/) (CSES)

## Greedy and Dynamic Programming

Two optimisation paradigms: make locally best choices when they are provably safe, and otherwise build answers from overlapping subproblems.

### Greedy Algorithms

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/greedy-algorithms

Make the locally optimal choice at each step when an exchange argument proves it leads to a global optimum, especially for intervals and scheduling.

A greedy algorithm builds a solution step by step, always taking the choice that looks best right now, and never reconsidering. When it works it is simple and fast (often just a sort plus a scan). The hard part is knowing **when** it works.

#### Proving a greedy choice
- **Exchange argument**: take any optimal solution that differs from greedy's choice, swap in the greedy choice and show the result is no worse.
- **Stays ahead**: show greedy's partial solution is always at least as good as any other after each step.
If you cannot find such an argument, try a counterexample; coin change with coins {1, 3, 4} and target 6 breaks the "largest coin first" greedy (4+1+1 vs 3+3).

#### Classic greedy families
- **Interval scheduling**: sort by end time and pick non-overlapping intervals (Non-overlapping Intervals, minimum arrows to burst balloons).
- **Merging intervals**: sort by start and extend.
- **Jump game**: track the farthest reachable index.
- **Resource allocation**: assign cookies, boats to save people (sort + two pointers).
- **Gas station**: if total gas >= total cost, the start is right after the point where the running tank goes negative.
- **Heap-based greedy**: Huffman coding, task scheduler, IPO.
- Fractional knapsack (greedy by value/weight) vs 0/1 knapsack (needs DP).

#### Pitfall
Greedy solutions that pass examples but fail hidden tests. Always test against a brute force on small random inputs when unsure.

Key concepts: Greedy choice property, Exchange argument proofs, Interval scheduling by end time, Merging and inserting intervals, Jump game reachability, Heap-driven greedy, Fractional vs 0/1 knapsack, Counterexamples and stress testing.

Mini project: Solve 9 problems: Jump Game, Jump Game II, Gas Station, Merge Intervals, Insert Interval, Non-overlapping Intervals, Minimum Number of Arrows to Burst Balloons, Partition Labels, and Candy. For two of them, write a brute force and random stress test.

Self-check: For maximum non-overlapping intervals, why does sorting by end time work while sorting by start time or by length fails?

Resources:
- [Jeff Erickson, Algorithms (Greedy chapter)](https://jeffe.cs.illinois.edu/teaching/algorithms/) (UIUC)
- [Greedy algorithms](https://www.geeksforgeeks.org/greedy-algorithms/) (GeeksforGeeks)
- [NeetCode Roadmap (Greedy, Intervals)](https://neetcode.io/roadmap) (NeetCode)

### Dynamic Programming Foundations (1D)

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/dp-foundations

Recognise overlapping subproblems, define states and transitions, and convert recursion to memoization and bottom-up tables for 1D problems.

Dynamic programming (DP) is recursion plus remembering. When a brute-force recursion solves the **same subproblem many times** and the problem has **optimal substructure** (the best answer is built from best answers to smaller parts), you can store results and cut exponential time to polynomial.

#### The four-step method
- **State**: what does `dp[i]` mean in one precise sentence? For example "the maximum money robbed from houses 0..i".
- **Transition**: how does `dp[i]` depend on smaller states? For House Robber, `dp[i] = max(dp[i-1], dp[i-2] + a[i])`.
- **Base cases**: the smallest states answered directly.
- **Answer**: which state (or max over states) is the final answer.

#### Top-down vs bottom-up
- **Memoization**: write the recursion, cache results in an array or map. Easiest to derive from brute force.
- **Tabulation**: fill a table in dependency order with loops. Avoids recursion depth issues and enables **space optimisation**: if `dp[i]` depends only on the last two states, keep two variables.

Start with memoization, then convert once it works.

#### Classic 1D problems
Climbing Stairs, House Robber (and the circular version), Min Cost Climbing Stairs, Decode Ways, Coin Change (min coins), Word Break, and Maximum Product Subarray.

#### Pitfalls
Vague state definitions (the number one cause of wrong DP), wrong iteration order in tabulation, and forgetting that "count ways" answers often need a modulus.

Key concepts: Overlapping subproblems, Optimal substructure, Defining state precisely, Memoization (top-down), Tabulation (bottom-up), Space optimisation, Counting vs optimisation DP.

Mini project: For each of 8 problems write brute force, memoized and tabulated versions: Climbing Stairs, Min Cost Climbing Stairs, House Robber, House Robber II, Decode Ways, Coin Change, Word Break, and Maximum Product Subarray.

Self-check: In Coin Change (minimum coins), what is the state, the transition, and why is greedy not enough?

Resources:
- [Competitive Programmer's Handbook (Ch. 7)](https://cses.fi/book/book.pdf) (CSES)
- [Introduction to dynamic programming](https://cp-algorithms.com/dynamic_programming/intro-to-dp.html) (cp-algorithms)
- [NeetCode Roadmap (1-D DP)](https://neetcode.io/roadmap) (NeetCode)

### 2D DP: Grids and Knapsack

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/dp-grids-and-knapsack

Extend DP to two dimensions for grid paths and to the knapsack family of choose-or-skip problems with capacity constraints.

Many DP problems need two indices in the state. Two families cover most of them: grid DP and knapsack.

#### Grid DP
State `dp[i][j]` is the answer for reaching (or starting from) cell (i, j). Transitions come from neighbours such as up and left.
- Unique Paths, Unique Paths with obstacles, Minimum Path Sum, Triangle, Dungeon Game (fill from the bottom-right), and Cherry Pickup (advanced, two walkers).
- Space can usually be reduced to one row.

#### 0/1 knapsack
Each item is taken at most once. State `dp[i][w]` = best value using the first i items with capacity w. Transition: skip item i, or take it if it fits: `max(dp[i-1][w], dp[i-1][w - wt] + val)`. With a 1D array, iterate w **downwards** so each item is used once.

Knapsack in disguise is extremely common:
- **Subset sum** / Partition Equal Subset Sum (boolean knapsack).
- **Target Sum** (count subsets with a given difference).
- **Last Stone Weight II**.

#### Unbounded knapsack
Items can be reused: iterate w **upwards** in the 1D version. Coin Change II (count combinations) and Rod Cutting are the classics. Loop order matters: items outer, amount inner counts combinations; amount outer counts permutations.

Good enough to move on: you can explain why the direction of the inner loop decides between 0/1 and unbounded knapsack.

Key concepts: Grid path DP, Row-based space optimisation, 0/1 knapsack, Subset sum and partition, Unbounded knapsack, Combinations vs permutations loop order, Multi-walker grid DP.

Mini project: Solve 9 problems: Unique Paths II, Minimum Path Sum, Triangle, Partition Equal Subset Sum, Target Sum, Coin Change II, Last Stone Weight II, Ones and Zeroes, and CSES Book Shop.

Self-check: In the 1D-array version of 0/1 knapsack, what goes wrong if you iterate capacity from small to large?

Resources:
- [Knapsack problem](https://cp-algorithms.com/dynamic_programming/knapsack.html) (cp-algorithms)
- [CSES Problem Set (Dynamic Programming)](https://cses.fi/problemset/) (CSES)
- [NeetCode Roadmap (2-D DP)](https://neetcode.io/roadmap) (NeetCode)

### DP on Sequences and Strings

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/dp-on-sequences

Solve LIS, LCS, edit distance and palindrome problems by defining states over prefixes or pairs of indices.

Sequence DP is where interviews get serious. The states are indices into one or two strings or arrays, and many problems are variants of a few classics.

#### Longest Increasing Subsequence (LIS)
- O(n^2): `dp[i]` = length of LIS ending at i, taking the best `dp[j] + 1` over j < i with `a[j] < a[i]`.
- O(n log n): maintain `tails[k]` = smallest possible tail of an increasing subsequence of length k + 1, updated with binary search. Variants: Russian Doll Envelopes, Number of LIS, longest chain.

#### Longest Common Subsequence (LCS)
`dp[i][j]` = LCS of the first i characters of s and the first j of t. If they match, `1 + dp[i-1][j-1]`; otherwise `max(dp[i-1][j], dp[i][j-1])`. Many problems reduce to LCS: minimum insertions/deletions to convert strings, shortest common supersequence, longest palindromic subsequence (LCS of s and reverse(s)).

#### Edit distance
Same table shape with three operations (insert, delete, replace). Knowing how to reconstruct the actual operations from the table is a strong signal.

#### Other patterns
- Distinct Subsequences (counting).
- Wildcard and regular expression matching.
- Palindromic substrings with `dp[i][j]` over intervals.
- Stock problems with states like "holding / not holding / cooldown".

Tip: use 1-indexed tables with an extra row and column for empty prefixes to simplify base cases.

Key concepts: LIS O(n^2) and O(n log n), LCS and its reductions, Edit distance, Longest palindromic subsequence, Distinct subsequences (counting), Wildcard and regex matching, State machine DP (stocks), Reconstructing the solution.

Mini project: Solve 10 problems: Longest Increasing Subsequence, Russian Doll Envelopes, Longest Common Subsequence, Edit Distance, Delete Operation for Two Strings, Longest Palindromic Subsequence, Distinct Subsequences, Wildcard Matching, Best Time to Buy and Sell Stock with Cooldown, and Interleaving String.

Self-check: In the O(n log n) LIS algorithm, the tails array is not itself a valid subsequence. Why is its length still the correct answer?

Resources:
- [Longest increasing subsequence](https://cp-algorithms.com/sequences/longest_increasing_subsequence.html) (cp-algorithms)
- [MIT 6.006 (Dynamic Programming lectures)](https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/) (MIT OCW)
- [Dynamic programming](https://www.geeksforgeeks.org/dynamic-programming/) (GeeksforGeeks)

### Advanced DP: Intervals, Trees and Bitmasks

optional · advanced · about 12 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/advanced-dp

Tackle interval DP, DP on trees, bitmask DP over subsets and digit DP, which show up in hard interview rounds and contests.

Once 1D, 2D and sequence DP feel natural, these patterns unlock most remaining "hard" DP problems. They are optional for mass-recruiter placements but valuable for top product companies and contests.

#### Interval DP
State `dp[l][r]` = best answer for the subarray from l to r. Transition tries every split point k in between. Fill by increasing interval length. Classics: Matrix Chain Multiplication, Burst Balloons, Minimum Cost to Cut a Stick, Palindrome Partitioning II. Complexity is usually O(n^3).

#### DP on trees
Compute a value for each node from its children in a post-order DFS. Often the state has two flavours, like "node taken / not taken": House Robber III, maximum independent set, tree diameter, and binary tree cameras. **Rerooting** computes an answer for every possible root in O(n) with two passes (Sum of Distances in Tree).

#### Bitmask DP
When n <= 20, represent the set of used items as a mask. State `dp[mask][i]` might mean "visited set mask, currently at i", which solves travelling salesman in O(2^n * n^2). Other examples: assigning tasks to people, Partition to K Equal Sum Subsets, Shortest Path Visiting All Nodes.

#### Digit DP
Count numbers in [L, R] with a digit property by walking digits with a "tight" flag. Appears mainly in contests.

Tip: the transition for these problems is rarely obvious. Write the brute-force recursion first and let the parameters of that recursion become your state.

Key concepts: Interval DP and split points, Matrix chain multiplication, DP on trees with post-order, Rerooting technique, Bitmask DP over subsets, Travelling salesman DP, Digit DP.

Mini project: Solve 8 problems: Burst Balloons, Minimum Cost to Cut a Stick, Palindrome Partitioning II, House Robber III, Binary Tree Cameras, Partition to K Equal Sum Subsets, Shortest Path Visiting All Nodes, and CSES Counting Tilings or Sum of Distances in Tree.

Self-check: In Burst Balloons, why is it easier to choose the balloon burst LAST in an interval rather than first?

Resources:
- [USACO Guide: Gold DP modules](https://usaco.guide/gold/) (USACO Guide)
- [Competitive Programmer's Handbook (Ch. 7, 10, 14)](https://cses.fi/book/book.pdf) (CSES)
- [DP on broken profile and bitmasks](https://cp-algorithms.com/dynamic_programming/profile-dynamics.html) (cp-algorithms)

## Deliberate Practice and Contests

How to practise DSA efficiently: learn patterns instead of memorising problems, track weak areas, and optionally sharpen speed with competitive programming.

### Pattern-Based Problem Solving

core · intermediate · about 20 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/pattern-based-practice

Build a repeatable process for solving unseen problems: read constraints, map to known patterns, brute force first, optimise, test and review.

Solving 1000 random problems is less effective than solving 250 well-chosen ones deeply. The goal is to recognise **patterns** so an unseen problem feels like a variant of something you know.

#### A problem-solving routine
- Read carefully and restate the problem. Work one example by hand.
- Read the **constraints** to guess the target complexity (n = 10^5 means O(n log n) or better).
- Write down the brute force and its complexity. This alone often earns partial credit in interviews.
- Ask which pattern removes the bottleneck: hashing, two pointers, sliding window, binary search, heap, graph traversal, DP.
- Code cleanly, then test edge cases: empty input, one element, duplicates, negatives, maximum sizes.

#### How to practise
- Follow a curated list (NeetCode 150, Striver's A2Z sheet, Blind 75) topic by topic, then mix topics to practise recognition.
- Time-box: if stuck for 30-45 minutes, read the editorial, then **re-solve it from scratch** a few days later.
- Keep a **mistake log**: the problem, the pattern, and the insight you missed. Review it weekly.
- Use **spaced repetition**: revisit problems after 3, 7 and 21 days.
- Aim for a balance of roughly 30% easy, 60% medium, 10% hard for placements.

#### Signs you are ready
You can solve most mediums in 25-30 minutes, explain the complexity without hesitation, and you get fewer "wrong answer on edge case" verdicts.

Key concepts: Reading constraints for target complexity, Brute force first, then optimise, Pattern recognition checklist, Curated lists (NeetCode 150, A2Z sheet), Mistake log and spaced repetition, Edge case testing, Stress testing against brute force.

Mini project: Run a 4-week sprint: 5 problems per day following a curated list, log every problem in a spreadsheet (pattern, time taken, solved alone or not), and at the end of each week re-solve the 5 problems you struggled with most without notes.

Self-check: Given a new problem with n up to 2 * 10^5 asking for a count over subarrays, which patterns would you consider first and why?

Resources:
- [NeetCode Roadmap](https://neetcode.io/roadmap) (NeetCode)
- [Tech Interview Handbook: Coding interview prep](https://www.techinterviewhandbook.org/coding-interview-prep/) (Tech Interview Handbook)
- [Striver's A2Z DSA resources](https://takeuforward.org/) (takeUforward)

### Competitive Programming

optional · advanced · about 30 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/competitive-programming

Sharpen speed and depth through timed contests on Codeforces, CodeChef, AtCoder and LeetCode, and learn to upsolve effectively.

Competitive programming (CP) is timed problem solving against others. It is not required for internships, but a good Codeforces or CodeChef rating is a strong resume signal in India, and contests train speed and accuracy under pressure, which directly helps in online assessments.

#### Where to compete
- **LeetCode weekly and biweekly contests**: closest to interview style.
- **Codeforces**: Div. 2/3/4 rounds, the main global platform. Ratings are widely recognised.
- **CodeChef**: Starters contests, popular in Indian colleges.
- **AtCoder Beginner Contests**: very clean problems, great for learning.
- **CSES problem set**: 300 classic problems organised by topic, excellent for fundamentals.

#### How to improve
- **Upsolve**: after each contest, solve the next one or two problems you could not finish, using the editorial if needed. This is where most learning happens.
- Practise problems slightly above your rating (about +100 to +300).
- Keep a clean template (fast I/O, common helpers) but understand everything in it.
- Learn to debug quickly: print intermediate values, test edge cases, and stress test against brute force.

#### Balance
CP rewards clever tricks and heavy math that interviews rarely need, and interviews reward communication and clean code that CP ignores. If placements are close, prioritise interview-style practice and keep CP as a weekly habit.

Key concepts: LeetCode contests, Codeforces rounds and ratings, CodeChef and AtCoder, CSES problem set, Upsolving after contests, Contest template and debugging, Time management in contests.

Mini project: Participate in 8 consecutive weekly contests (mix of LeetCode and Codeforces Div. 3/4), upsolve at least one extra problem after each, and track your rating and the topics of the problems you missed.

Self-check: Why is upsolving after a contest usually more valuable than the contest itself, and how do you choose which problems to upsolve?

Resources:
- [Codeforces](https://codeforces.com/) (Codeforces)
- [AtCoder](https://atcoder.jp/) (AtCoder)
- [CSES Problem Set](https://cses.fi/problemset/) (CSES)
- [USACO Guide](https://usaco.guide/) (USACO Guide)

## Object-Oriented Design and Patterns

Model real problems with classes and interfaces, apply SOLID to keep code easy to change, and recognise the handful of design patterns interviewers actually ask about.

### OOP Principles

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/oop-principles

Understand encapsulation, abstraction, inheritance and polymorphism well enough to explain them with your own examples and use them in code.

OOP questions appear in almost every placement interview, usually as "explain the four pillars with an example" followed by a follow-up that checks whether you really understand them. Memorised definitions fall apart at the follow-up, so learn each idea through code.

#### The four pillars, practically
- **Encapsulation**: keep state private and expose behaviour. A `BankAccount` exposes `deposit()` and `withdraw()` that enforce rules; nobody sets `balance` directly.
- **Abstraction**: callers depend on *what* something does, not *how*. An interface `PaymentMethod` with `pay(amount)` hides whether it is UPI, card or wallet.
- **Inheritance**: an "is-a" relationship that reuses behaviour. Useful, but deep hierarchies become rigid.
- **Polymorphism**: one call, many behaviours. **Runtime** polymorphism is method overriding through a base reference (virtual functions in C++); **compile-time** polymorphism is overloading and templates/generics.

#### Ideas interviewers probe next
- **Composition over inheritance**: a `Car` *has an* `Engine` rather than *being* one. Prefer composition when the relationship is "has-a" or behaviour needs to change at runtime.
- Abstract class vs interface: an abstract class can hold state and partial implementation; an interface is a pure contract (Java allows multiple interfaces, single class inheritance).
- Access modifiers, constructors, destructors, `static` members, and in C++ the **virtual destructor** rule for base classes.
- Overloading vs overriding, and why overriding needs the same signature.

#### Pitfalls
- Using inheritance only to reuse code, which creates fragile "is-a" claims that are not true.
- Getters and setters for every field, which is encapsulation in name only.

Good enough to move on: you can design a small class hierarchy for shapes or payment methods, explain each pillar using it, and justify one place where you chose composition.

Key concepts: Classes, objects and constructors, Encapsulation and access modifiers, Abstraction with interfaces, Inheritance and its limits, Runtime vs compile-time polymorphism, Abstract class vs interface, Composition over inheritance, Virtual functions and vtables.

Mini project: Build a console payment system with a PaymentMethod interface and UPI, Card and Wallet implementations, a Wallet that composes a TransactionHistory, and a checkout function that works with any PaymentMethod. Write a short README mapping each OOP pillar to a line of your code.

Self-check: Give an example where inheritance is the wrong choice and composition is better, and explain what breaks if you use inheritance there.

Resources:
- [LearnCpp: Object-oriented programming chapters](https://www.learncpp.com/) (LearnCpp)
- [The Java Tutorials: Object-Oriented Programming Concepts](https://docs.oracle.com/javase/tutorial/java/concepts/) (Oracle)
- [Refactoring Guru: Design patterns and principles](https://refactoring.guru/design-patterns) (Refactoring Guru)

### SOLID and Clean Design

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/solid-principles

Apply the five SOLID principles plus DRY, KISS and YAGNI to write classes that are easy to extend, test and explain in a design round.

SOLID is a set of five guidelines for keeping object-oriented code flexible. In LLD and machine coding rounds, interviewers do not want the acronym recited; they watch whether your design **naturally follows** it.

#### The five principles
- **S, Single Responsibility**: a class should have one reason to change. An `Invoice` that also emails itself and writes to the database has three reasons.
- **O, Open/Closed**: open for extension, closed for modification. Adding a new discount type should mean adding a class, not editing a growing `if/else` chain.
- **L, Liskov Substitution**: a subclass must work anywhere its parent is expected. The classic violation is `Square extends Rectangle` breaking `setWidth`.
- **I, Interface Segregation**: many small interfaces beat one fat one. A `Printer` should not force a `fax()` method on devices that cannot fax.
- **D, Dependency Inversion**: high-level logic depends on abstractions, not concrete classes. `OrderService` takes a `PaymentGateway` interface, so tests can pass a fake.

#### Companion rules
- **DRY**: do not repeat knowledge (but two similar-looking lines are not always duplication).
- **KISS** and **YAGNI**: build what the requirement needs today. Over-engineering is a common LLD mistake.
- Meaningful names, small functions, and no hidden side effects.

#### How to practise
Take an old project and look for a class that changes for many reasons or a long `switch` on type. Refactor it using one principle at a time and notice how tests become easier.

Good enough to move on: for each letter you can show a small "before" snippet that violates it and an "after" snippet that fixes it.

Key concepts: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion and injection, DRY, KISS, YAGNI, Code smells and refactoring.

Mini project: Write a deliberately messy discount calculator (one class, a switch on customer type, direct database calls), then refactor it in five commits, one per SOLID principle, with unit tests that use a fake repository.

Self-check: Why does Square extending Rectangle violate Liskov Substitution, and how would you model the two shapes instead?

Resources:
- [Refactoring Guru: Refactoring and code smells](https://refactoring.guru/refactoring) (Refactoring Guru)
- [freeCodeCamp: SOLID principles explained](https://www.freecodecamp.org/news/solid-principles-explained-in-plain-english/) (freeCodeCamp)

### Creational and Structural Patterns

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/creational-structural-patterns

Learn Singleton, Factory, Builder, Adapter, Decorator, Facade and Proxy: the problem each solves, a minimal implementation, and when not to use it.

Design patterns are named solutions to recurring design problems. You only need a handful for interviews, but you must know the **problem** each one solves, because interviewers ask "why" far more than "how".

#### Creational patterns (how objects get made)
- **Singleton**: exactly one instance, such as a config or logger. Know the thread-safe version (double-checked locking or a static local in C++11) and the downsides: hidden global state and hard-to-test code.
- **Factory Method / Simple Factory**: a function decides which concrete class to create (`NotificationFactory.create("sms")`), so callers do not depend on concrete types.
- **Abstract Factory**: families of related objects (a light vs dark UI kit).
- **Builder**: constructing objects with many optional fields step by step, avoiding constructors with ten parameters.

#### Structural patterns (how objects fit together)
- **Adapter**: wrap an incompatible interface so it fits yours, such as adapting a third-party payment SDK.
- **Decorator**: add behaviour by wrapping, such as adding toppings to a pizza or logging to a data source, without subclass explosion.
- **Facade**: one simple entry point over a complicated subsystem.
- **Proxy**: a stand-in that controls access, for lazy loading, caching or permission checks.
- **Composite** (optional): treat trees of objects uniformly, like files and folders.

#### Pitfalls
- Applying patterns because they exist. Name a pattern only when the problem it solves is actually present.
- Confusing Decorator (adds behaviour, same interface) with Adapter (changes interface) and Proxy (controls access).

Good enough to move on: you can code Singleton, Factory, Builder and Decorator from scratch in your DSA language and give a real-world use for each.

Key concepts: Singleton and thread safety, Factory and Abstract Factory, Builder, Adapter, Decorator, Facade, Proxy, Composite, Prototype.

Mini project: Build a notification library: a Factory that returns Email, SMS or Push senders, a Builder for Notification objects with optional fields, a Decorator that adds retry and logging to any sender, and a thread-safe Singleton config loader.

Self-check: What is the difference between Adapter, Decorator and Proxy if all three wrap another object?

Resources:
- [Refactoring Guru: Design Patterns catalog](https://refactoring.guru/design-patterns/catalog) (Refactoring Guru)
- [SourceMaking: Design Patterns](https://sourcemaking.com/design_patterns) (SourceMaking)

### Behavioral Patterns

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/behavioral-patterns

Use Strategy, Observer, State, Command, Chain of Responsibility and Template Method to organise changing behaviour, the patterns most used in LLD rounds.

Behavioral patterns are about **who does what and how objects communicate**. They show up constantly in low-level design: pricing rules, event notifications, state machines and undo systems.

#### The ones to know well
- **Strategy**: swap an algorithm at runtime behind an interface. Parking fee calculation, sorting policies, payment methods and pricing all fit. This is the single most useful LLD pattern because it directly implements Open/Closed.
- **Observer**: subjects notify subscribers when something changes. Stock price alerts, YouTube subscriptions, UI events. Know the risk of memory leaks when observers never unsubscribe.
- **State**: an object changes behaviour when its internal state changes. A vending machine (Idle, HasMoney, Dispensing) or an order lifecycle is cleaner as State classes than as nested `if` checks on an enum.
- **Command**: wrap a request as an object so you can queue, log or undo it. Text editor undo/redo and job queues.
- **Chain of Responsibility**: pass a request along handlers until one handles it. Logging levels, approval workflows, middleware, ATM cash dispensing (2000, 500, 100 notes).
- **Template Method**: a base class fixes the algorithm skeleton; subclasses fill in steps.
- **Iterator** (optional): traverse a collection without exposing its internals.

#### Choosing between them
- Behaviour picked by the **caller** or config: Strategy.
- Behaviour driven by the object's **own state**: State.
- Many parties need to **react** to an event: Observer.
- Actions must be **stored or undone**: Command.

Good enough to move on: given a design prompt like "vending machine" or "notification service", you can name the pattern that fits, justify it in one sentence and sketch the classes.

Key concepts: Strategy, Observer, State, Command and undo, Chain of Responsibility, Template Method, Iterator, Mediator.

Mini project: Implement a vending machine using the State pattern, pluggable pricing with Strategy, low-stock alerts with Observer, and an admin action log with Command that supports undoing the last restock.

Self-check: When would you choose the State pattern over Strategy, given that both replace conditionals with polymorphic classes?

Resources:
- [Refactoring Guru: Behavioral patterns](https://refactoring.guru/design-patterns/behavioral-patterns) (Refactoring Guru)
- [SourceMaking: Behavioral patterns](https://sourcemaking.com/design_patterns/behavioral_patterns) (SourceMaking)

## Operating Systems

The OS concepts asked in every placement: processes and threads, scheduling, synchronization, deadlocks, memory management and file systems.

### Processes and Threads

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/processes-and-threads

Learn what a process is, how threads differ, how the OS switches between them, and the role of system calls and the kernel.

An operating system manages hardware and gives programs a clean, isolated environment. Most interview OS questions start here, so get the vocabulary precise.

#### Core ideas
- **Kernel vs user mode**: user programs cannot touch hardware directly; they ask the kernel via **system calls** (`read`, `write`, `fork`, `exec`). Switching into kernel mode has a cost.
- **Process**: a running program with its own address space (code, data, heap, stack), open files and a **Process Control Block** (PCB) holding its state, registers and scheduling info.
- **Process states**: new, ready, running, waiting (blocked), terminated. Be able to draw the transitions.
- **Thread**: a unit of execution inside a process. Threads share code, heap and open files but each has its own stack and registers. Creating and switching threads is cheaper than processes.
- **Context switch**: saving one task's registers and loading another's. It is pure overhead, which is why too many threads can slow a system down.
- `fork()` creates a child process that is a copy of the parent (with **copy-on-write** pages); `exec()` replaces the program. A classic question: how many times does "hello" print after three `fork()` calls? (8.)

#### Also know
- Zombie process (finished, parent has not called `wait`) vs orphan process (parent died first).
- User-level vs kernel-level threads, and multithreading models.
- Inter-process communication: pipes, shared memory, message queues, sockets, signals.

Good enough to move on: you can explain process vs thread with what each shares, draw the state diagram, and describe what happens during a context switch.

Key concepts: Kernel, user mode and system calls, Process, PCB and address space, Process states and transitions, Threads vs processes, Context switching, fork, exec and wait, Zombie and orphan processes, Inter-process communication.

Mini project: On Linux or WSL, write a C program that forks children, has each run a different command via exec, and waits for them; then write a two-thread program with pthreads or std::thread and print which values are shared and which are per-thread.

Self-check: What exactly do two threads of the same process share, what do they not share, and why is a thread switch cheaper than a process switch?

Resources:
- [Operating Systems: Three Easy Pieces](https://pages.cs.wisc.edu/~remzi/OSTEP/) (OSTEP)
- [MIT 6.S081 / 6.1810 Operating System Engineering](https://pdos.csail.mit.edu/6.828/) (MIT)
- [GeeksforGeeks: Operating Systems tutorial](https://www.geeksforgeeks.org/operating-systems/) (GeeksforGeeks)

### CPU Scheduling

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/cpu-scheduling

Compare FCFS, SJF, SRTF, Priority and Round Robin scheduling, compute waiting and turnaround times, and understand starvation and aging.

The scheduler decides which ready process runs next. Placement tests love numerical scheduling problems, so practise the Gantt charts until they are mechanical.

#### Metrics
- **Arrival time**, **burst time**, **completion time**.
- **Turnaround time** = completion - arrival. **Waiting time** = turnaround - burst. **Response time** = first run - arrival.
- **Throughput** and **CPU utilisation** at the system level.

#### Algorithms
- **FCFS**: simple queue, non-preemptive. Suffers from the **convoy effect** when a long job blocks short ones.
- **SJF**: shortest burst first, optimal average waiting time, but needs burst estimates and can starve long jobs. **SRTF** is its preemptive version.
- **Priority scheduling**: preemptive or not. Low-priority jobs can **starve**; **aging** gradually raises their priority.
- **Round Robin**: each process gets a **time quantum**. Too small means excessive context switches; too large degrades to FCFS. Good response time for interactive systems.
- **Multilevel queue** and **multilevel feedback queue**: separate queues for interactive and batch jobs, with processes moving between levels based on behaviour. Real OSes use variants of this.

#### How to solve numericals
Draw a timeline, track the ready queue at each arrival or completion, and fill a table with CT, TAT and WT. For Round Robin, be careful about the order when a new process arrives at the same moment another's quantum expires (state your assumption).

#### Also know
Preemptive vs non-preemptive scheduling, CPU-bound vs I/O-bound processes, and the idea behind Linux's Completely Fair Scheduler (optional).

Good enough to move on: you can solve a five-process Round Robin and SRTF question correctly in under ten minutes.

Key concepts: Turnaround, waiting and response time, FCFS and convoy effect, SJF and SRTF, Priority scheduling and aging, Round Robin and time quantum, Multilevel feedback queues, Linux CFS basics.

Mini project: Write a scheduling simulator that reads processes (arrival, burst, priority) and prints the Gantt chart plus average waiting and turnaround time for FCFS, SJF, SRTF, Priority and Round Robin, then compare results on the same input.

Self-check: Why does SJF give the minimum average waiting time, and what practical problems stop an OS from using it directly?

Resources:
- [OSTEP: Scheduling chapters](https://pages.cs.wisc.edu/~remzi/OSTEP/) (OSTEP)
- [GeeksforGeeks: CPU Scheduling in Operating Systems](https://www.geeksforgeeks.org/cpu-scheduling-in-operating-systems/) (GeeksforGeeks)

### Concurrency and Synchronization

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/concurrency-synchronization

Understand race conditions and critical sections, and solve them with mutexes, semaphores, condition variables and atomics, including the classic synchronization problems.

When threads share data, the order of their operations becomes unpredictable. **Synchronization** is how you make shared state correct again, and it is one of the most asked (and most misunderstood) OS topics.

#### The problem
- A **race condition** happens when the result depends on timing. `count++` is really read, add, write; two threads can both read 5 and both write 6.
- The code that touches shared state is the **critical section**. A correct solution needs **mutual exclusion**, **progress** and **bounded waiting**.

#### Tools
- **Mutex (lock)**: only the owner can unlock. Use it to guard a critical section. Keep critical sections short.
- **Semaphore**: an integer counter with `wait` (P) and `signal` (V). A **binary semaphore** acts like a lock; a **counting semaphore** limits access to N resources, such as a pool of 5 database connections.
- **Condition variable**: wait until a condition becomes true, always inside a loop that re-checks the condition (spurious wakeups).
- **Atomics** and compare-and-swap for lock-free counters.
- **Spinlock**: busy waits; good only for very short waits on multicore machines.
- Peterson's solution is a classic software-only algorithm worth knowing for theory questions.

#### Classic problems
- **Producer-consumer** (bounded buffer): two counting semaphores (empty, full) plus a mutex.
- **Readers-writers**: many readers or one writer; watch for writer starvation.
- **Dining philosophers**: illustrates deadlock; fix by ordering resources or limiting diners.

#### Pitfalls
Forgetting to unlock on an error path (use RAII `lock_guard` in C++ or try/finally in Java), locking in inconsistent order across threads, and using `if` instead of `while` around a condition wait.

Good enough to move on: you can write a correct bounded-buffer producer-consumer and explain mutex vs semaphore without mixing them up.

Key concepts: Race conditions and critical sections, Mutex and locks, Binary and counting semaphores, Condition variables, Producer-consumer problem, Readers-writers problem, Dining philosophers, Atomics and spinlocks, Peterson's solution.

Mini project: Implement a thread-safe bounded blocking queue using a mutex and two condition variables, stress test it with 4 producers and 4 consumers, and show that removing the lock produces lost or duplicated items.

Self-check: What is the difference between a mutex and a binary semaphore, and why must a condition variable wait be wrapped in a while loop?

Resources:
- [OSTEP: Concurrency chapters](https://pages.cs.wisc.edu/~remzi/OSTEP/) (OSTEP)
- [The Little Book of Semaphores](https://greenteapress.com/wp/semaphores/) (Green Tea Press)
- [LeetCode Concurrency problems](https://leetcode.com/problemset/concurrency/) (LeetCode)

### Deadlocks

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/deadlocks

Learn the four Coffman conditions, resource allocation graphs, and the strategies of prevention, avoidance with the Banker's algorithm, detection and recovery.

A **deadlock** is a set of processes each waiting for a resource held by another, so none can proceed. It is a favourite interview topic because it links theory (conditions, algorithms) with practical coding habits.

#### The four necessary conditions (all must hold)
- **Mutual exclusion**: a resource can be held by only one process.
- **Hold and wait**: a process holds one resource while waiting for another.
- **No preemption**: resources cannot be forcibly taken away.
- **Circular wait**: a cycle of processes each waiting on the next.

Break any one and deadlock cannot happen.

#### Handling strategies
- **Prevention**: design so a condition never holds. The most practical is **lock ordering** (always acquire locks in a global order), which removes circular wait. Requesting all resources at once removes hold and wait but wastes resources.
- **Avoidance**: grant a request only if the system stays in a **safe state**. The **Banker's algorithm** uses Max, Allocation, Need and Available matrices to find a safe sequence. Practise at least three numericals.
- **Detection and recovery**: allow deadlocks, detect cycles in a **wait-for graph** (a graph cycle problem you already know), then kill or roll back a victim.
- **Ignore it** (the ostrich approach): what most general-purpose OSes do for user resources.

#### Related terms
- **Starvation**: a process waits indefinitely but the system still progresses. Not the same as deadlock.
- **Livelock**: processes keep changing state in response to each other without progress.
- A **resource allocation graph** with single-instance resources is deadlocked if and only if it has a cycle.

Good enough to move on: you can list the four conditions, solve a Banker's safe sequence question, and explain how lock ordering prevents deadlock in real code.

Key concepts: Four Coffman conditions, Resource allocation graphs, Deadlock prevention and lock ordering, Banker's algorithm and safe state, Detection and recovery, Starvation vs livelock vs deadlock.

Mini project: Write a Banker's algorithm program that reads Allocation, Max and Available, prints a safe sequence or reports an unsafe state, and checks whether a new request can be granted. Then create a real two-lock deadlock in code and fix it with lock ordering.

Self-check: Which of the four deadlock conditions does consistent lock ordering break, and why is that the most common fix in practice?

Resources:
- [OSTEP: Common Concurrency Problems](https://pages.cs.wisc.edu/~remzi/OSTEP/) (OSTEP)
- [GeeksforGeeks: Banker's Algorithm](https://www.geeksforgeeks.org/bankers-algorithm-in-operating-system-2/) (GeeksforGeeks)

### Memory Management and Virtual Memory

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/memory-management

Understand paging, segmentation, page tables, TLBs, virtual memory, page faults, page replacement algorithms and thrashing.

Every process believes it has a large, private, contiguous memory. **Virtual memory** creates that illusion, and it is the densest OS topic in interviews.

#### From physical to virtual
- Early schemes used **contiguous allocation** with fixed or variable partitions. They suffer **internal fragmentation** (waste inside a block) and **external fragmentation** (free memory in scattered holes). Know first-fit, best-fit and worst-fit.
- **Paging** splits virtual memory into fixed-size **pages** and physical memory into **frames** of the same size. A **page table** maps page numbers to frame numbers. No external fragmentation, small internal fragmentation.
- Address translation: split the virtual address into page number and offset; practise questions like "32-bit address, 4 KB pages, how many page table entries?" (2^20).
- The **TLB** caches recent translations; effective access time questions combine TLB hit ratio with memory access time.
- **Multi-level page tables** save memory for sparse address spaces. **Segmentation** divides memory by logical units (code, stack) and can be combined with paging.

#### Virtual memory and demand paging
- Pages are loaded only when accessed. Accessing a page not in memory causes a **page fault**, handled by the OS reading it from disk.
- **Page replacement**: FIFO, **LRU**, **Optimal** (theoretical best, needs the future), and Clock (an LRU approximation). Practise counting faults for a reference string.
- **Belady's anomaly**: with FIFO, more frames can cause more faults. LRU and Optimal do not suffer from it.
- **Thrashing**: the system spends more time paging than running because the working sets do not fit. Fix with the working set model or by reducing multiprogramming.

#### Also know
Stack vs heap, memory leaks, and why `malloc`/`new` are not free operations.

Good enough to move on: you can compute page faults for FIFO, LRU and Optimal on a reference string and explain what happens step by step on a TLB miss followed by a page fault.

Key concepts: Contiguous allocation and fragmentation, Paging and page tables, Address translation numericals, TLB and effective access time, Segmentation, Demand paging and page faults, FIFO, LRU and Optimal replacement, Belady's anomaly, Thrashing and working sets, Multi-level page tables.

Mini project: Write a page replacement simulator that takes a reference string and frame count and reports faults for FIFO, LRU, Optimal and Clock, and use it to demonstrate Belady's anomaly with FIFO on the string 1,2,3,4,1,2,5,1,2,3,4,5.

Self-check: Walk through what happens, step by step, when a program reads an address whose page is not in the TLB and not in physical memory.

Resources:
- [OSTEP: Virtualization of memory chapters](https://pages.cs.wisc.edu/~remzi/OSTEP/) (OSTEP)
- [GeeksforGeeks: Page Replacement Algorithms](https://www.geeksforgeeks.org/page-replacement-algorithms-in-operating-systems/) (GeeksforGeeks)

### File Systems, Storage and I/O

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/file-systems-and-io

Learn how files, directories and inodes are organised, how disks and SSDs are scheduled, and how the OS handles I/O with interrupts and DMA.

This area is asked less often than processes or memory, but a few questions come up reliably, and it builds intuition you will need for databases and system design.

#### File systems
- A **file** is a named sequence of bytes; a **directory** maps names to files. Know single-level, two-level and tree directory structures.
- Unix file systems store metadata (size, permissions, timestamps, block pointers) in an **inode**; the file name lives in the directory entry. Hard links share an inode, soft links point to a path.
- **Allocation methods**: contiguous (fast, fragments), linked (no fragmentation, slow random access), indexed (an index block of pointers, used by inodes with direct and indirect blocks).
- **Free space management**: bitmaps or free lists.
- **Journaling** protects metadata consistency after a crash by writing intent to a log first.

#### Disks and I/O
- HDD access time = seek time + rotational latency + transfer time. **Disk scheduling** algorithms: FCFS, SSTF, SCAN (elevator), C-SCAN, LOOK. Practise total head movement numericals.
- SSDs have no seek time but have erase-before-write and wear leveling.
- **I/O techniques**: polling (CPU keeps checking), **interrupts** (device signals the CPU), and **DMA** (device transfers data to memory directly, freeing the CPU).
- **Buffering, caching and spooling** (printing queues).
- **RAID** levels 0, 1, 5 and 10: striping, mirroring and parity trade-offs (optional but common in some companies).

Good enough to move on: you can explain what an inode holds, compute head movement for SCAN and C-SCAN, and describe why DMA exists.

Key concepts: Files, directories and inodes, Hard links vs soft links, File allocation methods, Disk scheduling (SCAN, C-SCAN, LOOK), Interrupts, polling and DMA, Journaling, RAID levels.

Mini project: Write a disk scheduling simulator for FCFS, SSTF, SCAN, C-SCAN and LOOK that prints the head order and total movement, and on Linux use ls -i and ln to observe inode numbers for hard and soft links.

Self-check: If you delete the original file, what happens to a hard link to it versus a soft link, and why?

Resources:
- [OSTEP: Persistence chapters](https://pages.cs.wisc.edu/~remzi/OSTEP/) (OSTEP)
- [GeeksforGeeks: Disk Scheduling Algorithms](https://www.geeksforgeeks.org/disk-scheduling-algorithms/) (GeeksforGeeks)

## Computer Networks

How data moves between machines: layered models, IP addressing, TCP and UDP, DNS, HTTP and HTTPS, and the security basics that tie them together.

### How the Internet Works: OSI and TCP/IP

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/network-models

Understand the layered models of networking, what each layer is responsible for, and how a packet is encapsulated from your app down to the wire and back.

Networking is easiest to learn as a stack of layers, each solving one problem and relying on the one below. Interviewers use the models as a map, so you should be able to place any protocol or device on it.

#### The two models
- **OSI (7 layers)**: Physical, Data Link, Network, Transport, Session, Presentation, Application. A teaching model.
- **TCP/IP (4 or 5 layers)**: Link, Internet (IP), Transport (TCP/UDP), Application (HTTP, DNS, SMTP). This is what the real internet runs on.

#### What each layer does
- **Physical**: bits on copper, fibre or radio.
- **Data link**: frames between directly connected machines, **MAC addresses**, error detection (CRC), switches, Ethernet, Wi-Fi.
- **Network**: routing packets across networks with **IP addresses**; routers live here.
- **Transport**: process-to-process delivery using **ports**; reliability (TCP) or speed (UDP).
- **Application**: the protocols your software speaks.

#### Encapsulation
Your HTTP request becomes a TCP segment (adds ports), then an IP packet (adds IPs), then an Ethernet frame (adds MACs). Each hop's router strips the frame, reads the IP header, and re-frames it for the next link. **ARP** resolves an IP to a MAC on the local network.

#### Devices and terms
Hub (layer 1), switch (layer 2), router (layer 3), and gateway; LAN vs WAN; bandwidth vs latency vs throughput; circuit vs packet switching.

Good enough to move on: you can narrate, layer by layer, what happens when you type a URL and press Enter, which is one of the most common networking interview questions.

Key concepts: OSI model layers, TCP/IP model, Encapsulation and headers, MAC addresses and ARP, Hubs, switches and routers, Bandwidth, latency, throughput, What happens when you type a URL.

Mini project: Capture your own traffic with Wireshark while loading a website and annotate one request through every layer: Ethernet frame, IP header, TCP segment and HTTP payload, noting source and destination at each level.

Self-check: When a packet crosses three routers to reach a server, which addresses change at each hop and which stay the same?

Resources:
- [Computer Networking: A Top-Down Approach (author resources)](https://gaia.cs.umass.edu/kurose_ross/index.php) (Kurose and Ross)
- [MDN: How does the Internet work?](https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/How_does_the_Internet_work) (MDN)
- [Cloudflare Learning Center: What is the OSI model?](https://www.cloudflare.com/learning/ddos/glossary/open-systems-interconnection-model-osi/) (Cloudflare)

### IP Addressing, Subnetting and Routing

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/ip-addressing-routing

Work with IPv4 and IPv6 addresses, CIDR and subnet masks, private ranges and NAT, DHCP, and the basics of how routers choose paths.

The network layer gets packets from one machine to any other machine on the internet. Subnetting numericals are standard in aptitude-style CS tests, and NAT and DHCP explain everyday networking behaviour.

#### IPv4 and CIDR
- An IPv4 address is 32 bits, written as four octets (`192.168.1.10`).
- **CIDR notation** `/24` means the first 24 bits are the network part. A /24 has 256 addresses, 254 usable hosts (network and broadcast addresses are reserved).
- **Subnetting**: borrowing host bits to split a network. Practise questions like "divide 10.0.0.0/24 into 4 subnets" (four /26 blocks of 64) and "which subnet does this IP belong to" by ANDing with the mask.
- Classful addressing (A, B, C) is legacy but still appears in some tests.

#### Private addresses and NAT
- Private ranges: `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`. They are not routable on the public internet.
- **NAT** lets many private devices share one public IP by rewriting addresses and ports at the router. It is why your laptop's IP is different from what websites see.
- **DHCP** hands out IP, subnet mask, gateway and DNS server automatically (Discover, Offer, Request, Acknowledge).

#### IPv6
128-bit addresses written in hex, no need for NAT, simplified header. Know the shorthand (`::`) and why IPv6 exists (IPv4 exhaustion).

#### Routing
- Routers forward using a **routing table** and **longest prefix match**.
- Interior routing: distance vector (RIP, Bellman-Ford based) vs link state (OSPF, Dijkstra based). You already know both algorithms from graphs.
- **BGP** connects autonomous systems across the internet (optional depth).
- **ICMP** powers `ping` and `traceroute` via TTL expiry.

Good enough to move on: you can compute network address, broadcast address and host range for any IP and prefix, and explain NAT to a friend.

Key concepts: IPv4 structure and CIDR, Subnet masks and subnetting numericals, Private ranges and NAT, DHCP, IPv6 basics, Routing tables and longest prefix match, RIP vs OSPF, ICMP, ping and traceroute, BGP overview.

Mini project: Write a subnet calculator CLI that takes an IP in CIDR notation and prints the network address, broadcast address, usable host range and host count, and can split a block into N equal subnets. Verify a few outputs with traceroute and ipconfig/ip addr on your machine.

Self-check: How many usable hosts does 172.16.5.0/27 have, what is its broadcast address, and does 172.16.5.40 belong to it?

Resources:
- [Cloudflare Learning Center: What is a subnet?](https://www.cloudflare.com/learning/network-layer/what-is-a-subnet/) (Cloudflare)
- [Cloudflare Learning Center: What is NAT?](https://www.cloudflare.com/learning/network-layer/what-is-nat/) (Cloudflare)
- [Kurose and Ross: Network layer resources](https://gaia.cs.umass.edu/kurose_ross/index.php) (Kurose and Ross)

### Transport Layer: TCP and UDP

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/tcp-and-udp

Learn how TCP delivers reliable ordered streams with handshakes, acknowledgements, flow and congestion control, and when lightweight UDP is the better choice.

The transport layer turns host-to-host delivery into **process-to-process** communication using ports. TCP vs UDP is one of the most predictable interview questions, but the follow-ups go deep, so understand the mechanisms.

#### TCP: reliable byte stream
- **Connection setup** with the **three-way handshake**: SYN, SYN-ACK, ACK. Teardown uses FIN and ACK (four steps), and the side that closes first waits in **TIME_WAIT**.
- **Reliability**: sequence numbers, acknowledgements, retransmission on timeout, and duplicate ACKs triggering fast retransmit.
- **Flow control**: the receiver advertises a window so a fast sender does not overwhelm it (sliding window, the same idea as the DSA pattern).
- **Congestion control**: slow start, congestion avoidance, and multiplicative decrease on loss, which protect the network as a whole.
- Ordered delivery and no duplicates, at the cost of latency and head-of-line blocking.

#### UDP: fire and forget
- No connection, no ordering, no retransmission. An 8-byte header.
- Used for DNS queries, video calls, online games, live streaming, and as the base for **QUIC** (HTTP/3), which re-implements reliability in user space.

#### Choosing
- Correctness of every byte matters (web pages, payments, file transfer): TCP.
- Freshness matters more than completeness (voice, gaming): UDP.

#### Ports and sockets
Well-known ports: 80 HTTP, 443 HTTPS, 53 DNS, 22 SSH, 25 SMTP. A **socket** is identified by the 5-tuple (protocol, source IP, source port, destination IP, destination port), which is why one server port can serve thousands of clients.

Good enough to move on: you can draw the handshake, explain flow control vs congestion control, and justify TCP or UDP for five different applications.

Key concepts: Ports and sockets, Three-way handshake and teardown, Reliability: ACKs and retransmission, Flow control and sliding window, Congestion control, UDP and its use cases, TCP vs UDP comparison, QUIC and HTTP/3.

Mini project: Write a TCP echo server and client and a UDP equivalent using sockets in Python or C++, then add a simple chat room to the TCP server. Capture the handshake in Wireshark and identify SYN, SYN-ACK and ACK packets.

Self-check: What is the difference between flow control and congestion control, and which party (sender, receiver, network) each one protects?

Resources:
- [Cloudflare Learning Center: TCP/IP](https://www.cloudflare.com/learning/ddos/glossary/tcp-ip/) (Cloudflare)
- [Beej's Guide to Network Programming](https://beej.us/guide/bgnet/) (Beej)
- [Kurose and Ross: Transport layer resources](https://gaia.cs.umass.edu/kurose_ross/index.php) (Kurose and Ross)

### DNS

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/dns

Understand how domain names resolve to IP addresses through recursive resolvers, root, TLD and authoritative servers, plus record types and caching.

DNS is the internet's phone book: it turns `example.com` into an IP address. It is short to learn and appears in almost every "what happens when you type a URL" answer.

#### Resolution step by step
- The browser checks its own cache, then the OS cache and the `hosts` file.
- The query goes to a **recursive resolver** (your ISP's, or a public one like 8.8.8.8 or 1.1.1.1).
- The resolver asks a **root server**, which points to the **TLD server** for `.com`, which points to the domain's **authoritative name server**, which returns the answer.
- The resolver caches the answer for its **TTL** and returns it. Recursive (resolver does the work for you) vs iterative (each server refers you onward) queries are a common question.

#### Record types to know
- **A** (IPv4) and **AAAA** (IPv6).
- **CNAME**: an alias to another name (`www` pointing to the root domain or a CDN).
- **MX**: mail servers. **TXT**: verification and email security (SPF, DKIM). **NS**: authoritative name servers.

#### Why it matters in engineering
- **TTL trade-off**: long TTLs mean fewer lookups but slow changes during a migration.
- DNS is used for simple load balancing and geo-routing (returning different IPs by region), which ties into system design.
- DNS runs mostly on **UDP port 53**, falling back to TCP for large responses.
- Security: DNS spoofing and cache poisoning, mitigated by DNSSEC; DNS over HTTPS for privacy.

Good enough to move on: you can explain the full resolution path with caching, pick the right record type for a scenario, and use `nslookup` or `dig` to inspect a domain.

Key concepts: Resolver, root, TLD, authoritative, Recursive vs iterative queries, A, AAAA, CNAME, MX, TXT, NS records, Caching and TTL, DNS-based load balancing, dig and nslookup, DNS security and DNSSEC.

Mini project: Use dig +trace on three domains and document each step of the resolution chain, then write a small script that sends a raw DNS query over UDP and parses the A records from the response.

Self-check: You changed your server's IP but some users still reach the old one for hours. What explains this and how would you plan the next migration?

Resources:
- [Cloudflare Learning Center: What is DNS?](https://www.cloudflare.com/learning/dns/what-is-dns/) (Cloudflare)
- [How DNS Works (comic)](https://howdns.works/) (howdns.works)
- [MDN: What is a domain name?](https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/What_is_a_domain_name) (MDN)

### HTTP, HTTPS and TLS

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/http-and-https

Learn the request-response model, methods, status codes, headers, cookies, HTTP versions and how TLS secures HTTPS connections.

HTTP is the application protocol of the web and of most APIs, so it matters in networking rounds, backend interviews and system design alike.

#### The basics
- A **request** has a method, path, headers and optional body; a **response** has a status code, headers and body.
- **Methods**: GET (read), POST (create), PUT (replace), PATCH (partial update), DELETE. Know which are **safe** and **idempotent** (GET, PUT and DELETE are idempotent; POST is not).
- **Status codes**: 2xx success (200, 201, 204), 3xx redirect (301, 302, 304), 4xx client errors (400, 401 vs 403, 404, 409, 429), 5xx server errors (500, 502, 503).
- HTTP is **stateless**. State is added with **cookies**, sessions or tokens (JWT).
- Useful headers: `Content-Type`, `Authorization`, `Cache-Control`, `ETag`, `Set-Cookie`, CORS headers.

#### Versions
- **HTTP/1.1**: persistent connections (keep-alive), but one request at a time per connection.
- **HTTP/2**: multiplexing many streams over one TCP connection, header compression.
- **HTTP/3**: runs over QUIC (UDP) to avoid TCP head-of-line blocking.

#### HTTPS and TLS
- HTTPS is HTTP inside **TLS**, which gives confidentiality, integrity and authentication.
- The **TLS handshake**: the client and server agree on a cipher, the server proves its identity with a **certificate** signed by a trusted CA, and they derive shared **symmetric keys** (asymmetric crypto is used only to set up the session because it is slow).
- Know symmetric vs asymmetric encryption, hashing, and what a digital signature proves.

#### Related
REST basics, WebSockets for two-way communication, and cookies vs local storage for auth tokens.

Good enough to move on: you can explain 401 vs 403, why PUT is idempotent but POST is not, and the purpose of each step of the TLS handshake.

Key concepts: Request and response structure, HTTP methods and idempotency, Status codes, Headers, cookies and sessions, HTTP/1.1 vs HTTP/2 vs HTTP/3, TLS handshake and certificates, Symmetric vs asymmetric encryption, WebSockets.

Mini project: Build a tiny HTTP/1.1 server on raw TCP sockets that parses a request line and headers and serves static files with correct status codes and Content-Type, then inspect a real HTTPS site's certificate chain in your browser and explain each certificate.

Self-check: Why does TLS use asymmetric cryptography during the handshake but symmetric cryptography for the rest of the connection?

Resources:
- [MDN: An overview of HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Overview) (MDN)
- [Cloudflare Learning Center: What is TLS?](https://www.cloudflare.com/learning/ssl/transport-layer-security-tls/) (Cloudflare)
- [High Performance Browser Networking](https://hpbn.co/) (Ilya Grigorik)

### Network Security Essentials

optional · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/network-security-basics

Know the common attacks and defences interviewers ask about: firewalls, VPNs, DDoS, man-in-the-middle, XSS, CSRF, SQL injection and secure authentication.

You do not need to be a security engineer, but SDE interviews and system design rounds often include a "how would you secure this?" follow-up. A clear mental model of attacks and defences is enough.

#### Network-level
- **Firewalls** filter traffic by rules on IPs, ports and protocols; stateful firewalls track connections.
- **VPNs** create an encrypted tunnel so traffic appears to come from another network.
- **Man-in-the-middle (MITM)**: an attacker intercepts traffic. Defence: TLS with proper certificate validation.
- **DDoS**: flooding a service with traffic from many machines. Defences: rate limiting, CDNs, scrubbing services, autoscaling.
- **SYN flood**: exhausting half-open TCP connections; mitigated with SYN cookies.

#### Application-level (the OWASP favourites)
- **SQL injection**: user input concatenated into queries. Fix with **parameterised queries**.
- **XSS**: injected scripts run in other users' browsers. Fix with output encoding and a Content Security Policy.
- **CSRF**: a malicious site triggers requests using a logged-in user's cookies. Fix with CSRF tokens and `SameSite` cookies.
- Broken authentication: store passwords with slow hashes (**bcrypt**, Argon2) plus salt, never plain or MD5.

#### Principles
- **Defence in depth**, **least privilege**, and never trusting client input.
- Authentication (who are you) vs authorization (what may you do).
- Hashing vs encryption vs encoding: hashing is one-way, encryption is reversible with a key, encoding (Base64) is not security at all.

Good enough to move on: for any feature you build, you can list the top three attacks it faces and the standard fix for each.

Key concepts: Firewalls and VPNs, MITM and certificate validation, DDoS and SYN floods, SQL injection, XSS and CSRF, Password hashing and salting, Hashing vs encryption vs encoding, OWASP Top 10.

Mini project: Take a small login and comments app you built, deliberately add SQL injection and stored XSS bugs, exploit them yourself in a local environment, then fix them with parameterised queries, output encoding and bcrypt password hashing.

Self-check: Why does a CSRF attack work even though the attacker never sees the victim's cookies, and how does a SameSite cookie stop it?

Resources:
- [OWASP Top Ten](https://owasp.org/www-project-top-ten/) (OWASP)
- [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/) (OWASP)
- [Cloudflare Learning Center: What is a DDoS attack?](https://www.cloudflare.com/learning/ddos/what-is-a-ddos-attack/) (Cloudflare)

## Database Management Systems

Design relational schemas, write interview-grade SQL, normalise tables, reason about transactions and isolation, use indexes well, and know when NoSQL fits.

### Relational Model and ER Design

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/relational-model-er

Model data with entities, relationships and cardinalities, turn ER diagrams into tables, and understand keys and integrity constraints.

DBMS is one of the three core CS subjects in placements (with OS and networks), and schema design questions show up in LLD and backend rounds too. Start with how to model data before writing any SQL.

#### The relational model
- Data lives in **relations** (tables) of **tuples** (rows) with typed **attributes** (columns).
- **Keys**: a **super key** uniquely identifies rows; a **candidate key** is a minimal super key; the chosen one is the **primary key**; others are **alternate keys**. A **foreign key** references another table's key.
- **Integrity constraints**: entity integrity (primary key not null), referential integrity (foreign keys point to real rows), plus `UNIQUE`, `NOT NULL`, `CHECK`.
- DBMS vs file systems: concurrency, recovery, integrity and a query language. Know the **three-schema architecture** and data independence.

#### ER modeling
- **Entities** (Student, Course), **attributes** (simple, composite, multivalued, derived), and **relationships** (Enrolls).
- **Cardinality**: one-to-one, one-to-many, many-to-many. **Participation**: total vs partial.
- **Weak entities** depend on an owner for identity (an OrderItem needs its Order).
- Specialisation and generalisation (optional).

#### ER to tables
- One-to-many: put the foreign key on the "many" side.
- Many-to-many: create a **junction table** with both foreign keys, such as `enrollments(student_id, course_id, grade)`.
- Multivalued attributes become their own table.

#### Pitfalls
Storing comma-separated lists in a column, using names as primary keys, and forgetting that a many-to-many relationship often has its own attributes.

Good enough to move on: you can design the schema for a college portal or a food delivery app with correct keys and relationships in 15 minutes.

Key concepts: Tables, rows and attributes, Super, candidate, primary and foreign keys, Integrity constraints, Entities, attributes and relationships, Cardinality and participation, ER diagram to tables, Weak entities, Three-schema architecture.

Mini project: Draw an ER diagram for a college placement portal (students, companies, drives, applications, interview rounds), convert it to tables with primary and foreign keys, and create it in PostgreSQL or MySQL with sample data.

Self-check: How do you represent a many-to-many relationship between students and courses that also stores each student's grade, and what is the primary key of that table?

Resources:
- [CMU 15-445 Intro to Database Systems](https://15445.courses.cs.cmu.edu/) (CMU)
- [GeeksforGeeks: DBMS tutorial](https://www.geeksforgeeks.org/dbms/) (GeeksforGeeks)
- [PostgreSQL Tutorial](https://www.postgresql.org/docs/current/tutorial.html) (PostgreSQL)

### SQL for Interviews

core · beginner · about 10 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/sql-for-interviews

Write the SQL asked in online assessments and interviews: joins, grouping, subqueries, window functions and classic questions like the Nth highest salary.

Many online assessments include one or two SQL questions, and they are easy marks if you have practised. Learn to think in **sets of rows**, not loops.

#### Core syntax
- `SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT`. Know the **logical execution order**: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. That explains why you cannot use a SELECT alias in WHERE.
- `WHERE` filters rows before grouping; `HAVING` filters groups after aggregation.
- Aggregates: `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`. `COUNT(*)` counts rows, `COUNT(col)` skips NULLs.
- `NULL` is not equal to anything, including NULL. Use `IS NULL`.

#### Joins
- **INNER JOIN**: matching rows only. **LEFT JOIN**: all rows from the left plus matches (NULLs otherwise). RIGHT and FULL OUTER joins, CROSS JOIN, and **self joins** (employee and manager in one table).
- "Find customers with no orders" is a LEFT JOIN with `WHERE o.id IS NULL`, or `NOT EXISTS`.

#### Subqueries and window functions
- Subqueries in WHERE (`IN`, `EXISTS`) and FROM; correlated subqueries run per row.
- **CTEs** with `WITH` make complex queries readable.
- **Window functions**: `ROW_NUMBER`, `RANK`, `DENSE_RANK`, `LAG`, `LEAD`, and running totals with `SUM(...) OVER (PARTITION BY ... ORDER BY ...)`. They solve "top N per group" cleanly.

#### Classic questions
Second or Nth highest salary (DENSE_RANK or LIMIT/OFFSET on distinct values), duplicate emails, department-wise highest salary, consecutive login days, and employees earning more than their managers.

Good enough to move on: you can solve the LeetCode SQL 50 study plan mostly without hints and explain the difference between RANK and DENSE_RANK.

Key concepts: SELECT, WHERE, ORDER BY, LIMIT, GROUP BY and HAVING, NULL handling, Inner, left, self and cross joins, Subqueries and EXISTS, CTEs, Window functions and ranking, Nth highest salary patterns, DDL, DML and DCL commands.

Mini project: Load a sample employees or e-commerce dataset into PostgreSQL and write 20 queries: department-wise top 3 earners, monthly revenue with running totals, customers with no orders, month-over-month growth using LAG, and duplicate detection.

Self-check: Why can you not use an alias defined in SELECT inside the WHERE clause, and how would you rewrite the query to filter on it?

Resources:
- [LeetCode SQL 50 study plan](https://leetcode.com/studyplan/top-sql-50/) (LeetCode)
- [SQLBolt interactive lessons](https://sqlbolt.com/) (SQLBolt)
- [Mode SQL Tutorial](https://mode.com/sql-tutorial/) (Mode)

### Normalization and Functional Dependencies

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/normalization

Use functional dependencies and closures to find keys, and normalise tables through 1NF, 2NF, 3NF and BCNF to remove redundancy and anomalies.

Normalization is the theory behind "good" schemas. It is heavily tested in written placement rounds and GATE-style questions, and interviewers like to ask why a denormalised table causes bugs.

#### Why normalise
A table like `orders(order_id, customer_name, customer_phone, product, price)` repeats customer data. That causes:
- **Update anomalies**: change a phone number in one row and not another.
- **Insert anomalies**: cannot add a customer without an order.
- **Delete anomalies**: deleting the last order loses the customer.

#### Functional dependencies
- `A -> B` means knowing A determines B.
- The **closure** of a set of attributes (A+) is everything it determines. If A+ contains all attributes, A is a super key. This is how you find candidate keys in exam questions.
- **Prime attributes** are part of some candidate key.

#### Normal forms
- **1NF**: atomic values, no repeating groups.
- **2NF**: 1NF and no **partial dependency** (a non-prime attribute depending on part of a composite key).
- **3NF**: 2NF and no **transitive dependency** (non-prime depends on another non-prime). Formal test: for every FD X -> A, X is a super key or A is prime.
- **BCNF**: for every FD X -> A, X is a super key. Stricter than 3NF; a BCNF decomposition may lose dependency preservation.
- 4NF and 5NF deal with multivalued and join dependencies (optional).

#### Decomposition properties
**Lossless join** (you can rebuild the original table) is mandatory; **dependency preservation** is desirable.

#### In the real world
Production systems usually aim for 3NF, then **denormalise deliberately** for read performance (for example, caching an order total), accepting the cost of keeping copies consistent.

Good enough to move on: given a relation and a set of FDs, you can find all candidate keys, state the highest normal form, and decompose it into BCNF.

Key concepts: Update, insert and delete anomalies, Functional dependencies, Attribute closure and finding keys, 1NF, 2NF, 3NF, BCNF, Lossless join and dependency preservation, Denormalization trade-offs, 4NF and 5NF.

Mini project: Take a single wide spreadsheet of college placement data (student, branch, HOD, company, package, round), list its functional dependencies, and normalise it step by step to BCNF, documenting the anomaly each step removes.

Self-check: For R(A, B, C, D) with A -> B and B -> C, what is the candidate key, what normal form is R in, and how would you decompose it?

Resources:
- [GeeksforGeeks: Normal Forms in DBMS](https://www.geeksforgeeks.org/normal-forms-in-dbms/) (GeeksforGeeks)
- [CMU 15-445 Intro to Database Systems](https://15445.courses.cs.cmu.edu/) (CMU)

### Transactions, ACID and Concurrency Control

core · intermediate · about 7 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/transactions-and-concurrency

Understand ACID, isolation levels and the anomalies they prevent, serializability, locking protocols, MVCC and crash recovery.

A **transaction** is a group of operations that must succeed or fail together, like moving money between accounts. This topic connects OS synchronization to databases and is asked by almost every product company.

#### ACID
- **Atomicity**: all or nothing, implemented with undo logs.
- **Consistency**: constraints hold before and after.
- **Isolation**: concurrent transactions behave as if run one at a time (to a configurable degree).
- **Durability**: committed data survives crashes, via the **write-ahead log** (WAL).

#### Anomalies and isolation levels
- **Dirty read**: reading uncommitted data.
- **Non-repeatable read**: the same row returns different values within one transaction.
- **Phantom read**: a repeated range query returns new rows.
- **Lost update**: two read-modify-write cycles overwrite each other.
- Levels: **Read Uncommitted**, **Read Committed** (PostgreSQL default), **Repeatable Read** (MySQL InnoDB default), **Serializable**. Be able to fill the table of which anomalies each level allows.

#### Concurrency control
- **Schedules** and **conflict serializability**: build a precedence graph; a cycle means not serializable (another graph cycle problem).
- **Two-phase locking (2PL)**: a growing phase then a shrinking phase guarantees serializability; **strict 2PL** holds write locks until commit to avoid cascading aborts. Shared vs exclusive locks.
- **MVCC**: readers see a snapshot and do not block writers. Used by PostgreSQL and InnoDB.
- Optimistic vs pessimistic locking: version columns vs `SELECT ... FOR UPDATE`.
- Deadlocks happen in databases too; the DB detects them and aborts a victim.

#### Recovery
Log-based recovery with undo and redo, checkpoints, and the idea behind ARIES (optional).

Good enough to move on: you can explain each ACID property with a bank transfer, map isolation levels to anomalies, and test a schedule for conflict serializability.

Key concepts: ACID properties, Dirty, non-repeatable and phantom reads, Isolation levels, Conflict serializability, Two-phase locking, MVCC, Optimistic vs pessimistic locking, Write-ahead logging and recovery, ARIES.

Mini project: In PostgreSQL, open two psql sessions and reproduce a lost update, a non-repeatable read and a phantom read under different isolation levels, then fix a concurrent seat-booking script using SELECT FOR UPDATE and separately with an optimistic version column.

Self-check: Which anomalies does Repeatable Read prevent that Read Committed does not, and what does Serializable add on top?

Resources:
- [PostgreSQL: Transaction Isolation](https://www.postgresql.org/docs/current/transaction-iso.html) (PostgreSQL)
- [CMU 15-445 Intro to Database Systems](https://15445.courses.cs.cmu.edu/) (CMU)
- [GeeksforGeeks: Concurrency Control in DBMS](https://www.geeksforgeeks.org/concurrency-control-in-dbms/) (GeeksforGeeks)

### Indexing and Query Performance

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/indexing-and-query-optimization

Learn how B+ tree and hash indexes work, clustered vs non-clustered indexes, composite index ordering, and how to read a query plan.

An index is a data structure that lets the database find rows without scanning the whole table. Indexing questions test whether you can connect DSA knowledge (trees, hashing, binary search) to real systems.

#### How indexes work
- Most relational indexes are **B+ trees**: balanced, very wide nodes sized to disk pages, with all data pointers in the leaves and leaves linked for fast **range scans**. Height stays around 3 or 4 even for millions of rows.
- Why not a binary search tree? Each node visit is a disk read, so fewer, wider nodes win.
- **Hash indexes** give O(1) equality lookups but cannot do ranges or sorting.

#### Kinds of indexes
- **Clustered (primary)**: table rows are stored in index order; only one per table (InnoDB clusters by primary key).
- **Non-clustered (secondary)**: a separate structure pointing to rows; a lookup may need an extra hop.
- **Composite index** on `(a, b)`: usable for filters on `a` or `a and b`, but not `b` alone. This **leftmost prefix rule** is a classic question.
- **Covering index**: contains every column a query needs, so the table is never touched.
- Dense vs sparse indexes (exam theory).

#### When indexes hurt
- Every insert, update and delete must also update each index, so write-heavy tables should have few.
- Low-selectivity columns (like a boolean) rarely benefit.
- Functions on a column (`WHERE LOWER(email) = ...`) or leading wildcards (`LIKE '%abc'`) usually prevent index use.

#### Reading query plans
Use `EXPLAIN` (and `EXPLAIN ANALYZE`) to see sequential scans vs index scans, join algorithms (nested loop, hash join, merge join) and estimated vs actual rows. Also avoid the **N+1 query** problem in application code.

Good enough to move on: you can explain why B+ trees suit disks, predict whether a composite index will be used, and speed up a slow query with EXPLAIN.

Key concepts: B+ tree indexes, Hash indexes, Clustered vs non-clustered, Composite indexes and leftmost prefix, Covering indexes, Index write costs and selectivity, EXPLAIN and query plans, Join algorithms.

Mini project: Generate a 1 million row orders table in PostgreSQL, time five common queries without indexes, add single, composite and covering indexes one at a time, and record the EXPLAIN ANALYZE output and speedup for each.

Self-check: Given an index on (city, age), which of these can use it: WHERE city = 'Pune', WHERE age = 21, WHERE city = 'Pune' AND age > 21? Why?

Resources:
- [Use The Index, Luke](https://use-the-index-luke.com/) (Markus Winand)
- [PostgreSQL: Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html) (PostgreSQL)

### NoSQL Databases

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/nosql-databases

Compare document, key-value, wide-column and graph databases with relational ones, and learn how to choose between SQL and NoSQL for a given workload.

"SQL or NoSQL?" appears in almost every system design interview. The right answer is always "it depends on the access pattern", followed by a concrete justification.

#### The main families
- **Key-value** (Redis, DynamoDB): get and put by key, extremely fast. Great for caches, sessions and counters.
- **Document** (MongoDB): JSON-like documents with flexible schemas; good when data is read as a whole unit, like a product with nested attributes.
- **Wide-column** (Cassandra, HBase): rows partitioned by key and optimised for massive write throughput and time-series style access.
- **Graph** (Neo4j): nodes and edges for highly connected data like social graphs and recommendations.

#### How they differ from relational databases
- Schemas are flexible or per-record instead of fixed.
- Most are built to **scale horizontally** by partitioning data across nodes.
- Joins are limited or absent, so data is often **denormalised** and modelled around queries rather than entities.
- Many favour availability with **eventual consistency** (you will study CAP in system design), though many now offer tunable or strong consistency.

#### Choosing
- Strong consistency, complex queries and relationships, transactions (payments, inventory): relational.
- Huge write volume, simple access by key, flexible or evolving data: NoSQL.
- Many real systems use both: PostgreSQL as the source of truth, Redis as a cache, Elasticsearch for search.

#### Pitfalls
Choosing MongoDB because "it is web scale" without an access-pattern reason, and assuming NoSQL means no schema design (bad partition keys create hot spots).

Good enough to move on: for a given feature you can name a suitable database type, explain the trade-off, and sketch how the data would be modelled.

Key concepts: Key-value stores, Document databases, Wide-column stores, Graph databases, Schema flexibility and denormalization, SQL vs NoSQL decision making, Partition keys and hot spots.

Mini project: Model a URL shortener and a blog with comments twice, once in PostgreSQL and once in MongoDB or Redis, implement the three most common queries in each, and write a one-page comparison of the trade-offs you noticed.

Self-check: For a chat application's message history, would you pick a relational database or a wide-column store, and what partition key would you use?

Resources:
- [MongoDB: Data modeling introduction](https://www.mongodb.com/docs/manual/data-modeling/) (MongoDB)
- [Redis documentation](https://redis.io/docs/latest/) (Redis)
- [System Design Primer: SQL or NoSQL](https://github.com/donnemartin/system-design-primer) (System Design Primer)

## Computer Architecture

How the hardware under your code works: number representation, the CPU and pipelining, and the memory hierarchy that explains why cache-friendly code is fast.

### Number Representation and Digital Logic

optional · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/number-systems-digital-logic

Understand binary, hex, two's complement, floating point and the logic gates and circuits that computers are built from.

This topic appears in aptitude-style CS MCQs and explains several bugs you will meet in DSA, such as overflow and floating point comparison errors. It pairs well with bit manipulation.

#### Number representation
- Convert between **binary, octal, decimal and hexadecimal** quickly. One hex digit is exactly four bits.
- **Two's complement** represents negative integers: invert the bits and add one. An n-bit signed integer ranges from -2^(n-1) to 2^(n-1) - 1, which is why `INT_MIN` has no positive counterpart and `abs(INT_MIN)` overflows.
- **Overflow**: adding two large positives can wrap to a negative in fixed-width arithmetic.
- **IEEE 754 floating point**: sign, exponent and mantissa. Many decimals (like 0.1) cannot be represented exactly, so never compare floats with `==`; compare with a small epsilon. Know what NaN and infinity are.
- **Endianness**: little-endian stores the least significant byte first (x86), big-endian the most significant first (network byte order).
- Character encodings: ASCII and UTF-8 basics.

#### Digital logic
- Gates: AND, OR, NOT, NAND, NOR, XOR. NAND and NOR are **universal**.
- Boolean algebra, De Morgan's laws, and simplifying with **Karnaugh maps**.
- **Combinational circuits**: half and full adders, multiplexers, decoders.
- **Sequential circuits**: latches and flip-flops (SR, D, JK, T) store state; registers and counters are built from them.

Good enough to move on: you can convert -13 to 8-bit two's complement, explain why 0.1 + 0.2 != 0.3 in most languages, and build a full adder from gates on paper.

Key concepts: Binary, octal and hex conversion, Two's complement and overflow, IEEE 754 floating point, Endianness, Logic gates and Boolean algebra, Karnaugh maps, Adders and multiplexers, Flip-flops and registers.

Mini project: Write a small program that prints the binary, hex, two's complement and IEEE 754 bit layout of any integer or float you enter, and use it to show overflow at INT_MAX + 1 and the exact stored value of 0.1.

Self-check: Why does abs(INT_MIN) overflow in a 32-bit signed integer, and what value does it usually return?

Resources:
- [Nand2Tetris](https://www.nand2tetris.org/) (Nand2Tetris)
- [What Every Programmer Should Know About Floating-Point](https://floating-point-gui.de/) (floating-point-gui.de)

### CPU Organisation, Instructions and Pipelining

optional · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/cpu-and-pipelining

Learn how a CPU fetches, decodes and executes instructions, what an ISA is, and how pipelining, hazards and branch prediction affect performance.

You rarely need assembly for SDE work, but understanding what the CPU actually does explains performance puzzles and shows up in core CS rounds at hardware and systems companies.

#### Organisation
- **Von Neumann architecture**: CPU, memory and I/O connected by buses, with instructions and data in the same memory.
- The CPU has an **ALU**, a **control unit** and **registers** (program counter, instruction register, general-purpose registers).
- The **instruction cycle**: fetch, decode, execute, memory access, write back.
- An **ISA** (instruction set architecture) is the contract between software and hardware. **RISC** (ARM, RISC-V: simple fixed-length instructions) vs **CISC** (x86: complex variable-length instructions).
- **Addressing modes**: immediate, register, direct, indirect, indexed.

#### Pipelining
- Like an assembly line, different instructions occupy different stages at once, improving throughput (not the latency of one instruction).
- Ideal speedup approaches the number of stages; numericals ask for time with and without pipelining.
- **Hazards** break the flow:
  - **Structural**: two stages need the same hardware.
  - **Data**: an instruction needs a result not yet written (fixed by forwarding or stalls).
  - **Control**: branches mean the next instruction is unknown (fixed by **branch prediction**).
- This is why a sorted array can make a branchy loop dramatically faster: the predictor guesses right.

#### Performance
- CPU time = instruction count x CPI x clock cycle time.
- Multicore processors, hyperthreading and why parallel speedup is limited by **Amdahl's law**.
- Interrupts and how the CPU switches into a handler.

Good enough to move on: you can explain the five pipeline stages, identify the hazard in a short instruction sequence, and apply Amdahl's law to a speedup question.

Key concepts: Von Neumann architecture, Registers, ALU and control unit, Instruction cycle, RISC vs CISC, Addressing modes, Pipelining and speedup, Structural, data and control hazards, Branch prediction, Amdahl's law.

Mini project: Write a tiny CPU simulator for a made-up 8-instruction ISA (LOAD, STORE, ADD, SUB, JMP, JZ, IN, OUT), run a program that sums numbers, and then benchmark summing values above a threshold in a sorted vs unsorted array to observe branch prediction.

Self-check: Why does pipelining improve throughput but not the latency of a single instruction?

Resources:
- [MIT 6.004 Computation Structures](https://ocw.mit.edu/courses/6-004-computation-structures-spring-2017/) (MIT OCW)
- [Nand2Tetris](https://www.nand2tetris.org/) (Nand2Tetris)
- [GeeksforGeeks: Computer Organization and Architecture](https://www.geeksforgeeks.org/computer-organization-and-architecture-tutorials/) (GeeksforGeeks)

### Memory Hierarchy and Caches

optional · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/memory-hierarchy-caches

Understand registers, caches, RAM and disk, cache mapping and replacement, locality, and how to write cache-friendly code.

Memory is a hierarchy of trade-offs: small and fast near the CPU, large and slow far away. Knowing the rough numbers changes how you write code and how you reason in system design.

#### The hierarchy
Registers (under 1 ns), L1 cache (about 1 ns), L2 and L3 (a few to tens of ns), main memory (about 100 ns), SSD (tens to hundreds of microseconds), HDD (milliseconds), network round trips (up to hundreds of ms). Each level caches the one below.

#### Locality
- **Temporal locality**: data used recently will likely be used again.
- **Spatial locality**: data near recently used data will likely be used soon. Caches fetch whole **cache lines** (often 64 bytes) to exploit this.
- Iterating a 2D array row by row in C++ is much faster than column by column because rows are contiguous.
- Arrays beat linked lists in practice partly because of spatial locality, even when Big-O is equal.

#### Cache organisation
- **Direct mapped**: each block maps to exactly one line (simple, conflict misses).
- **Fully associative**: any block anywhere (flexible, expensive).
- **Set associative**: a compromise, used in real CPUs.
- Address split into **tag, index and offset**; numericals ask for bit counts.
- Miss types: compulsory, capacity, conflict (the three Cs).
- **Write-through vs write-back** and write-allocate policies.
- **Average memory access time** = hit time + miss rate x miss penalty.
- Multicore **cache coherence** (MESI) and false sharing (optional).

#### Connecting ideas
The same concepts reappear everywhere: TLBs in OS, buffer pools in databases, CDNs and Redis in system design. LRU from page replacement is the same LRU cache you implement in DSA.

Good enough to move on: you can compute tag/index/offset bits for a set-associative cache, explain why row-major traversal is faster, and quote the rough latency ladder.

Key concepts: Latency numbers and the hierarchy, Temporal and spatial locality, Cache lines, Direct, associative and set-associative mapping, Tag, index and offset numericals, Write-through vs write-back, Average memory access time, Cache coherence and false sharing.

Mini project: Benchmark summing a 4000 x 4000 matrix row-wise vs column-wise, and a vector vs a linked list of 10 million integers, then explain the timing differences in terms of cache lines and locality.

Self-check: Why can iterating over a linked list be several times slower than an array even though both are O(n)?

Resources:
- [Latency Numbers Every Programmer Should Know](https://colin-scott.github.io/personal_website/research/interactive_latency.html) (Colin Scott)
- [MIT 6.004 Computation Structures](https://ocw.mit.edu/courses/6-004-computation-structures-spring-2017/) (MIT OCW)

## Low-Level Design

Turn vague requirements into clean classes, interfaces and interactions, practise the classic LLD case studies, and survive the machine coding round.

### How to Approach an LLD Interview

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/lld-approach

Follow a repeatable framework: clarify requirements, identify entities, define relationships and interfaces, pick patterns, and walk through key flows.

Low-level design (LLD) or object-oriented design rounds ask you to design something like a parking lot or a library system in 45-60 minutes. Interviewers grade **structure and reasoning**, not how many classes you draw.

#### A framework that works
- **Clarify requirements (5 minutes)**. Ask about scope: how many floors, what vehicle types, how payment works, whether multiple entry gates exist. Write down functional requirements and a few non-functional ones (thread safety, extensibility).
- **Identify core entities**: the nouns (ParkingLot, Floor, Spot, Vehicle, Ticket, Payment). Drop ones that are only attributes.
- **Define relationships**: has-a (composition), is-a (inheritance), uses. Sketch a **class diagram** with key fields and methods.
- **Define interfaces for what varies**: pricing, spot allocation and payment are classic Strategy candidates.
- **Walk through flows**: vehicle enters, gets a spot and ticket, exits and pays. A **sequence** of method calls shows your design actually works.
- **Handle concurrency and edge cases**: two cars grabbing the last spot at once, lost tickets, full lot.
- **Discuss extensions**: electric charging spots, monthly passes. Good designs absorb these by adding classes.

#### UML you need
Class diagrams (association, aggregation, composition, inheritance, multiplicity) and simple sequence diagrams. Neat boxes and arrows are enough.

#### Common mistakes
- Jumping into code before agreeing on requirements.
- God classes like `ParkingLotManager` that do everything.
- Enum plus switch everywhere instead of polymorphism.
- Ignoring thread safety when shared resources (spots, seats, inventory) are involved.

Good enough to move on: you can take any unfamiliar prompt and produce a requirement list, class diagram and two walked-through flows in 30 minutes.

Key concepts: Clarifying requirements, Identifying entities and responsibilities, Class diagrams and relationships, Sequence diagrams for key flows, Designing for extension, Concurrency in shared resources, Common LLD mistakes.

Mini project: Pick a prompt you have not seen (for example, a coffee vending machine) and do a timed 45-minute mock alone: write requirements, a class diagram, two sequence flows and three extension scenarios, then compare with a published solution and note what you missed.

Self-check: In a parking lot design, which parts would you model with the Strategy pattern, and how would that help when a new pricing rule is added?

Resources:
- [awesome-low-level-design (case studies)](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [Refactoring Guru: Design patterns](https://refactoring.guru/design-patterns) (Refactoring Guru)
- [Grokking the Object Oriented Design Interview notes](https://github.com/tssovi/grokking-the-object-oriented-design-interview) (GitHub)

### Classic LLD Case Studies

core · intermediate · about 12 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/lld-classic-case-studies

Practise the most frequently asked designs: parking lot, library management, vending machine, tic-tac-toe or snake and ladder, and an elevator system.

A small set of prompts covers most LLD interviews. Designing each one yourself, then comparing with reference solutions, teaches you reusable building blocks.

#### The core set and what each teaches
- **Parking lot**: entity modelling, Strategy for spot allocation and pricing, concurrency on spot assignment, and the Factory pattern for vehicles.
- **Library management**: users, books vs book copies (a key distinction), reservations, fines, and search. Teaches separating a catalogue item from a physical item.
- **Vending machine or ATM**: the **State** pattern (Idle, HasMoney, Dispensing) and Chain of Responsibility for dispensing notes.
- **Tic-tac-toe, Snake and Ladder, Chess**: game loops, board and player abstractions, win checking, and keeping rules separate from the board so you can change them. Chess adds per-piece movement via polymorphism.
- **Elevator system**: request scheduling (a SCAN-like algorithm, which you saw in disk scheduling), states per elevator, and a controller that assigns requests. Great for showing Strategy and State together.
- **Logger or notification service**: Chain of Responsibility for levels, Observer for subscribers, Singleton for the logger instance.

#### How to practise each one
- Timebox 45 minutes: requirements, class diagram, then code the core classes and one flow.
- Compare with a reference solution and note differences in responsibilities, not naming.
- Revisit a week later and add one extension (EV charging, multiple elevators, undo in games).

#### What interviewers look for
Clear single-responsibility classes, interfaces at the points of change, correct relationships, and working code for at least the main flow.

Good enough to move on: you can design and partially code any three of these from a blank page within the time limit, and explain the pattern choices.

Key concepts: Parking lot, Library management system, Vending machine and ATM, Tic-tac-toe and Snake and Ladder, Elevator system, Logger and notification service, Chess.

Mini project: Implement a working parking lot and an elevator system in your DSA language with a simple CLI: multiple floors and spot types, pluggable pricing, and an elevator controller that serves requests using a SCAN-style strategy, with unit tests for the core flows.

Self-check: In a library system, why should Book and BookItem be separate classes, and which one does a reservation reference?

Resources:
- [awesome-low-level-design (case studies)](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [Grokking the Object Oriented Design Interview notes](https://github.com/tssovi/grokking-the-object-oriented-design-interview) (GitHub)

### Advanced LLD Case Studies

recommended · advanced · about 14 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/lld-advanced-case-studies

Tackle designs asked by product companies: Splitwise, BookMyShow, a rate limiter, an LRU cache, a food delivery system and an in-memory key-value store.

Product companies in India (Flipkart, Swiggy, PhonePe, Razorpay and others) prefer prompts closer to their own domains. These add business rules, concurrency and data-structure choices on top of basic modelling.

#### The advanced set
- **Splitwise**: users, groups, expenses with equal, exact and percentage splits (Strategy), balance sheets, and **simplifying debts** (a greedy heap-based algorithm).
- **BookMyShow / movie ticket booking**: theatres, screens, shows, seats, and the core challenge of **concurrent seat booking**. Discuss temporary seat locks with expiry, and optimistic vs pessimistic locking.
- **Rate limiter**: token bucket, leaky bucket, fixed and sliding window algorithms behind a common interface. Thread-safe counters per user.
- **LRU cache**: hash map plus doubly linked list for O(1) get and put. Extend to LFU and to a thread-safe version.
- **Food delivery or ride hailing**: order lifecycle with the State pattern, delivery partner assignment via Strategy, and notifications via Observer.
- **In-memory key-value store**: get, set, delete, TTL expiry and optional transactions (begin, commit, rollback with a stack of change sets).
- Others worth a look: a cab booking app, a stock exchange order matching engine, a pub-sub queue, a snake game with a leaderboard.

#### Skills these add
- Picking the right **data structures** inside a design (heaps, ordered maps, linked lists).
- **Concurrency**: locks per resource rather than one global lock, and atomic operations.
- Making business rules pluggable so new split types or pricing need no core changes.

Good enough to move on: you can implement LRU cache and a thread-safe rate limiter from scratch and explain how BookMyShow avoids double-booking.

Key concepts: Splitwise and debt simplification, Movie ticket booking and seat locking, Rate limiter algorithms, LRU and LFU cache, Food delivery or ride hailing, In-memory key-value store with TTL, Order matching engine, Pub-sub message queue.

Mini project: Build a Splitwise clone as a CLI with equal, exact and percentage splits and a simplify-debts command, plus a thread-safe token bucket rate limiter with a test that fires 1000 concurrent requests and asserts the allowed count.

Self-check: Two users click the same seat for the same show within milliseconds. Walk through how your booking design guarantees only one succeeds.

Resources:
- [awesome-low-level-design (case studies)](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [LeetCode: LRU Cache](https://leetcode.com/problems/lru-cache/) (LeetCode)
- [Stripe: Scaling your API with rate limiters](https://stripe.com/blog/rate-limiters) (Stripe)

### The Machine Coding Round

recommended · advanced · about 12 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/machine-coding-round

Prepare for 90-120 minute rounds where you build a working, extensible, tested application from a problem statement under time pressure.

Machine coding rounds (common at Flipkart, Swiggy, Uber, PhonePe, Razorpay, Atlassian and many startups) give you a problem statement and 90-120 minutes to produce **working code**, followed by a review of your design and a live extension.

#### What they grade
- **It runs**: the required commands or APIs work on the sample input. A half-finished "perfect" design scores worse than a simple working one.
- **Modularity**: separate models, services and a thin driver or CLI. No logic in `main`.
- **Extensibility**: new requirements (announced during review) can be added in minutes.
- **Readability**: meaningful names, small methods, no copy-paste.
- **Edge cases and errors**: invalid input handled gracefully with clear messages.
- **Tests** are a strong bonus, even a few.

#### A time plan for 90 minutes
- 10 minutes: read, clarify, list entities and commands.
- 10 minutes: sketch classes and interfaces on paper.
- 50 minutes: implement the core flow first, then secondary features.
- 10 minutes: edge cases, error handling, a couple of tests.
- 10 minutes: clean up and prepare to explain.

#### Practical tips
- Use **in-memory storage** (maps and lists) behind a repository interface unless told otherwise.
- Keep a personal skeleton ready in your language: package layout, a command parser, a custom exception class.
- Avoid frameworks unless required; they cost setup time.
- Commit or save progress in stages so you always have something runnable.
- Practise with real prompts: a snake and ladder game, a parking lot with commands, a Splitwise CLI, a meeting room scheduler, an inventory management system.

Good enough to move on: you have completed at least five timed machine coding problems end to end, each running correctly and able to take one new requirement in under ten minutes.

Key concepts: Reading the prompt and scoping, Project layout: models, services, driver, In-memory repositories, Time management, Error handling and validation, Writing quick unit tests, Handling live extensions.

Mini project: Do five timed 90-minute machine coding sessions (meeting room scheduler, Splitwise CLI, snake and ladder, inventory manager, parking lot with commands). After each, have a friend add one surprise requirement and record how long the change took.

Self-check: At minute 60 of 90 your design is elegant but only half the commands work. What do you do in the remaining 30 minutes and why?

Resources:
- [awesome-low-level-design (machine coding problems)](https://github.com/ashishps1/awesome-low-level-design) (GitHub)
- [Refactoring Guru: Refactoring](https://refactoring.guru/refactoring) (Refactoring Guru)

## System Design Foundations

The building blocks of large systems: scalability and performance vocabulary, load balancers, caching and CDNs, and scaling databases with replication and sharding.

### Scalability, Latency and Back-of-the-Envelope Estimates

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/scalability-basics

Learn the vocabulary of system design: vertical vs horizontal scaling, latency vs throughput, availability, and quick capacity estimates.

High-level design (HLD) interviews are common for SDE-2 roles and increasingly appear for strong freshers and interns at product companies. Even when not asked directly, this vocabulary helps you discuss your projects convincingly.

#### Core vocabulary
- **Vertical scaling**: a bigger machine. Simple, but has a ceiling and a single point of failure.
- **Horizontal scaling**: more machines behind a load balancer. Needs **stateless** application servers (sessions in Redis or tokens, not in server memory).
- **Latency** (time per request) vs **throughput** (requests per second). Report latency as percentiles: p50, p95, **p99**. Averages hide slow tails.
- **Availability**: "three nines" (99.9%) allows about 8.8 hours of downtime a year; four nines about 53 minutes. Redundancy and removing **single points of failure** raise it.
- **Reliability**, **fault tolerance** and **graceful degradation** (serve cached data when a dependency is down).

#### Back-of-the-envelope estimation
- Useful constants: a day has about 86,400 seconds (round to 10^5), so 1 million requests per day is roughly 12 requests per second on average; plan for peaks of 2-10x.
- Storage: users x items per user x bytes per item x retention. 100 million tweets per day at 300 bytes is about 30 GB per day.
- Bandwidth: requests per second x response size.
- Know the rough latency ladder (memory vs SSD vs network) from computer architecture.

#### Why this matters
Estimates decide the design. 12 requests per second fits a single server and database; 100,000 per second needs caching, sharding and queues. Always estimate before choosing components.

Good enough to move on: you can estimate QPS, storage and bandwidth for a service like Instagram in five minutes and explain why stateless servers make horizontal scaling easy.

Key concepts: Vertical vs horizontal scaling, Stateless services, Latency, throughput and percentiles, Availability and nines, Single points of failure and redundancy, QPS, storage and bandwidth estimates, Latency numbers.

Mini project: Write one-page capacity estimates for three services (a URL shortener, WhatsApp, and YouTube uploads): daily active users, read and write QPS with peaks, storage over five years and bandwidth, and state which numbers would force caching or sharding.

Self-check: A service gets 50 million requests per day with a 5x peak factor. Roughly what peak QPS must it handle, and could a single server cope?

Resources:
- [The System Design Primer](https://github.com/donnemartin/system-design-primer) (GitHub)
- [ByteByteGo system design resources](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)
- [Latency Numbers Every Programmer Should Know](https://colin-scott.github.io/personal_website/research/interactive_latency.html) (Colin Scott)

### Load Balancers, Proxies and API Gateways

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/load-balancing-and-proxies

Distribute traffic across servers with load balancing algorithms, understand L4 vs L7, health checks, reverse proxies and API gateways.

A **load balancer** (LB) spreads requests across servers so no single one is overwhelmed and failed servers are bypassed. It is the first box you draw in almost every design.

#### Algorithms
- **Round robin** and weighted round robin: simple and fair when requests are similar.
- **Least connections** or least response time: better when requests vary in cost.
- **IP hash / consistent hashing**: the same client or key goes to the same server, useful for caches and sticky sessions.
- Random with two choices (optional): surprisingly effective.

#### Layers
- **L4 (transport)** balancers route by IP and port without reading the request. Very fast.
- **L7 (application)** balancers read HTTP (path, headers, cookies) and can route `/api` and `/images` to different pools, terminate TLS and rewrite requests. Nginx, HAProxy and cloud ALBs do this.

#### Reliability features
- **Health checks** remove unhealthy servers automatically.
- The LB itself must not be a single point of failure: run it in active-passive or active-active pairs, or use a managed cloud LB.
- **Sticky sessions** are a crutch; prefer stateless servers.

#### Proxies and gateways
- A **forward proxy** acts for clients (corporate proxies, VPN-like use).
- A **reverse proxy** sits in front of servers: TLS termination, compression, caching and hiding internal topology.
- An **API gateway** is a reverse proxy with API concerns: authentication, rate limiting, request routing to microservices, and logging.
- **DNS load balancing** and global server load balancing route users to the nearest region.

Good enough to move on: you can pick an LB algorithm for a given workload, explain L4 vs L7, and describe what happens when a backend server dies mid-traffic.

Key concepts: Round robin and least connections, Hash-based routing, L4 vs L7 load balancing, Health checks and failover, Forward vs reverse proxy, API gateways, Global and DNS load balancing.

Mini project: Run three copies of a small web server with Docker, put Nginx in front as a reverse proxy with round robin and then least connections, add a health check, kill one server during a load test with a tool like hey or k6, and record what clients observe.

Self-check: Why would you choose an L7 load balancer over an L4 one for a web application with separate API and static file servers?

Resources:
- [The System Design Primer: Load balancer](https://github.com/donnemartin/system-design-primer) (GitHub)
- [NGINX: HTTP load balancing](https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/) (NGINX)
- [Cloudflare Learning Center: What is load balancing?](https://www.cloudflare.com/learning/performance/what-is-load-balancing/) (Cloudflare)

### Caching and CDNs

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/caching-and-cdn

Use caches at every layer, choose cache-aside, write-through or write-back, handle eviction and invalidation, and serve static content via CDNs.

Caching stores the results of expensive work closer to where they are needed. It is the most powerful and most error-prone tool in system design.

#### Where caches live
Browser cache, **CDN** edge servers, reverse proxy cache, application in-memory cache, distributed caches like **Redis** or Memcached, and the database's own buffer pool.

#### Caching strategies
- **Cache-aside (lazy loading)**: the app checks the cache, on a miss reads the DB and fills the cache. The most common pattern.
- **Read-through**: the cache itself loads from the DB on a miss.
- **Write-through**: write to cache and DB together. Consistent, but slower writes.
- **Write-back (write-behind)**: write to cache, flush to DB later. Fast, but risk of data loss.
- **Write-around**: write to DB only; the cache fills on reads.

#### Eviction and expiry
- **LRU** (least recently used, the same data structure you built in DSA), **LFU**, FIFO.
- **TTL** bounds staleness; choose it from how stale the data may safely be.

#### The hard parts
- **Invalidation**: when data changes, delete or update the cached copy. Deleting on write is usually safer than updating.
- **Thundering herd / cache stampede**: a popular key expires and thousands of requests hit the DB at once. Fix with request coalescing, locks or jittered TTLs.
- **Cache penetration**: repeated requests for keys that do not exist; cache the "not found" or use a Bloom filter.
- **Hot keys**: one key gets most of the traffic; replicate it or add a local cache.

#### CDNs
CDNs cache static assets (images, JS, video) at edge locations near users, cutting latency and origin load. Push vs pull CDNs, and cache-busting with versioned file names.

Good enough to move on: you can add a cache to a design, justify the strategy and TTL, and explain how you would prevent a stampede on a trending key.

Key concepts: Cache layers from browser to DB, Cache-aside and read-through, Write-through, write-back, write-around, Eviction policies and TTL, Cache invalidation, Stampede, penetration and hot keys, CDNs and edge caching, Redis basics.

Mini project: Add Redis cache-aside caching to a slow API endpoint in one of your projects, measure p50 and p95 latency before and after with a load test, then implement invalidation on update and a simple lock to prevent stampedes when a hot key expires.

Self-check: When a user updates their profile, why is deleting the cached entry usually safer than writing the new value into the cache?

Resources:
- [The System Design Primer: Cache](https://github.com/donnemartin/system-design-primer) (GitHub)
- [Redis documentation](https://redis.io/docs/latest/) (Redis)
- [Cloudflare Learning Center: What is a CDN?](https://www.cloudflare.com/learning/cdn/what-is-a-cdn/) (Cloudflare)

### Scaling Databases: Replication, Partitioning and Sharding

core · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/database-scaling

Scale reads with replicas, scale writes with sharding, choose shard keys, use consistent hashing, and understand the costs of distributed data.

The database is usually the first real bottleneck. Scaling it well is a core system design skill and builds directly on the DBMS section.

#### Replication
- **Leader-follower (master-slave)**: writes go to the leader, reads can go to followers. Scales reads and adds failover.
- **Synchronous vs asynchronous** replication: sync is safer but slower; async risks losing recent writes and causes **replication lag**, so a user may not see their own update ("read your own writes" problem).
- **Multi-leader** and **leaderless** (quorum-based, like Cassandra and DynamoDB) replication for multi-region writes, at the cost of conflict resolution.
- **Failover**: promoting a follower when the leader dies, and the danger of split brain.

#### Partitioning and sharding
- **Vertical partitioning**: split tables or columns by feature (users DB, orders DB).
- **Horizontal sharding**: split rows of one table across machines.
- **Shard key choice** is everything: range-based (easy range queries, risk of hot spots) vs hash-based (even spread, no efficient ranges) vs directory-based (a lookup service).
- **Consistent hashing** places nodes and keys on a ring so adding or removing a node moves only a small fraction of keys. Virtual nodes smooth the distribution.

#### Costs of sharding
- Cross-shard joins and transactions become hard or impossible.
- Rebalancing when shards grow unevenly.
- **Hot partitions** from celebrity users or trending items.
- Global unique IDs: use UUIDs, Snowflake-style IDs, or ticket servers instead of auto-increment.

#### Order of operations in practice
Optimise queries and add indexes, then cache, then read replicas, and only then shard. Sharding is a big operational commitment.

Good enough to move on: you can choose a shard key for a given access pattern, explain consistent hashing on a whiteboard, and describe the replication lag problem and one fix.

Key concepts: Leader-follower replication, Sync vs async replication and lag, Multi-leader and leaderless replication, Vertical partitioning, Horizontal sharding and shard keys, Consistent hashing, Hot partitions and rebalancing, Distributed ID generation.

Mini project: Implement consistent hashing with virtual nodes in your DSA language, simulate distributing 1 million keys over 5 nodes, then add and remove a node and measure how many keys move compared with simple modulo hashing.

Self-check: Why does hash(key) mod N perform badly when you add a new database server, and how does consistent hashing fix it?

Resources:
- [The System Design Primer: Database scaling](https://github.com/donnemartin/system-design-primer) (GitHub)
- [Tom White: Consistent Hashing](https://tom-e-white.com/2007/11/consistent-hashing.html) (Tom White)
- [Designing Data-Intensive Applications (book site)](https://dataintensive.net/) (Martin Kleppmann)

## Distributed Systems and HLD Interviews

Asynchronous messaging, CAP and consistency models, service architecture and API design, a repeatable HLD interview framework, and the classic case studies.

### Message Queues and Asynchronous Processing

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/message-queues-async

Decouple services with queues and event streams, learn delivery guarantees, idempotency, retries and dead-letter queues, and when to use Kafka vs a task queue.

Not every piece of work should happen inside the user's request. **Message queues** let one service hand work to another asynchronously, smoothing traffic spikes and isolating failures.

#### When to go async
- Slow or non-urgent work: sending emails, generating thumbnails, processing payments webhooks, updating search indexes.
- **Traffic spikes**: the queue absorbs bursts while consumers work at a steady rate (load levelling).
- **Fan-out**: one event (order placed) triggers many independent actions (email, analytics, inventory).

#### Models
- **Point-to-point task queues** (RabbitMQ, SQS, Celery, BullMQ): each message is processed by one worker.
- **Publish-subscribe / event streams** (Kafka, Pub/Sub, SNS): many consumer groups each read every event. Kafka keeps an ordered, replayable **log** split into **partitions**; ordering is guaranteed only within a partition.

#### Delivery guarantees
- **At most once**: may lose messages.
- **At least once**: may deliver duplicates (the common default).
- **Exactly once**: very hard end to end; in practice you combine at-least-once delivery with **idempotent consumers** (processing the same message twice has the same effect, for example by storing processed message IDs).

#### Operating queues
- **Retries with exponential backoff** and jitter.
- **Dead-letter queues** for messages that keep failing, so they do not block others.
- **Backpressure** and monitoring consumer lag.
- The **outbox pattern** to reliably publish an event when a DB transaction commits.

#### Pitfalls
Assuming global ordering, making consumers non-idempotent, and adding queues where a simple synchronous call would do.

Good enough to move on: you can place a queue in a design, justify it, and explain how you make a payment consumer safe against duplicate messages.

Key concepts: Sync vs async communication, Task queues vs pub-sub, Kafka topics, partitions and consumer groups, Delivery guarantees, Idempotent consumers, Retries, backoff and dead-letter queues, Outbox pattern.

Mini project: Build an image upload service where the API stores the file and enqueues a job, and a separate worker (using Redis-backed BullMQ, Celery or RabbitMQ) generates thumbnails with retries, a dead-letter queue and idempotency by job ID. Kill the worker mid-job and verify nothing is lost or duplicated.

Self-check: Why is at-least-once delivery combined with idempotent consumers the usual practical answer to exactly-once processing?

Resources:
- [The System Design Primer: Asynchronism](https://github.com/donnemartin/system-design-primer) (GitHub)
- [Apache Kafka introduction](https://kafka.apache.org/intro) (Apache Kafka)
- [RabbitMQ tutorials](https://www.rabbitmq.com/tutorials) (RabbitMQ)

### CAP Theorem and Consistency Models

core · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/cap-and-consistency

Understand CAP and PACELC, strong vs eventual consistency, quorums, and the basics of consensus and distributed transactions.

Once data lives on several machines, networks fail and clocks disagree. This topic gives you the language to discuss those trade-offs precisely rather than hand-waving.

#### CAP, stated correctly
- **Consistency**: every read sees the latest write (linearizability).
- **Availability**: every request to a non-failed node gets a response.
- **Partition tolerance**: the system keeps working despite lost messages between nodes.
- Partitions **will** happen, so the real choice during a partition is **CP** (refuse some requests to stay consistent) or **AP** (answer with possibly stale data). A bank balance leans CP; a like counter leans AP.
- **PACELC** adds: even without a partition, you trade **latency vs consistency**.

#### Consistency models
- **Strong / linearizable**: behaves like one copy.
- **Eventual consistency**: replicas converge if writes stop. Needs conflict handling (last-write-wins, version vectors, CRDTs).
- Practical middle grounds: **read-your-own-writes**, **monotonic reads**, causal consistency.
- **Quorums**: with N replicas, W write acks and R read replies, **R + W > N** guarantees reads overlap the latest write.

#### Consensus and coordination
- Consensus algorithms like **Raft** and Paxos let nodes agree on a leader or a log despite failures; ZooKeeper and etcd provide this as a service (leader election, locks, config).
- **Distributed transactions**: two-phase commit (2PC) is blocking and fragile; microservices often use the **Saga** pattern with compensating actions instead.
- Clocks: do not rely on wall-clock ordering across machines; logical clocks exist for this.

Good enough to move on: for any feature you can state whether it should be CP or AP and why, explain R + W > N, and describe how a Saga undoes a failed multi-service order.

Key concepts: CAP theorem, PACELC, Strong vs eventual consistency, Read-your-writes and causal consistency, Quorums (R + W > N), Leader election and Raft, Two-phase commit vs Saga, Conflict resolution and CRDTs.

Mini project: Write a short design note for three features (wallet balance, shopping cart, social feed likes) choosing CP or AP for each with justification, then play the Raft visualisation and explain in your own words how a new leader is elected after a crash.

Self-check: With 5 replicas, what R and W values give strong consistency while tolerating one slow node on both reads and writes?

Resources:
- [The System Design Primer: CAP and consistency patterns](https://github.com/donnemartin/system-design-primer) (GitHub)
- [The Raft Consensus Algorithm](https://raft.github.io/) (raft.github.io)
- [MIT 6.824 Distributed Systems](https://pdos.csail.mit.edu/6.824/) (MIT)

### Service Architecture and API Design

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/service-architecture-api-design

Compare monoliths and microservices, design clean REST APIs with pagination and versioning, and add rate limiting, observability and resilience patterns.

Every HLD answer includes some APIs and some service boundaries. This topic covers how to define them sensibly.

#### Monolith vs microservices
- A **monolith** is one deployable app. Simple to build, test and deploy; the right default for small teams and most college projects.
- **Microservices** split by business capability (users, orders, payments), each owning its data. They allow independent scaling and deployment but add network calls, distributed failures and operational overhead.
- A **modular monolith** is a common middle path. Do not say "microservices" in an interview without naming the benefit you need.

#### API design
- REST resources as nouns (`/users/42/orders`), correct methods and status codes.
- **Pagination**: offset/limit is simple but slow for deep pages; **cursor-based** pagination is stable and scales.
- **Idempotency keys** for POSTs like payments, so retries do not double-charge.
- Versioning (`/v1/`), consistent error formats, filtering and sorting.
- Alternatives: **gRPC** for fast internal calls, **GraphQL** for flexible client queries, **WebSockets** or server-sent events for real-time updates, and long polling.

#### Protecting services
- **Rate limiting** with token bucket or sliding window, usually at the API gateway, returning 429.
- **Timeouts**, **retries with backoff**, **circuit breakers** (stop calling a failing dependency) and bulkheads.
- Service discovery and health checks.

#### Observability
Logs, metrics (latency percentiles, error rates) and distributed traces. Mention monitoring and alerting in every design.

Good enough to move on: you can write the core API endpoints for a given system with request and response shapes, choose cursor pagination where appropriate, and explain what a circuit breaker prevents.

Key concepts: Monolith vs microservices, REST resource design, Offset vs cursor pagination, Idempotency keys, gRPC, GraphQL and WebSockets, Rate limiting at the gateway, Timeouts, retries and circuit breakers, Logs, metrics and tracing.

Mini project: Design and implement the API for a small e-commerce backend: products with cursor pagination and filters, an orders endpoint that accepts an Idempotency-Key header, a per-user token bucket rate limiter returning 429, and a circuit breaker around a mock payment service.

Self-check: Why does offset pagination become slow and inconsistent on a large, frequently updated feed, and how does cursor pagination fix both problems?

Resources:
- [Microsoft: Web API design best practices](https://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design) (Microsoft Learn)
- [Martin Fowler: Microservices](https://martinfowler.com/articles/microservices.html) (martinfowler.com)
- [Martin Fowler: Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html) (martinfowler.com)

### The HLD Interview Framework

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/hld-interview-framework

Structure a 45-minute system design interview: requirements, estimates, API, data model, high-level diagram, deep dives and trade-offs.

System design interviews are open-ended on purpose. A consistent structure keeps you from rambling and shows the interviewer you can drive an ambiguous discussion.

#### A 45-minute structure
- **Requirements (5-7 min)**: functional (users can post, follow, view feed) and non-functional (scale, latency, availability, consistency). Agree on what is out of scope.
- **Estimates (3-5 min)**: DAU, read and write QPS, storage, bandwidth. Note the read:write ratio; it drives caching decisions.
- **API (3-5 min)**: the handful of endpoints that cover the requirements.
- **Data model (5 min)**: main entities, SQL or NoSQL with a reason, and likely shard keys.
- **High-level design (10 min)**: clients, LB, services, databases, caches, queues, CDN, drawn as boxes with data flow for the main use cases.
- **Deep dives (10-15 min)**: the one or two hardest parts, often chosen by the interviewer: feed generation, hot keys, consistency, failure handling.
- **Wrap-up**: bottlenecks, monitoring, and what you would do next with more time.

#### Habits that score well
- Think aloud and check in: "I will assume 100 million DAU, does that sound right?"
- State **trade-offs** explicitly for every major choice, including what you give up.
- Start simple, then scale the parts the numbers say need scaling.
- Use real components by category (a relational DB, a cache like Redis, a queue like Kafka) without obsessing over brands.

#### Red flags
Drawing twenty boxes before requirements, ignoring the numbers, never mentioning failures, and treating every design as needing microservices and Kafka.

Good enough to move on: you can run a full mock of a design you have not seen, finish the high-level diagram by minute 25, and lead a deep dive with trade-offs.

Key concepts: Functional and non-functional requirements, Estimation step, API and data model, High-level diagram, Deep dives and bottlenecks, Communicating trade-offs, Common red flags.

Mini project: Record yourself (screen plus voice) doing three 45-minute designs using this framework on a whiteboard tool like Excalidraw, then review the recordings against the timings and list where you lost time or skipped trade-offs.

Self-check: Why should the read-to-write ratio you estimate early change which components you add later in the design?

Resources:
- [The System Design Primer: How to approach a system design interview](https://github.com/donnemartin/system-design-primer) (GitHub)
- [Tech Interview Handbook: System design](https://www.techinterviewhandbook.org/system-design/) (Tech Interview Handbook)
- [Excalidraw whiteboard](https://excalidraw.com/) (Excalidraw)

### Classic HLD Case Studies

core · advanced · about 16 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/hld-case-studies

Practise the most asked designs: URL shortener, rate limiter, chat app, news feed, notification system, file storage, video streaming and ride hailing.

Each classic case study exercises a different set of building blocks. Work through them in roughly this order, since later ones reuse ideas from earlier ones.

#### The list and the key idea in each
- **URL shortener** (TinyURL): ID generation (base62 encoding, counters vs hashing), a read-heavy workload served from cache, and redirects with 301 vs 302.
- **Distributed rate limiter**: token bucket in Redis with atomic operations, per-user vs global limits, and behaviour when Redis is down.
- **Chat application** (WhatsApp): persistent **WebSocket** connections, message ordering per conversation, delivery and read receipts, offline storage, and a presence service.
- **News feed** (Instagram, Twitter): **fan-out on write vs fan-out on read**, the celebrity problem, and a hybrid approach with feed caches.
- **Notification system**: queues per channel (push, SMS, email), retries, user preferences, templates and rate limiting.
- **File storage** (Google Drive, Dropbox): chunking, deduplication with hashes, metadata DB vs blob storage, and sync conflicts.
- **Video streaming** (YouTube, Netflix): upload pipeline with transcoding workers, adaptive bitrate streaming, and heavy use of CDNs.
- **Ride hailing** (Uber, Ola): location updates at high write rates, geospatial indexing (geohash or quadtrees) for nearby drivers, and matching.
- Also useful: typeahead search (tries plus caching), a web crawler, a distributed key-value store, and a ticket booking system at scale.

#### How to study them
- Attempt the design yourself first with the framework, then read a reference and list every idea you missed.
- Keep a one-page cheat sheet per design: requirements, estimates, diagram, two deep dives.
- Re-do three of them a week later from memory.

Good enough to move on: you can present any five of these end to end in 45 minutes each and explain the central trade-off of each design in two sentences.

Key concepts: URL shortener, Distributed rate limiter, Chat application, News feed and fan-out, Notification system, File storage and sync, Video streaming, Ride hailing and geospatial indexing, Typeahead search, Web crawler.

Mini project: Build a working mini URL shortener with base62 IDs, a PostgreSQL store, Redis caching and click analytics pushed through a queue, deploy it on a free tier, load test it, and write a design doc that shows how it would scale to 100 million URLs.

Self-check: In a news feed, why does pure fan-out on write break for celebrity accounts, and what hybrid approach fixes it?

Resources:
- [The System Design Primer: System design interview questions with solutions](https://github.com/donnemartin/system-design-primer) (GitHub)
- [ByteByteGo System Design 101](https://github.com/ByteByteGoHq/system-design-101) (ByteByteGo)
- [High Scalability blog](https://highscalability.com/) (High Scalability)

## Interview and Placement Preparation

Turn your skills into offers: a sharp resume, projects worth discussing, online assessments and aptitude, the coding interview itself, behavioral rounds, mocks and company-specific preparation.

### Building a Strong Tech Resume

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/resume-building

Write a one-page, ATS-friendly resume with quantified impact bullets, the right section order for students, and links that recruiters actually click.

Your resume gets roughly 10-30 seconds of attention, often after an automated filter (ATS). Its only job is to get you to the interview, so optimise for fast scanning.

#### Structure for students
- **One page**, single column, a clean template (LaTeX templates like Jake's resume are popular for a reason).
- Order: header (name, email, phone, GitHub, LinkedIn, portfolio or LeetCode/Codeforces profile), **Education** (college, degree, CGPA if decent, graduation year), **Experience** (internships), **Projects**, **Skills**, **Achievements**.
- Skills grouped: Languages, Frameworks, Tools, Databases. List only what you can be questioned on.

#### Writing bullets that work
- Use the pattern **action verb + what you built + how + measurable result**: "Built a Redis-backed caching layer for the course search API, cutting p95 latency from 800 ms to 120 ms."
- Quantify wherever honest: users, requests, percentages, time saved, dataset size, rank.
- Two to four bullets per project or internship; lead with the most impressive.
- Achievements that matter: contest ratings and ranks (Codeforces, CodeChef, LeetCode), hackathon wins, GSoC or open source contributions, scholarships.

#### ATS and formatting
- Standard section headings, real text (not images), common fonts, PDF export.
- Mirror keywords from the job description where they are true for you.
- No photos, no rating bars for skills, no "objective" paragraph.

#### Common mistakes
Listing coursework instead of projects, tutorial clones as headline projects, vague bullets ("worked on backend"), typos, and claiming skills you cannot defend in an interview.

Good enough to move on: three people (a senior, a peer and a mentor) can each tell you your top two strengths within 30 seconds of reading it, and every line is something you can discuss for five minutes.

Key concepts: One-page structure and section order, Impact-driven bullet points, Quantifying results, ATS-friendly formatting, Tailoring to a job description, Profile links: GitHub, LinkedIn, coding profiles, LaTeX resume templates.

Mini project: Rewrite your resume from scratch using the bullet formula, create two tailored versions (one for an SDE internship, one for a data or ML role), and get written feedback from at least two people who have cleared interviews at product companies.

Self-check: Rewrite the bullet 'Worked on the backend of a college app' so it shows what you built, how, and the measurable result.

Resources:
- [Tech Interview Handbook: Resume guide](https://www.techinterviewhandbook.org/resume/) (Tech Interview Handbook)
- [Jake's Resume LaTeX template](https://github.com/jakegut/resume) (GitHub)
- [Harvard: Resume action verbs and guides](https://careerservices.fas.harvard.edu/resources/) (Harvard Career Services)

### Projects, GitHub and Open Source

core · intermediate · about 30 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/projects-and-portfolio

Pick and build two or three projects that demonstrate real engineering, present them well on GitHub, and optionally contribute to open source or GSoC.

Projects are the main thing interviewers ask about beyond DSA, and they are often the tie-breaker between candidates with similar coding skills. Depth beats count: two strong projects you can defend are better than eight tutorials.

#### What makes a project strong
- It **solves a real problem** for real users (your college, a club, a local business), even if only a few.
- It shows engineering beyond CRUD: authentication, caching, background jobs, search, real-time features, payments, a deployed ML model, or measurable performance work.
- It is **deployed** with a live link, and ideally has some usage data.
- It uses fundamentals you learned here: a good schema, indexes, a queue, a clear API, tests.

#### Presenting it on GitHub
- A **README** with the problem, a screenshot or GIF, the live link, the architecture diagram, the tech stack, how to run it, and the trade-offs you made.
- Meaningful commit history (not a single "final" commit), clean folder structure, no committed secrets.
- Pin your best repositories on your profile.

#### Being ready to discuss it
Interviewers will ask: why this stack, the hardest bug, what breaks at 10x users, what you would change, and what exactly *you* did in a team project. Prepare two-minute and ten-minute explanations.

#### Open source and programs
- Start with documentation fixes and "good first issue" labels, then real bug fixes. Read the contribution guide first.
- Programs: **Google Summer of Code**, LFX Mentorship, Outreachy, MLH Fellowship, and Hacktoberfest.
- Hackathons (Smart India Hackathon, MLH events) add teamwork stories and sometimes direct interview calls.

Good enough to move on: you have at least two deployed projects with strong READMEs, and you can confidently answer "what would break first if traffic grew 100x?" for each.

Key concepts: Choosing problems worth building, Going beyond CRUD, Deployment and live demos, READMEs and architecture diagrams, Explaining projects in interviews, Open source first contributions, GSoC, LFX and Outreachy, Hackathons.

Mini project: Upgrade your best existing project: add one serious engineering feature (caching, background jobs or search), deploy it, write a README with an architecture diagram and trade-offs, and make one merged contribution to an open source project you actually use.

Self-check: For your main project, what is the first component that would fail at 100x traffic, and how would you fix it?

Resources:
- [GitHub Docs: About READMEs](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-readmes) (GitHub)
- [First Contributions](https://github.com/firstcontributions/first-contributions) (GitHub)
- [Google Summer of Code](https://summerofcode.withgoogle.com/) (Google)

### Online Assessments and Aptitude

recommended · beginner · about 15 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/online-assessments-aptitude

Clear the first filter: timed coding OAs on HackerRank-style platforms, CS fundamentals MCQs, and the quantitative, logical and verbal aptitude used by service companies.

Most campus and off-campus processes start with an **online assessment (OA)**. It is a filter, so the goal is reliability under time pressure rather than brilliance.

#### Coding OAs
- Typically 2-4 problems in 60-120 minutes on HackerRank, HackerEarth, CodeSignal, Mettl or a company portal.
- Read all problems first; solve the easiest fully before attempting the hard one.
- **Partial credit** is common: a brute force passing half the tests beats an unfinished optimal solution.
- Watch input format, integer overflow and edge cases. Practise on the platform's editor so its I/O style is familiar.
- Proctoring rules are strict; follow them exactly.

#### CS fundamentals MCQs
OS, DBMS, networks, OOP, output-prediction questions in C/C++/Java, and SQL. The earlier sections of this track cover them; revise with quick question banks in the last week.

#### Aptitude (OPTIONAL for product companies, key for service companies)
Service and mass recruiters (TCS NQT, Infosys, Wipro, Accenture, Cognizant, Capgemini) weigh aptitude heavily.
- **Quantitative**: percentages, profit and loss, ratios, time and work, time speed distance, simple and compound interest, permutations and probability, number systems.
- **Logical reasoning**: series, coding-decoding, blood relations, seating arrangements, syllogisms, puzzles, data sufficiency.
- **Verbal**: reading comprehension, sentence correction, para jumbles, vocabulary.
- Learn shortcuts for the most frequent types and do timed sectional tests; speed matters more than depth.

#### A two-week OA sprint
Daily: two timed coding problems, 20 aptitude questions, and 15 CS MCQs. On weekends, take a full mock under exam conditions.

Good enough to move on: you consistently solve two of three OA-style problems in 90 minutes and score above the typical cut-off on full aptitude mocks.

Key concepts: Coding OA strategy and partial credit, HackerRank and CodeSignal practice, CS fundamentals MCQs, Output prediction questions, Quantitative aptitude, Logical reasoning, Verbal ability, Full-length timed mocks.

Mini project: Run a two-week OA sprint: each weekday do two timed coding problems on HackerRank, 20 aptitude questions and 15 CS MCQs, and each weekend a full mock; log scores in a sheet and target your two weakest categories in the second week.

Self-check: You have 90 minutes and three problems: an easy, a medium, and a hard you only have a brute force for. How do you allocate your time and why?

Resources:
- [HackerRank Interview Preparation Kit](https://www.hackerrank.com/interview/interview-preparation-kit) (HackerRank)
- [IndiaBIX aptitude practice](https://www.indiabix.com/) (IndiaBIX)
- [GeeksforGeeks: Aptitude questions and answers](https://www.geeksforgeeks.org/aptitude-questions-and-answers/) (GeeksforGeeks)

### Performing in the Coding Interview

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/coding-interview-skills

Communicate like an engineer in a live DSA round: clarify, talk through brute force and optimisation, code cleanly, test out loud and handle hints.

Solving a problem alone and solving it in front of an interviewer are different skills. Interviewers grade **problem solving, communication, code quality and testing**, not just the final answer.

#### A round, minute by minute
- **Clarify (2-3 min)**: restate the problem, ask about input size, duplicates, negative numbers, empty input and expected output format. Work a small example together.
- **Brute force (2-3 min)**: state it and its complexity. This proves you understand the problem and gives a fallback.
- **Optimise (5-10 min)**: say which bottleneck you are attacking and which pattern might help. Get agreement before coding.
- **Code (15-20 min)**: clean names, helper functions, no clever one-liners. Narrate the key decisions, not every keystroke.
- **Test (5 min)**: dry run your code on the example, then edge cases. Find your own bugs before the interviewer does.
- **Complexity**: state final time and space, and mention any trade-offs.

#### Handling difficulty
- Stuck? Say what you are considering: "Sorting would give n log n; I wonder if a hash map can do better." Silence is the real failure.
- **Take hints gracefully** and build on them; using hints well is a positive signal.
- If time runs short, explain what remains and how you would finish it.

#### Platforms and formats
Shared editors (CoderPad, CodeSignal, Google Docs with no autocomplete), whiteboards in on-site rounds, and occasionally your own IDE. Practise at least some problems without autocomplete or running code.

#### Common failure modes
Coding before clarifying, going silent for five minutes, arguing with hints, skipping testing, and using a language feature you cannot explain.

Good enough to move on: in mock interviews you consistently finish a medium problem with clean, tested code in 35 minutes while explaining your reasoning throughout.

Key concepts: Clarifying questions and examples, Brute force then optimise, Thinking out loud, Clean interview code, Dry runs and edge case testing, Using hints well, Coding without autocomplete.

Mini project: Solve ten medium problems in a plain editor with no autocomplete and no running code, recording your voice as you go. Review each recording against the six-step structure and note where you went silent or skipped testing.

Self-check: Your optimal idea is not working ten minutes before the end. What do you say and do to maximise your evaluation?

Resources:
- [Tech Interview Handbook: Coding interview best practices](https://www.techinterviewhandbook.org/coding-interview-techniques/) (Tech Interview Handbook)
- [LeetCode Explore: Interview crash courses](https://leetcode.com/explore/) (LeetCode)

### Behavioral and HR Interviews

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/behavioral-interviews

Prepare stories with the STAR method for teamwork, conflict, failure and leadership questions, and handle HR rounds, culture fit and 'tell me about yourself'.

Behavioral rounds decide more offers than students expect, and they are the easiest to improve with preparation. Amazon's Leadership Principles round, Google's "Googleyness" round and every HR round follow the same logic: past behaviour predicts future behaviour.

#### The STAR method
- **Situation**: brief context (one or two sentences).
- **Task**: what you were responsible for.
- **Action**: what *you* did, in detail. This is 60% of the answer. Say "I", not "we".
- **Result**: the outcome, quantified if possible, plus what you learned.
Keep each answer to about two minutes.

#### Build a story bank
Prepare 6-8 stories from projects, internships, hackathons, clubs and group assignments, then map each to several themes:
- A challenging technical problem you solved.
- A conflict or disagreement with a teammate.
- A failure or mistake and what you changed afterwards.
- Taking ownership or leading without authority.
- Meeting a tight deadline or juggling priorities.
- Learning something new quickly.

#### Common questions
- "Tell me about yourself": a 60-90 second pitch covering who you are, what you have built, and why this role.
- "Why this company?": show you researched its products and engineering, not just its brand.
- Strengths and weaknesses: pick a real weakness and show what you are doing about it.
- HR topics: relocation, bonds, higher studies plans, salary expectations. Be honest and consistent.

#### Questions to ask them
Always have two or three: about the team's work, how interns are mentored, or what success looks like in the first months.

Good enough to move on: you can answer any common behavioral question with a specific STAR story in under two minutes without it sounding memorised.

Key concepts: STAR method, Building a story bank, Tell me about yourself pitch, Conflict, failure and ownership stories, Amazon Leadership Principles, HR round questions, Questions to ask the interviewer.

Mini project: Write out eight STAR stories in a document, tag each with the themes it covers and at least two Amazon Leadership Principles, then rehearse them aloud with a timer and a friend who asks one follow-up question per story.

Self-check: Tell a two-minute story about a disagreement with a teammate using STAR. Where did you say 'we' when you should have said 'I'?

Resources:
- [Tech Interview Handbook: Behavioral interviews](https://www.techinterviewhandbook.org/behavioral-interview/) (Tech Interview Handbook)
- [Amazon Leadership Principles](https://www.amazon.jobs/content/en/our-workplace/leadership-principles) (Amazon)

### Mock Interviews and Feedback Loops

core · intermediate · about 12 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/mock-interviews

Practise full interview loops with peers and platforms, give and receive structured feedback, and track progress until real interviews feel familiar.

Mock interviews convert knowledge into performance. Most candidates who fail with good preparation fail because the real setting was unfamiliar, and mocks remove that surprise.

#### Where to get mocks
- **Peers**: pair up with a friend and alternate interviewer and candidate. Being the interviewer teaches you what good answers look like.
- **Seniors and alumni** who recently cleared product company interviews.
- **Platforms**: Pramp (free peer mocks), interviewing.io, and peer mock features on prep platforms, including InternHack.
- College placement cells often arrange mock drives before the season.

#### How to run a good mock
- Use real conditions: camera on, 45 minutes, shared editor with no autocomplete, an unseen problem.
- The interviewer takes notes on four dimensions: **problem solving, communication, code quality, testing**.
- End with 10 minutes of candid feedback: one thing to keep doing, two things to fix.
- Rotate formats: DSA, CS fundamentals (OS, DBMS, networks rapid-fire), LLD, HLD and behavioral.

#### Track and iterate
- Keep a log of every mock and real interview: questions asked, how it went, feedback, and what to practise next.
- Look for patterns, such as always struggling with graphs or rushing testing, and schedule targeted practice.
- Increase frequency as the season approaches: one mock a week early on, two or three a week in the final month.

#### Mindset
Treat early real interviews as practice too, applying to a few lower-priority companies first. Rejections are data. Rest before important rounds; performance drops sharply when you are exhausted.

Good enough to move on: you have done at least ten mocks across formats, your feedback log shows your top weakness improving, and a new mock no longer makes you nervous.

Key concepts: Peer mocks and swapping roles, Mock platforms, Realistic interview conditions, Structured feedback rubric, Interview log and pattern tracking, CS fundamentals rapid-fire rounds, Managing nerves and energy.

Mini project: Organise a four-week mock series with two or three friends: two DSA mocks, one CS fundamentals rapid-fire, one LLD or HLD and one behavioral mock each, all logged with the four-dimension rubric, and present your before and after scores at the end.

Self-check: What did your last three mocks have in common in their feedback, and what specific practice have you scheduled to fix it?

Resources:
- [Pramp free peer mock interviews](https://www.pramp.com/) (Pramp)
- [interviewing.io](https://interviewing.io/) (interviewing.io)
- [Tech Interview Handbook: Mock interviews](https://www.techinterviewhandbook.org/mock-interviews/) (Tech Interview Handbook)

### Company-Specific Preparation and Offers

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/cs-fundamentals/company-specific-prep

Research each company's interview pattern, from service companies to product giants and startups, prepare in the final weeks accordingly, and handle offers and negotiation.

Companies test the same fundamentals but weight them very differently. Spending the last two or three weeks before an interview on that company's specific pattern gives an outsized return.

#### Broad patterns (these change, so verify with recent candidates)
- **Mass recruiters and service companies** (TCS, Infosys, Wipro, Accenture, Cognizant): aptitude and basic coding OA, then technical and HR interviews focused on OOP, DBMS, a project and simple programs. Special tracks like TCS Digital or Infosys SP go deeper into DSA.
- **Big product companies** (Google, Microsoft, Amazon, Adobe, Atlassian): a hard coding OA, then two to four DSA rounds, sometimes LLD or a CS fundamentals round, and a behavioral round (Amazon's is heavily Leadership Principles based).
- **Indian product companies and unicorns** (Flipkart, Swiggy, Razorpay, PhonePe, Zomato): DSA plus a **machine coding** round and often LLD, with HLD for experienced hires.
- **Startups**: often a take-home assignment or a practical build, deep discussion of your projects, and a culture-fit conversation.
- **Quant and trading firms** (optional path): heavy math, probability puzzles and competitive-programming-level problems.

#### How to research
- Read recent interview experiences on LeetCode Discuss, GeeksforGeeks interview experiences, Glassdoor and seniors' notes.
- Filter LeetCode problems by company tag (with premium or community lists) and do the most frequent ones.
- Study the company's products and engineering blog for "why this company" and system design context.

#### Final-week checklist
Revise your mistake log, redo company-tagged problems, rehearse your resume walkthrough and STAR stories, and prepare questions to ask.

#### Offers
Understand CTC vs in-hand salary, joining bonuses, stock vesting, bonds and PPO conversion rates for internships. Negotiate politely with competing offers as leverage, and never renege after formally accepting.

Good enough to move on: for each target company you have a one-page note on its rounds, top question themes and your prep plan, and you can explain the components of an offer letter.

Key concepts: Service company patterns, Big tech interview loops, Indian product companies and machine coding, Startup take-home assignments, Reading interview experiences, Company-tagged problem practice, Understanding CTC, stocks and bonds, Negotiation and offer etiquette, Quant firm interviews.

Mini project: Pick your five target companies and build a one-page prep note for each from at least five recent interview experiences: rounds, question themes, three most frequent problems, and a two-week plan. Execute the plan for your top choice and review what matched the real interview.

Self-check: How would your final two weeks of preparation differ for Amazon versus Flipkart, based on their interview rounds?

Resources:
- [LeetCode Discuss: Interview experiences](https://leetcode.com/discuss/) (LeetCode)
- [GeeksforGeeks: Company interview corner](https://www.geeksforgeeks.org/company-interview-corner/) (GeeksforGeeks)
- [Tech Interview Handbook: Negotiation](https://www.techinterviewhandbook.org/negotiation/) (Tech Interview Handbook)

## Related

- [Career roadmaps](https://www.internhack.in/roadmaps)
