# DSA and Placement Prep roadmap

> The complete path to cracking Indian campus placements and off-campus SDE roles: DSA, aptitude, CS core subjects, OAs and interviews.

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

17 sections, 60 topics, about 394 hours.

A placement-first roadmap for Indian college students. Pick one language and master its standard library, learn to reason about complexity, then work pattern by pattern through arrays, hashing, two pointers, sliding window, prefix sums, binary search, recursion and backtracking, linked lists, stacks and queues, heaps, trees, graphs, greedy, dynamic programming, tries and bit manipulation, with segment trees as an advanced option. Build a practice system around sheets, spaced repetition and contests on LeetCode, Codeforces and CodeChef. Then cover everything else a placement drive tests: quantitative aptitude, logical reasoning, verbal ability, OOP, DBMS and SQL, operating systems and computer networks, online assessment patterns for TCS NQT, Infosys, Accenture and product companies, a fresher resume and projects, technical and HR rounds, and an 8-12 week plan that ties it all together.

## Outcomes

- Write clean, bug-free solutions in one language using its standard library fluently
- Estimate time and space complexity and pick an approach that fits the constraints
- Recognise and apply the core patterns: hashing, two pointers, sliding window, prefix sums and binary search on answer
- Solve recursion, backtracking, linked list, stack, queue and heap problems at interview level
- Handle tree and graph problems including BFS, DFS, topological sort, shortest paths, MST and DSU
- Break dynamic programming problems into states and transitions across 1D, 2D, knapsack, LIS and interval DP
- Run a sustainable practice system with sheets, revision logs and weekly contests
- Clear aptitude, reasoning and verbal sections of mass-recruiter tests within time
- Answer OOP, DBMS, SQL, OS and Computer Networks interview questions with confidence
- Present a one-page resume and two strong projects, and handle technical and HR rounds
- Follow a realistic 8-12 week plan from first problem to offer

## Prerequisites

- Basic programming in any one language (loops, functions, arrays)
- School-level mathematics

## Getting Started: Placements, Language and Complexity

Understand how placement drives work, pick one language and learn its standard library, and learn to judge whether a solution will pass before you write it.

### How Campus and Off-Campus Hiring Works

core · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/placement-landscape

Learn the difference between service and product companies, the rounds each one runs, eligibility rules, and what each round actually tests.

Before you solve a single problem, know what you are preparing for. Indian fresher hiring falls into two broad buckets and they test different things.

#### Service companies (mass recruiters)
TCS, Infosys, Wipro, Accenture, Cognizant, Capgemini, HCLTech and Tech Mahindra hire thousands of freshers every year. Their process is usually an **online test** (aptitude, reasoning, verbal, basic coding), then a **technical interview** on CS basics and your projects, then an **HR round**. Easy-to-medium DSA and strong aptitude are enough for most roles; higher bands like TCS Digital or Infosys Specialist Programmer need stronger coding.

#### Product companies
Amazon, Microsoft, Google, Flipkart, Atlassian, startups and fintechs run a **coding OA** (2-4 DSA problems on HackerRank, HackerEarth or their own platform), then 2-4 **technical rounds** that go deeper into DSA, CS core subjects and sometimes low-level design, then a hiring manager or HR conversation. Here DSA depth decides the outcome.

#### Things that filter you before any test
- **Eligibility**: CGPA cut-offs (often 6.0 to 7.5), no active backlogs, branch restrictions.
- **Placement policy**: many colleges stop you from sitting for more companies after one offer, or separate "dream" and "super dream" slots. Read your college rules early.
- **Off-campus routes**: referrals, careers pages, hiring challenges (TCS CodeVita, Infosys HackWithInfy, Flipkart GRiD) and platforms like Unstop.

#### Pitfalls
- Preparing only DSA and failing the aptitude cut-off in a mass-recruiter test.
- Ignoring CGPA until final year, when it is too late to cross a cut-off.

You are ready to move on when you can list your target companies, the rounds each one runs, and which skills each round tests.

Key concepts: Service vs product companies, Typical round structure, Eligibility and CGPA cut-offs, College placement policies, Off-campus routes and referrals, Hiring challenges.

Mini project: Build a target sheet of 15 companies (5 mass recruiters, 5 mid-size product, 5 dream): eligibility, rounds, typical CTC band, last year's visit month and one senior you can ask about it.

Self-check: What is the main difference between how TCS and Amazon evaluate a fresher, and how should that change the time you spend on aptitude vs DSA?

Resources:
- [Tech Interview Handbook](https://www.techinterviewhandbook.org/) (Tech Interview Handbook)
- [Unstop: hiring challenges and competitions](https://unstop.com/) (Unstop)
- [PrepInsta placement preparation](https://prepinsta.com/) (PrepInsta)

### C++ and the STL

recommended · beginner · about 15 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/cpp-stl

Use C++ with the Standard Template Library: the fastest and most common choice for placements and competitive programming.

C++ is the default language for competitive programming and most Indian placement OAs. It is fast, so slightly heavier solutions still pass, and the **STL** gives you every data structure you need.

#### The subset you need
- Types and limits: `int` holds about 2.1e9, `long long` about 9.2e18. Use `long long` for sums and products.
- Containers: `vector`, `string`, `pair`, `stack`, `queue`, `deque`, `priority_queue`, `set`, `multiset`, `map`, `unordered_map`, `unordered_set`.
- Algorithms: `sort` with lambdas, `lower_bound`, `upper_bound`, `reverse`, `accumulate`, `next_permutation`, `__gcd` or `std::gcd`.
- Pass large containers by reference: `const vector<int>& a`.
- Fast I/O: `ios::sync_with_stdio(false); cin.tie(nullptr);`

#### Pitfalls
- `a * b` computed in `int` overflows before it is stored into a `long long`. Cast one side first.
- `v.size() - 1` on an empty vector wraps to a huge unsigned number.
- `mp[key]` inserts a default entry; use `count` or `find` to test membership.
- `unordered_map` can be hacked to O(n) per operation on Codeforces; use `map` or a custom hash there.

You are ready to move on when you can write a frequency map, sort pairs by second value with a lambda and build a min-heap without looking anything up.

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

Mini project: Write a contest template, then solve 8 warm-ups using only STL: word frequency, sort students by marks then name, k largest with a heap, remove duplicates with set, anagram check, first element >= x with lower_bound, next permutation, and running median with two heaps.

Self-check: Why can passing a vector<int> by value into a recursive function cause TLE, and what is the one-word fix?

Resources:
- [cppreference: containers library](https://en.cppreference.com/w/cpp/container) (cppreference)
- [LearnCpp.com](https://www.learncpp.com/) (LearnCpp)
- [Competitive Programmer's Handbook](https://cses.fi/book/book.pdf) (CSES)

### Java and the Collections Framework

alternative · beginner · about 15 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/java-collections

Use Java with ArrayList, HashMap, ArrayDeque and PriorityQueue: a strong choice if your college teaches Java or you target Java backend roles.

Java is accepted on every OA platform and is common in service-company interviews. It is verbose but safe, and the **Collections Framework** covers every structure you need.

#### The subset you need
- Primitives vs wrappers: `int` vs `Integer`, `long` for big sums.
- Collections: `ArrayList`, `HashMap`, `HashSet`, `TreeMap`, `TreeSet` (ordered, with `floorKey` and `ceilingKey`), `ArrayDeque` (use it for both stack and queue), `PriorityQueue`.
- Sorting: `Arrays.sort`, `Collections.sort`, comparators like `(a, b) -> a[1] - b[1]` or `Comparator.comparingInt`.
- `StringBuilder` for building strings in loops.
- Fast input with `BufferedReader` and `StringTokenizer` instead of `Scanner` for large inputs.

#### Pitfalls
- Comparing `Integer` objects with `==` works for small values (cached) and silently fails for larger ones. Use `.equals`.
- Comparator `a - b` can overflow for large values; use `Integer.compare(a, b)`.
- `String` concatenation in a loop is O(n^2); use `StringBuilder`.
- `Arrays.sort` on a primitive `int[]` uses quicksort and can be pushed to O(n^2) by adversarial tests on Codeforces; shuffle first or sort an `Integer[]`.

You are ready to move on when you can use a HashMap for counting, an ArrayDeque as a stack and a PriorityQueue with a custom comparator from memory.

Key concepts: Primitives vs wrapper types, ArrayList, HashMap, HashSet, TreeMap and TreeSet, ArrayDeque as stack and queue, PriorityQueue with comparators, StringBuilder, Fast I/O with BufferedReader.

Mini project: Solve 8 warm-ups in Java using only the Collections Framework: word frequency, sort intervals by start, k largest with a PriorityQueue, valid parentheses with ArrayDeque, first unique character, floor lookup with TreeMap, group anagrams and running median with two heaps.

Self-check: Why might comparing two Integer objects with == pass on small test cases and fail on large ones?

Resources:
- [Oracle Java Tutorials: Collections](https://docs.oracle.com/javase/tutorial/collections/) (Oracle)
- [Java SE API documentation](https://docs.oracle.com/en/java/javase/21/docs/api/) (Oracle)
- [GeeksforGeeks](https://www.geeksforgeeks.org/) (GeeksforGeeks)

### Python for DSA

alternative · beginner · about 12 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/python-for-dsa

Use Python with collections, heapq and bisect: the quickest language to write, fine for interviews but sometimes too slow for strict OAs.

Python lets you write short, readable solutions, which helps a lot in live interviews. The trade-off is speed: some OA problems with tight limits are hard to pass in Python.

#### The subset you need
- Lists, tuples, dicts, sets, slicing and comprehensions.
- `collections`: `Counter`, `defaultdict`, `deque` (O(1) at both ends).
- `heapq`: a min-heap on a plain list. For a max-heap, push negated values.
- `bisect`: `bisect_left` and `bisect_right` for binary search on sorted lists.
- `sorted(arr, key=lambda x: (x[1], x[0]))` for multi-key sorts.
- Fast input: `sys.stdin.readline`.

#### Pitfalls
- `list.pop(0)` and `list.insert(0, x)` are O(n). Use `deque`.
- Default recursion limit is about 1000. Deep DFS needs `sys.setrecursionlimit` or an iterative version.
- `[[0] * m] * n` makes n references to the same row. Use a comprehension.
- String concatenation in a loop is slow; collect parts and `"".join` them.
- If a platform offers PyPy, it is often several times faster for loop-heavy code.

You are ready to move on when you can use Counter, deque, heapq and bisect correctly without looking them up and know when to switch to an iterative solution.

Key concepts: Lists, dicts, sets and slicing, Counter and defaultdict, deque, heapq and max-heap trick, bisect, Recursion limit and iterative DFS, PyPy vs CPython.

Mini project: Solve 8 warm-ups in Python using only the standard library: word frequency with Counter, sliding window max with deque, top k frequent with heapq, search insert position with bisect, group anagrams with defaultdict, BFS on a grid, merge intervals and running median with two heaps.

Self-check: Why is using list.pop(0) inside a BFS loop a performance bug, and what should you use instead?

Resources:
- [Python docs: collections](https://docs.python.org/3/library/collections.html) (Python)
- [Python docs: heapq](https://docs.python.org/3/library/heapq.html) (Python)
- [Python docs: bisect](https://docs.python.org/3/library/bisect.html) (Python)

### Time and Space Complexity

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/complexity-analysis

Use Big-O to estimate whether an approach fits the constraints, and read constraints to guess the intended solution before coding.

Complexity analysis tells you, before you code, whether a solution will pass. Interviewers ask for it after every problem, so you must state it without hesitation.

#### Big-O basics
- Count how work grows with input size n, dropping constants and lower-order terms.
- Common classes: O(1), O(log n), O(n), O(n log n), O(n^2), O(2^n), O(n!).
- Nested loops multiply, sequential steps add. A loop that halves n each time is O(log n).
- Space counts extra memory, including the recursion stack.

#### Read the constraints
A judge does roughly 1e8 simple operations per second. Use this table:
- n up to 10 to 12: O(n!) or O(2^n * n) (permutations, bitmask brute force)
- n up to 20 to 25: O(2^n)
- n up to 500: O(n^3)
- n up to 5000: O(n^2)
- n up to 1e5 to 1e6: O(n log n) or O(n)
- n up to 1e9 or more: O(log n) or O(1) (math, binary search)

#### Amortised and recursive cost
Dynamic array push is O(1) amortised. Recursion cost is (number of calls) x (work per call): naive Fibonacci is O(2^n), merge sort is O(n log n) by the recurrence T(n) = 2T(n/2) + O(n).

#### Pitfalls
- Forgetting hidden costs: string concatenation, slicing, `substr` and copying inside loops.
- Calling an O(n) operation like `list.index` inside a loop and calling the result O(n).

You are ready to move on when you can look at a constraint like n = 2e5 and immediately say "I need O(n log n) or better".

Key concepts: Big-O, Big-Omega, Big-Theta, Common complexity classes, Space complexity and recursion stack, Reading constraints to pick an approach, Amortised analysis, Recurrences and Master theorem, Best, average and worst case.

Mini project: Take 15 code snippets from your old assignments or LeetCode discussions, write the time and space complexity of each, then verify 5 of them by timing them on inputs of size 1e3, 1e4 and 1e5.

Self-check: A problem has n up to 2e5. Your solution has two nested loops over n. Will it pass, and what complexity should you aim for?

Resources:
- [Big-O Cheat Sheet](https://www.bigocheatsheet.com/) (bigocheatsheet)
- [Competitive Programmer's Handbook (Ch. 2)](https://cses.fi/book/book.pdf) (CSES)
- [USACO Guide](https://usaco.guide/) (USACO Guide)

## Arrays, Strings and Hashing

The foundation of most OA questions: in-place array tricks, string handling, and hash maps that turn O(n^2) searches into O(n).

### Arrays: Core Techniques

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/arrays

Master traversal, in-place updates, rotation, Kadane's algorithm and the classic array problems that open almost every OA.

Arrays appear in nearly every coding round. Most array questions reduce to a handful of reusable ideas.

#### Key patterns
- **Running state in one pass**: track max, min, sum or best-so-far while scanning (Best Time to Buy and Sell Stock).
- **Kadane's algorithm**: maximum subarray sum in O(n) by deciding at each index whether to extend or restart.
- **In-place rearrangement**: Dutch national flag for Sort Colors, moving zeroes, rotating by reversal (reverse all, then reverse each part).
- **Index as hash**: when values are in 1..n, mark visited by negating or swapping into place (Find the Duplicate Number, First Missing Positive).
- **Matrix traversal**: spiral order, transpose then reverse rows to rotate 90 degrees.

#### Classic problems
Two Sum (brute force first), Maximum Subarray, Best Time to Buy and Sell Stock, Sort Colors, Rotate Array, Next Permutation, Majority Element (Boyer-Moore voting), Spiral Matrix, Set Matrix Zeroes.

#### Pitfalls
- Off-by-one errors at the boundaries. Dry-run on arrays of size 0, 1 and 2.
- Kadane's with all negative numbers: initialise the answer to the first element, not 0.
- Modifying an array while iterating over it in a way that skips elements.

You are ready to move on when you can solve Maximum Subarray, Sort Colors and Next Permutation from scratch and explain each in one sentence.

Key concepts: Traversal and running state, Kadane's algorithm, Dutch national flag, Rotation by reversal, Boyer-Moore majority vote, Index marking for 1..n values, Matrix traversal and rotation.

Mini project: Solve these 10 in 7 days and log time taken plus the pattern used: Two Sum, Best Time to Buy and Sell Stock, Maximum Subarray, Sort Colors, Move Zeroes, Rotate Array, Majority Element, Next Permutation, Spiral Matrix, Set Matrix Zeroes.

Self-check: Why does Kadane's algorithm fail if you initialise the best sum to 0, and on what input does it fail?

Resources:
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)
- [takeUforward DSA course and sheets](https://takeuforward.org/) (takeUforward)
- [NeetCode roadmap](https://neetcode.io/roadmap) (NeetCode)

### Strings

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/strings

Handle character counting, palindromes, parsing and basic pattern matching, including the string questions service-company tests love.

String questions are very common in mass-recruiter OAs and in first-round interviews. Most rely on counting, two pointers or careful parsing.

#### Key patterns
- **Frequency arrays**: a size-26 array beats a hash map for lowercase letters (Valid Anagram, Ransom Note).
- **Two pointers from both ends**: palindromes, reversing words, Valid Palindrome with non-alphanumeric characters.
- **Expand around centre**: Longest Palindromic Substring in O(n^2) with O(1) space.
- **Parsing**: String to Integer (atoi), compressing runs ("aaabb" to "a3b2"), counting words.
- **Pattern matching**: naive O(n*m) first. KMP (prefix function) and Z-function give O(n + m) and appear in product-company rounds now and then. Rabin-Karp uses rolling hashes.

#### Classic problems
Valid Anagram, Valid Palindrome, Reverse Words in a String, Longest Common Prefix, String Compression, Longest Palindromic Substring, String to Integer (atoi), Find the Index of the First Occurrence in a String, Roman to Integer.

#### Pitfalls
- Building strings with += in a loop (O(n^2) in Java and Python).
- Forgetting uppercase, spaces, digits or Unicode in the input.
- In C++, `s.substr(i, len)` copies, so calling it inside a loop adds a hidden factor of n.

You are ready to move on when you can solve Longest Palindromic Substring by expanding around centre and explain what the KMP prefix function stores.

Key concepts: Character frequency arrays, Palindrome checks, Expand around centre, Parsing and string building, KMP prefix function, Z-function, Rabin-Karp rolling hash.

Mini project: Solve these 10 in 7 days, log time and pattern: Valid Anagram, Valid Palindrome, Reverse Words in a String, Longest Common Prefix, String Compression, Roman to Integer, String to Integer (atoi), Longest Palindromic Substring, Find the Index of the First Occurrence (with KMP), Count and Say.

Self-check: For Longest Palindromic Substring, why do you need to expand from both single characters and pairs of characters?

Resources:
- [cp-algorithms: Prefix function (KMP)](https://cp-algorithms.com/string/prefix-function.html) (cp-algorithms)
- [cp-algorithms: Z-function](https://cp-algorithms.com/string/z-function.html) (cp-algorithms)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Hashing with Maps and Sets

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/hashing

Use hash maps and sets to trade memory for speed: counting, seen-before checks, grouping and complement lookups.

Hashing is the single most useful trick in interviews. Whenever a brute force asks "have I seen something like this before?", a hash map or set usually removes a whole loop.

#### Key patterns
- **Complement lookup**: store values as you scan and check for target minus current (Two Sum in O(n)).
- **Frequency count**: Top K Frequent Elements, First Unique Character, Majority Element.
- **Grouping by a canonical key**: sorted string or count signature as the key (Group Anagrams).
- **Seen set**: Contains Duplicate, Longest Consecutive Sequence (start counting only from numbers whose predecessor is missing).
- **Prefix sum + map**: count subarrays with sum k (covered in the prefix sums topic).

#### How it works underneath
A hash function maps a key to a bucket. Collisions are handled by chaining or open addressing. Average O(1), worst case O(n). Ordered maps (C++ map, Java TreeMap) are balanced BSTs with O(log n) but keep keys sorted, which you need for floor and ceiling queries.

#### Pitfalls
- Using a hash map when a fixed-size array would do (characters, small value ranges).
- Mutable or custom keys: in C++ a pair needs a custom hash for unordered_map; in Java override equals and hashCode.
- Iterating a hash map and expecting sorted order.

You are ready to move on when you can solve Two Sum, Group Anagrams and Longest Consecutive Sequence in O(n) and explain the worst case of a hash map.

Key concepts: Complement lookup, Frequency counting, Grouping by canonical key, Seen sets and duplicates, Collisions and worst case, Hash map vs ordered map, Custom keys and hash functions.

Mini project: Solve these 10 in 7 days, log time and pattern: Two Sum, Contains Duplicate, Valid Anagram, Group Anagrams, Top K Frequent Elements, Longest Consecutive Sequence, First Unique Character in a String, Isomorphic Strings, Word Pattern, Encode and Decode Strings.

Self-check: In Longest Consecutive Sequence, why does starting a count only when x - 1 is absent keep the whole algorithm O(n)?

Resources:
- [NeetCode roadmap: Arrays and Hashing](https://neetcode.io/roadmap) (NeetCode)
- [cppreference: unordered_map](https://en.cppreference.com/w/cpp/container/unordered_map) (cppreference)
- [takeUforward](https://takeuforward.org/) (takeUforward)

## Two Pointers, Sliding Window and Prefix Sums

Three patterns that turn many O(n^2) array and string problems into O(n), and that show up in almost every product-company OA.

### Two Pointers

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/two-pointers

Move two indices through sorted arrays or strings to find pairs, remove duplicates and partition in linear time.

Two pointers works when moving one index in a known direction can only improve or worsen the answer in a predictable way. It usually needs sorted data or a structure with a clear order.

#### Variants
- **Opposite ends**: start at both ends and move inward (Two Sum II on sorted input, Container With Most Water, Valid Palindrome).
- **Same direction (slow and fast)**: a write pointer and a read pointer (Remove Duplicates from Sorted Array, Move Zeroes).
- **Fixing one, two-pointer the rest**: 3Sum is sort plus a loop plus two pointers, giving O(n^2) instead of O(n^3).
- **Two arrays**: merge two sorted arrays, intersection of sorted arrays.

#### Classic problems
Two Sum II, 3Sum, 3Sum Closest, 4Sum, Container With Most Water, Trapping Rain Water (two-pointer version), Remove Duplicates from Sorted Array, Merge Sorted Array, Squares of a Sorted Array.

#### Pitfalls
- Skipping duplicates wrongly in 3Sum, giving repeated triplets or missing ones.
- Applying two pointers to unsorted data where moving a pointer does not have a clear effect.
- Overflow in 4Sum when adding four large ints.

You are ready to move on when you can explain why, in Container With Most Water, you always move the shorter side.

Key concepts: Opposite-end pointers, Slow and fast pointers, Sort then two pointers, Skipping duplicates, Merging two sorted sequences, Trapping Rain Water.

Mini project: Solve these 10 in 7 days, log time and pattern: Two Sum II, Valid Palindrome, Remove Duplicates from Sorted Array, Move Zeroes, Merge Sorted Array, Squares of a Sorted Array, 3Sum, 3Sum Closest, Container With Most Water, Trapping Rain Water.

Self-check: Why does 3Sum need the array sorted first, and what is its final time complexity?

Resources:
- [NeetCode roadmap: Two Pointers](https://neetcode.io/roadmap) (NeetCode)
- [USACO Guide: Two Pointers](https://usaco.guide/) (USACO Guide)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Sliding Window

core · intermediate · about 7 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/sliding-window

Maintain a window over a contiguous range and update it incrementally for fixed-size and variable-size subarray and substring problems.

Sliding window applies when the question asks about a **contiguous** subarray or substring and the window's validity changes in one direction as it grows.

#### Two templates
- **Fixed size k**: add the new element, remove the one leaving, update the answer (Maximum Average Subarray, max sum of k consecutive elements).
- **Variable size**: expand the right end; while the window is invalid, shrink from the left; record the answer. Used for "longest" and "shortest" questions.

#### Classic problems
Longest Substring Without Repeating Characters, Longest Repeating Character Replacement, Minimum Size Subarray Sum, Permutation in String, Find All Anagrams in a String, Fruit Into Baskets, Max Consecutive Ones III, Minimum Window Substring, Sliding Window Maximum (with a monotonic deque).

#### The counting trick
"Number of subarrays with exactly k distinct" = atMost(k) - atMost(k - 1). The same trick works for "exactly k odd numbers" (Count Number of Nice Subarrays) and Binary Subarrays With Sum.

#### Pitfalls
- Using a sliding window when the array has negative numbers and you want a target sum. Shrinking no longer helps; use prefix sums with a hash map.
- Updating the answer before the window is valid again.
- Forgetting to decrement counts when the left pointer moves.

You are ready to move on when you can solve Minimum Window Substring and explain why each index enters and leaves the window at most once.

Key concepts: Fixed-size window, Variable-size window, Window with frequency map, atMost(k) - atMost(k-1) trick, Window maximum with deque, When sliding window fails.

Mini project: Solve these 10 in 7 days, log time and pattern: Maximum Average Subarray I, Longest Substring Without Repeating Characters, Minimum Size Subarray Sum, Max Consecutive Ones III, Fruit Into Baskets, Longest Repeating Character Replacement, Permutation in String, Find All Anagrams in a String, Subarrays with K Different Integers, Minimum Window Substring.

Self-check: Why does the variable sliding window fail for 'count subarrays with sum k' when the array contains negative numbers?

Resources:
- [NeetCode roadmap: Sliding Window](https://neetcode.io/roadmap) (NeetCode)
- [takeUforward](https://takeuforward.org/) (takeUforward)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Prefix Sums and Difference Arrays

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/prefix-sums

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

A prefix sum array stores the total of the first i elements, so any range sum is one subtraction. Combine it with a hash map and it solves a whole family of subarray counting problems.

#### Key patterns
- **Range sum query**: sum(l..r) = pre[r + 1] - pre[l]. Range Sum Query - Immutable.
- **2D prefix sums**: rectangle sums with inclusion-exclusion (Range Sum Query 2D).
- **Prefix sum + hash map**: count subarrays with sum k by storing how often each prefix value has appeared (Subarray Sum Equals K). Works with negative numbers, unlike sliding window.
- **Prefix modulo**: Subarray Sums Divisible by K, Continuous Subarray Sum.
- **Prefix of a transformed array**: treat 0 as -1 to find the longest subarray with equal 0s and 1s (Contiguous Array).
- **Difference array**: add v to a range in O(1) by updating two cells, then prefix-sum once (Corporate Flight Bookings, Car Pooling).
- **Prefix and suffix products**: Product of Array Except Self without division.

#### Pitfalls
- Off-by-one between 0-indexed arrays and 1-indexed prefix arrays. Pick one convention and stick to it.
- Forgetting to seed the map with prefix 0 seen once.
- Negative remainders in languages where -3 % 5 is -3; normalise with ((x % k) + k) % k.

You are ready to move on when you can solve Subarray Sum Equals K and explain why the map must start with {0: 1}.

Key concepts: 1D prefix sums, 2D prefix sums, Prefix sum with hash map, Prefix modulo, Difference arrays, Prefix and suffix products.

Mini project: Solve these 10 in 7 days, log time and pattern: Running Sum of 1d Array, Range Sum Query - Immutable, Find Pivot Index, Product of Array Except Self, Subarray Sum Equals K, Contiguous Array, Subarray Sums Divisible by K, Range Sum Query 2D - Immutable, Corporate Flight Bookings, Car Pooling.

Self-check: How does a difference array let you apply 1e5 range updates and then read the final array in O(n + q)?

Resources:
- [USACO Guide: Prefix Sums](https://usaco.guide/) (USACO Guide)
- [CSES Problem Set](https://cses.fi/problemset/) (CSES)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

## Sorting and Binary Search

Know how the classic sorts work, use sorting as a preprocessing step, and apply binary search on arrays and on the answer space.

### Sorting Algorithms and Custom Sorts

core · beginner · about 7 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/sorting

Understand bubble, selection, insertion, merge, quick and counting sort, and use built-in sorts with custom comparators to simplify problems.

Interviewers at service companies often ask you to write a sorting algorithm by hand. Product companies care more about whether you see that sorting first makes the problem easy.

#### The algorithms to know
- **Bubble, selection, insertion**: O(n^2). Insertion sort is fast on nearly sorted data and is stable.
- **Merge sort**: O(n log n) always, stable, O(n) extra space. Its merge step also counts inversions.
- **Quick sort**: O(n log n) average, O(n^2) worst case on bad pivots, in-place. Know Lomuto or Hoare partition.
- **Heap sort**: O(n log n), in-place, not stable.
- **Counting and radix sort**: O(n + k) when values lie in a small range.

#### Sorting as a tool
- Sort intervals by start, then merge (Merge Intervals, Meeting Rooms).
- Sort with a custom comparator: Largest Number compares a + b vs b + a.
- Sort then two pointers or binary search.
- Quickselect finds the kth smallest in O(n) average (Kth Largest Element in an Array).

#### Classic problems
Sort an Array (write merge sort), Merge Intervals, Insert Interval, Largest Number, Sort Colors, Kth Largest Element, Count Inversions, Maximum Gap.

#### Pitfalls
- Comparators that are not strict weak orderings (returning true for equal elements in C++) cause crashes or wrong output.
- Forgetting stability matters when sorting by one key after another.

You are ready to move on when you can write merge sort and quick sort from memory and explain when each is the better choice.

Key concepts: Bubble, selection, insertion sort, Merge sort and inversion count, Quick sort and partitioning, Heap sort, Counting and radix sort, Stability, Custom comparators, Quickselect.

Mini project: Implement bubble, insertion, merge and quick sort in one file and time them on 1e3, 1e4 and 1e5 random and sorted inputs. Then solve: Merge Intervals, Insert Interval, Largest Number, Kth Largest Element in an Array, Count Inversions (GfG), and Meeting Rooms.

Self-check: Why does quick sort degrade to O(n^2) on an already sorted array with a first-element pivot, and how do you avoid it?

Resources:
- [VisuAlgo: sorting visualisations](https://visualgo.net/en/sorting) (VisuAlgo)
- [Competitive Programmer's Handbook (Ch. 3)](https://cses.fi/book/book.pdf) (CSES)
- [GeeksforGeeks](https://www.geeksforgeeks.org/) (GeeksforGeeks)

### Binary Search on Arrays

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/binary-search

Search sorted and rotated arrays in O(log n), find first and last occurrences, and write a bug-free binary search every time.

Binary search is short to write and easy to get wrong. Learn one template and use it everywhere.

#### One reliable template
Search for the **first index where a condition becomes true** (lower bound). Keep lo and hi so the answer is always inside [lo, hi], use mid = lo + (hi - lo) / 2, and shrink until lo == hi. Every variant below is a choice of condition.

#### Variants
- First and last position of an element (two lower-bound searches).
- Search insert position, floor and ceiling.
- **Rotated sorted array**: one half is always sorted; decide which half the target is in.
- Find minimum in a rotated array, peak element (compare mid with mid + 1).
- **2D matrix**: treat a row-major sorted matrix as one array, or walk from the top-right corner for row-and-column sorted matrices.
- Median of Two Sorted Arrays: binary search on the partition (a hard classic).

#### Pitfalls
- (lo + hi) / 2 overflows for large ints; use lo + (hi - lo) / 2.
- Infinite loops when lo = mid and mid rounds down. Match the rounding to the update.
- Rotated arrays with duplicates break the O(log n) guarantee.

You are ready to move on when you can solve Search in Rotated Sorted Array and Find First and Last Position without a single off-by-one bug on the first submission.

Key concepts: Lower bound and upper bound, Loop invariants, First and last occurrence, Rotated sorted arrays, Peak element, Search in 2D matrix, Median of two sorted arrays.

Mini project: Solve these 10 in 7 days, log time and pattern: Binary Search, Search Insert Position, Find First and Last Position, Search in Rotated Sorted Array, Search in Rotated Sorted Array II, Find Minimum in Rotated Sorted Array, Find Peak Element, Single Element in a Sorted Array, Search a 2D Matrix, Median of Two Sorted Arrays.

Self-check: In a rotated sorted array, how do you decide which half to discard after computing mid?

Resources:
- [cp-algorithms: Binary search](https://cp-algorithms.com/num_methods/binary_search.html) (cp-algorithms)
- [takeUforward](https://takeuforward.org/) (takeUforward)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Binary Search on the Answer

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/binary-search-on-answer

Binary search over the range of possible answers using a monotonic feasibility check: a very common pattern in product-company OAs.

Many optimisation problems say "find the minimum maximum" or "the smallest value such that...". If you can check whether a candidate answer x is feasible, and feasibility is **monotonic** (if x works, every larger x works), binary search on x.

#### The recipe
1. Find the answer range [lo, hi], for example 1 to max(arr) or 1 to sum(arr).
2. Write `feasible(x)`, usually a greedy O(n) pass.
3. Binary search for the smallest feasible x. Total cost: O(n log(range)).

#### Classic problems
Koko Eating Bananas, Capacity To Ship Packages Within D Days, Split Array Largest Sum, Book Allocation (GfG), Aggressive Cows (SPOJ), Minimum Number of Days to Make m Bouquets, Find the Smallest Divisor Given a Threshold, Magnetic Force Between Two Balls, Painter's Partition, Nth root of a number.

#### Spotting it
- Phrases like "minimise the maximum", "maximise the minimum", "least capacity", "at least k".
- Large answer ranges (up to 1e9 or 1e18) with n up to 1e5.
- Binary search on real numbers: loop a fixed 100 times instead of comparing with an epsilon.

#### Pitfalls
- Getting the feasibility direction backwards, so the search converges to the wrong end.
- Overflow inside feasible() when summing; use 64-bit integers.
- Setting lo too high (for example max(arr) in a problem where the answer can be smaller).

You are ready to move on when you can explain why Aggressive Cows is "maximise the minimum distance" and write its feasibility check in five lines.

Key concepts: Monotonic feasibility, Choosing the search range, Greedy feasibility checks, Minimise the maximum, Maximise the minimum, Binary search on real numbers.

Mini project: Solve these 10 in 7 days, log time and pattern: Sqrt(x), Koko Eating Bananas, Find the Smallest Divisor Given a Threshold, Capacity To Ship Packages Within D Days, Minimum Number of Days to Make m Bouquets, Aggressive Cows, Book Allocation, Split Array Largest Sum, Magnetic Force Between Two Balls, Kth Missing Positive Number.

Self-check: Why is feasibility monotonic in Capacity To Ship Packages, and what are the correct lo and hi?

Resources:
- [USACO Guide: Binary Search](https://usaco.guide/) (USACO Guide)
- [Codeforces EDU: Binary Search](https://codeforces.com/edu/courses) (Codeforces)
- [takeUforward](https://takeuforward.org/) (takeUforward)

## Recursion and Backtracking

Think recursively, trust the function, and explore choices systematically with pruning: the base for trees, graphs and DP.

### Recursion Fundamentals

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

Write recursive functions with clear base cases, understand the call stack, and recognise the pick or not-pick pattern used everywhere later.

Recursion is the foundation for trees, graphs, backtracking and DP. If recursion feels shaky, every later topic will too.

#### How to think
- Define what the function returns for a given input, in one sentence.
- Write the **base case** first.
- Assume the function works for smaller inputs (the leap of faith) and combine the results.
- Draw the **recursion tree** for small inputs to see the number of calls and the stack depth.

#### Core patterns
- **Linear recursion**: factorial, sum of digits, reverse an array, check palindrome.
- **Divide and conquer**: power(x, n) in O(log n), merge sort.
- **Pick or not pick**: at each index, include the element or skip it. This generates all subsequences and later becomes subset-sum DP.
- **Return values vs global state**: count subsequences with sum k by returning counts instead of mutating a global.

#### Classic problems
Pow(x, n), Print all subsequences, Count subsequences with sum K, Generate Parentheses, Tower of Hanoi, Fibonacci (then see why it is O(2^n)), Reverse a stack using recursion, Sort a stack using recursion.

#### Pitfalls
- Missing or wrong base case causing stack overflow.
- Deep recursion (depth 1e5 or more) crashing; know when to go iterative.
- Passing large structures by value at every call.

You are ready to move on when you can draw the recursion tree for printing all subsequences of [1, 2, 3] and state its time complexity.

Key concepts: Base case and recursive case, Call stack and stack depth, Recursion trees, Pick or not-pick pattern, Divide and conquer, Tail recursion and iteration.

Mini project: Solve these 10 in 7 days without loops where possible, log time and pattern: Factorial, Reverse an array, Check palindrome, Pow(x, n), Print all subsequences, Count subsequences with sum K, Generate Parentheses, Tower of Hanoi, Reverse a stack using recursion, Sort a stack using recursion.

Self-check: How many calls does the pick or not-pick recursion make for an array of size n, and how deep does the stack go?

Resources:
- [takeUforward recursion series](https://takeuforward.org/) (takeUforward)
- [VisuAlgo: recursion tree](https://visualgo.net/en/recursion) (VisuAlgo)
- [GeeksforGeeks](https://www.geeksforgeeks.org/) (GeeksforGeeks)

### Backtracking

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

Build candidate solutions step by step, undo choices on return, and prune early to solve subsets, permutations and constraint puzzles.

Backtracking is recursion that explores a tree of choices: make a choice, recurse, then **undo** the choice. It is the standard approach when you must list every valid configuration.

#### Template
1. If the current state is a complete solution, record it and return.
2. For each available choice: if it is valid, apply it, recurse, then undo it.

#### Families
- **Subsets**: Subsets, Subsets II (sort and skip duplicates at the same level).
- **Combinations**: Combination Sum (reuse allowed), Combination Sum II (no reuse, skip duplicates), Combinations.
- **Permutations**: with a used[] array or by swapping in place; Permutations II for duplicates.
- **Partitioning**: Palindrome Partitioning.
- **Grid search**: Word Search, Rat in a Maze.
- **Constraint puzzles**: N-Queens (track columns and both diagonals), Sudoku Solver, M-Coloring.

#### Pruning
Sort the input and break early when the remaining target goes negative. Check constraints before recursing, not after. Good pruning is the difference between TLE and accepted.

#### Pitfalls
- Forgetting to undo state (pop from the path, unmark visited).
- Adding a reference to the path instead of a copy to the answer list (Java and Python).
- Duplicate handling: skip only when i > start and nums[i] == nums[i - 1].

You are ready to move on when you can solve N-Queens and Subsets II and explain how your duplicate-skip condition works.

Key concepts: Choose, explore, unchoose, Subsets and combinations, Permutations, Handling duplicates, Pruning, Grid backtracking, N-Queens and Sudoku.

Mini project: Solve these 10 in 7 days, log time and pattern: Subsets, Subsets II, Combination Sum, Combination Sum II, Permutations, Permutations II, Letter Combinations of a Phone Number, Palindrome Partitioning, Word Search, N-Queens.

Self-check: In Combination Sum II, why does the duplicate check use i > start rather than i > 0?

Resources:
- [NeetCode roadmap: Backtracking](https://neetcode.io/roadmap) (NeetCode)
- [Competitive Programmer's Handbook (Ch. 5)](https://cses.fi/book/book.pdf) (CSES)
- [CSES Problem Set](https://cses.fi/problemset/) (CSES)

## Linked Lists, Stacks and Queues

Pointer manipulation, LIFO and FIFO structures, and the monotonic stack pattern behind next-greater and histogram problems.

### Linked Lists

core · beginner · about 7 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/linked-lists

Reverse, merge, split and detect cycles in singly and doubly linked lists using dummy nodes and slow and fast pointers.

Linked list questions test careful pointer handling more than clever ideas. They are very common in first technical rounds at both service and product companies.

#### Core techniques
- **Dummy (sentinel) node**: removes special cases when the head might change.
- **Iterative reversal** with prev, curr and next. Also know the recursive version.
- **Slow and fast pointers**: middle of the list, cycle detection (Floyd's), start of the cycle, nth node from the end (gap of n).
- **Merge**: two sorted lists; then Sort List using merge sort.
- **Splitting and reconnecting**: Reorder List (find middle, reverse second half, merge), Reverse Nodes in k-Group.
- **Hash map of nodes**: Copy List with Random Pointer, LRU Cache (hash map + doubly linked list).

#### Classic problems
Reverse Linked List, Middle of the Linked List, Merge Two Sorted Lists, Linked List Cycle and Cycle II, Remove Nth Node From End, Palindrome Linked List, Intersection of Two Linked Lists, Add Two Numbers, Reorder List, Reverse Nodes in k-Group, LRU Cache.

#### Pitfalls
- Losing the rest of the list by overwriting next before saving it.
- Null pointer access on fast.next.next. Check fast and fast.next.
- Not handling lists of length 0, 1 and 2.

You are ready to move on when you can reverse a list iteratively and recursively and implement LRU Cache with O(1) get and put.

Key concepts: Singly and doubly linked lists, Dummy nodes, Reversal: iterative and recursive, Slow and fast pointers, Floyd's cycle detection, Merging and sorting lists, LRU Cache design.

Mini project: Solve these 10 in 7 days, log time and pattern: Reverse Linked List, Middle of the Linked List, Merge Two Sorted Lists, Linked List Cycle II, Remove Nth Node From End of List, Palindrome Linked List, Add Two Numbers, Reorder List, Copy List with Random Pointer, LRU Cache.

Self-check: After the slow and fast pointers meet inside a cycle, why does moving one pointer back to the head and stepping both by one find the cycle start?

Resources:
- [VisuAlgo: linked lists](https://visualgo.net/en/list) (VisuAlgo)
- [NeetCode roadmap: Linked List](https://neetcode.io/roadmap) (NeetCode)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Stacks and Queues

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/stacks-queues

Use LIFO and FIFO structures for matching brackets, evaluating expressions, simulating processes and designing min-stacks and queues.

Stacks and queues are simple structures that show up as building blocks in many problems and as design questions on their own.

#### Stack patterns
- **Matching**: Valid Parentheses, Minimum Add to Make Parentheses Valid.
- **Expression evaluation**: Evaluate Reverse Polish Notation, infix to postfix conversion, Basic Calculator.
- **Undo and history**: Simplify Path, Backspace String Compare, Decode String.
- **Design**: Min Stack (store pairs of value and current min), Implement Queue using Stacks (amortised O(1)), Implement Stack using Queues.

#### Queue patterns
- BFS (used heavily in trees and graphs).
- Simulation: Number of Recent Calls, Time Needed to Buy Tickets.
- **Deque**: push and pop at both ends; used for sliding window maximum and 0-1 BFS.
- Circular queue implementation with an array and two indices.

#### Pitfalls
- Popping from an empty stack. Always check before popping.
- Using a Java Stack class (synchronised, slow) instead of ArrayDeque.
- Using a Python list as a queue with pop(0).

You are ready to move on when you can implement Min Stack with O(1) getMin and explain the amortised cost of a queue built from two stacks.

Key concepts: Stack and queue operations, Bracket matching, Expression evaluation, Min Stack design, Queue using stacks, Deque, Circular queue.

Mini project: Solve these 10 in 7 days, log time and pattern: Valid Parentheses, Min Stack, Implement Queue using Stacks, Implement Stack using Queues, Evaluate Reverse Polish Notation, Backspace String Compare, Simplify Path, Decode String, Design Circular Queue, Basic Calculator II.

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

Resources:
- [VisuAlgo: stack and queue](https://visualgo.net/en/list) (VisuAlgo)
- [NeetCode roadmap: Stack](https://neetcode.io/roadmap) (NeetCode)
- [takeUforward](https://takeuforward.org/) (takeUforward)

### Monotonic Stack and Deque

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/monotonic-stack

Keep a stack or deque in sorted order to answer next greater, previous smaller and window maximum queries in O(n).

A monotonic stack keeps its elements in increasing or decreasing order. When a new element breaks the order, you pop, and each pop answers a question about the popped element. Every element is pushed and popped once, so the whole pass is O(n).

#### Key patterns
- **Next greater element**: keep a decreasing stack; when a bigger value arrives, it is the answer for everything it pops (Next Greater Element I and II, Daily Temperatures).
- **Previous and next smaller**: the boundaries used by Largest Rectangle in Histogram and Maximal Rectangle.
- **Contribution technique**: count for each element how many subarrays it is the minimum of (Sum of Subarray Minimums).
- **Monotonic deque**: Sliding Window Maximum keeps indices in decreasing value order and drops ones that leave the window.
- **Stock span and asteroid collision**: stack-based simulation.

#### Classic problems
Next Greater Element I, Next Greater Element II (circular, loop 2n), Daily Temperatures, Online Stock Span, Largest Rectangle in Histogram, Maximal Rectangle, Trapping Rain Water (stack version), Sum of Subarray Minimums, Remove K Digits, Asteroid Collision, Sliding Window Maximum.

#### Pitfalls
- Storing values when you need indices (for distances or widths).
- Handling equal values inconsistently in contribution problems, which double counts subarrays. Use strict on one side and non-strict on the other.

You are ready to move on when you can solve Largest Rectangle in Histogram and explain what each pop computes.

Key concepts: Next greater and next smaller, Previous greater and smaller, Storing indices vs values, Histogram problems, Contribution technique, Monotonic deque for windows.

Mini project: Solve these 10 in 7 days, log time and pattern: Next Greater Element I, Next Greater Element II, Daily Temperatures, Online Stock Span, Asteroid Collision, Remove K Digits, Sliding Window Maximum, Largest Rectangle in Histogram, Maximal Rectangle, Sum of Subarray Minimums.

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

Resources:
- [takeUforward stack and queue playlist](https://takeuforward.org/) (takeUforward)
- [NeetCode roadmap: Stack](https://neetcode.io/roadmap) (NeetCode)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

## Trees, BSTs and Heaps

Hierarchical data structures that dominate the middle rounds of product-company interviews: traversals, tree recursion, BST properties and priority queues.

### Binary Tree Traversals

core · beginner · about 7 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/binary-trees

Traverse trees with preorder, inorder, postorder and level order, both recursively and iteratively, and compute basic properties like height.

Trees are recursion in disguise. Almost every tree problem is a traversal plus a small piece of logic at each node.

#### Traversals
- **DFS orders**: preorder (node, left, right), inorder (left, node, right), postorder (left, right, node).
- **Iterative versions** with an explicit stack. Interviewers often ask for iterative inorder.
- **Level order (BFS)** with a queue, processing one level at a time by reading the queue size.
- **Morris traversal**: O(1) extra space inorder, an occasional follow-up.

#### Basic tree recursion
Height (Maximum Depth of Binary Tree), count nodes, Same Tree, Symmetric Tree, Invert Binary Tree, Path Sum. Write each as: handle null, recurse on children, combine.

#### Building trees
Construct Binary Tree from Preorder and Inorder Traversal uses a hash map from value to inorder index. Know why preorder plus inorder (or postorder plus inorder) is enough but preorder plus postorder is not, in general.

#### Classic problems
Binary Tree Inorder Traversal (iterative), Level Order Traversal, Zigzag Level Order, Maximum Depth, Same Tree, Symmetric Tree, Invert Binary Tree, Path Sum, Construct Binary Tree from Preorder and Inorder.

#### Pitfalls
- Forgetting the null base case.
- Mixing up height (edges vs nodes) definitions; ask the interviewer which one they mean.

You are ready to move on when you can write all four traversals iteratively and explain the level-size trick in BFS.

Key concepts: Tree terminology, Preorder, inorder, postorder, Iterative traversals with a stack, Level order with a queue, Construct tree from traversals, Morris traversal.

Mini project: Solve these 10 in 7 days, log time and pattern: Binary Tree Inorder Traversal (iterative), Preorder (iterative), Postorder (iterative), Level Order Traversal, Zigzag Level Order Traversal, Maximum Depth, Same Tree, Symmetric Tree, Invert Binary Tree, Construct Binary Tree from Preorder and Inorder Traversal.

Self-check: How does BFS process exactly one level per outer loop iteration?

Resources:
- [VisuAlgo: binary trees and BST](https://visualgo.net/en/bst) (VisuAlgo)
- [takeUforward tree series](https://takeuforward.org/) (takeUforward)
- [NeetCode roadmap: Trees](https://neetcode.io/roadmap) (NeetCode)

### Tree Problem Patterns

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/tree-patterns

Solve the harder tree questions: diameter, maximum path sum, views, lowest common ancestor, serialisation and distance problems.

Once traversals are automatic, the harder tree problems come from a few recurring ideas.

#### Key patterns
- **Return one thing, update a global**: compute height but update the answer with left + right at each node (Diameter of Binary Tree, Binary Tree Maximum Path Sum, Balanced Binary Tree).
- **Views by level or column**: right side view via BFS, top and bottom view via BFS with horizontal distance and a map, vertical order traversal.
- **Lowest Common Ancestor**: return the node if it is p or q; if both sides return non-null, the current node is the LCA.
- **Root-to-node paths**: path sums with backtracking, Path Sum II, Path Sum III (prefix sums on a tree).
- **Treat the tree as a graph**: store parent pointers and BFS outward (All Nodes Distance K, Minimum time to burn a tree).
- **Serialisation**: Serialize and Deserialize Binary Tree with preorder and null markers.

#### Classic problems
Diameter of Binary Tree, Balanced Binary Tree, Binary Tree Maximum Path Sum, Binary Tree Right Side View, Top View (GfG), Vertical Order Traversal, Lowest Common Ancestor of a Binary Tree, Path Sum III, All Nodes Distance K, Serialize and Deserialize Binary Tree, Maximum Width of Binary Tree.

#### Pitfalls
- In Maximum Path Sum, returning left + right + node upward. Only one branch can be extended to the parent.
- Overflow in Maximum Width when indices double each level; normalise indices per level.

You are ready to move on when you can solve Maximum Path Sum and LCA and explain what each recursive call returns.

Key concepts: Height-based global answers, Diameter and maximum path sum, Left, right, top and bottom views, Lowest common ancestor, Root-to-leaf paths, Parent pointers and distance K, Serialise and deserialise.

Mini project: Solve these 10 in 7 days, log time and pattern: Balanced Binary Tree, Diameter of Binary Tree, Binary Tree Right Side View, Top View of Binary Tree, Vertical Order Traversal, Lowest Common Ancestor of a Binary Tree, Path Sum III, All Nodes Distance K, Binary Tree Maximum Path Sum, Serialize and Deserialize Binary Tree.

Self-check: In Binary Tree Maximum Path Sum, what does the recursive function return to its parent, and what does it record in the global answer?

Resources:
- [takeUforward tree series](https://takeuforward.org/) (takeUforward)
- [cp-algorithms: Lowest Common Ancestor](https://cp-algorithms.com/graph/lca.html) (cp-algorithms)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Binary Search Trees

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/bst

Use the BST ordering property for search, insert, delete, validation, kth smallest and floor and ceiling queries.

A BST keeps every left subtree smaller and every right subtree larger than the node. That property lets you discard half the tree at each step when it is balanced.

#### Operations
- Search, insert and delete in O(h). Delete has three cases: leaf, one child, two children (replace with inorder successor).
- **Inorder traversal of a BST is sorted**. Many problems reduce to this fact.
- Floor and ceiling of a key, inorder successor and predecessor.

#### Key patterns
- **Validate BST** by passing a (min, max) range down, not by comparing only with direct children.
- **Kth Smallest Element**: inorder traversal with a counter.
- **LCA in a BST**: walk down; split point is the answer.
- **Build from sorted array**: pick the middle as root for a balanced tree.
- **Two Sum in a BST**: inorder to array plus two pointers, or a BST iterator from both ends.
- **BST Iterator**: controlled inorder with a stack, O(h) memory.

#### Balanced trees
Know that AVL and red-black trees keep height O(log n) and that C++ set and map, and Java TreeMap, are red-black trees. You will rarely implement one in an interview.

#### Pitfalls
- Checking only node.left.val < node.val, which misses deeper violations.
- Assuming O(log n) on a skewed BST, which is O(n).

You are ready to move on when you can delete a node with two children and validate a BST using ranges.

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

Mini project: Solve these 10 in 7 days, log time and pattern: Search in a BST, Insert into a BST, Delete Node in a BST, Validate Binary Search Tree, Kth Smallest Element in a BST, Lowest Common Ancestor of a BST, Convert Sorted Array to BST, Construct BST from Preorder Traversal, BST Iterator, Two Sum IV - Input is a BST.

Self-check: Give a small tree where every node satisfies left < node < right with its direct children but the tree is not a valid BST.

Resources:
- [VisuAlgo: BST and AVL](https://visualgo.net/en/bst) (VisuAlgo)
- [takeUforward](https://takeuforward.org/) (takeUforward)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Heaps and Priority Queues

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/heaps

Use min-heaps and max-heaps for top-k, k-way merge, scheduling and running median problems.

A heap gives you the smallest (or largest) element in O(1) and insert or remove in O(log n). Whenever a problem keeps asking for "the current best", think heap.

#### How it works
A binary heap is a complete tree stored in an array: children of i are 2i + 1 and 2i + 2. Push sifts up, pop sifts down. Building a heap from n elements takes O(n), not O(n log n).

#### Key patterns
- **Top K**: keep a min-heap of size k for the k largest (Kth Largest Element, Top K Frequent Elements, K Closest Points to Origin). Cost O(n log k).
- **K-way merge**: push the head of each list (Merge k Sorted Lists, Kth Smallest Element in a Sorted Matrix, Find K Pairs with Smallest Sums).
- **Two heaps**: a max-heap for the lower half and a min-heap for the upper half (Find Median from Data Stream).
- **Greedy with a heap**: Task Scheduler, Reorganize String, Minimum Cost to Connect Sticks, IPO, Meeting Rooms II (min-heap of end times).
- Heaps also power Dijkstra and Prim's algorithm in the graph section.

#### Pitfalls
- Using a max-heap of size n for top-k when a min-heap of size k is cheaper.
- Comparator direction confusion: C++ priority_queue is a max-heap by default; Java PriorityQueue and Python heapq are min-heaps.
- Updating an element's priority in place; push a new entry and skip stale ones instead.

You are ready to move on when you can implement a heap with sift-up and sift-down and solve Find Median from Data Stream.

Key concepts: Array representation of a heap, Sift up, sift down, heapify, Top K with a size-k heap, K-way merge, Two heaps for running median, Heap-based greedy scheduling, Lazy deletion.

Mini project: Implement a min-heap class from scratch, then solve these 9 in 7 days, log time and pattern: Kth Largest Element in an Array, Kth Largest Element in a Stream, Top K Frequent Elements, K Closest Points to Origin, Last Stone Weight, Merge k Sorted Lists, Task Scheduler, Meeting Rooms II, Find Median from Data Stream.

Self-check: Why does finding the k largest elements use a min-heap of size k, and what is the time complexity?

Resources:
- [VisuAlgo: binary heap](https://visualgo.net/en/heap) (VisuAlgo)
- [NeetCode roadmap: Heap](https://neetcode.io/roadmap) (NeetCode)
- [Python docs: heapq](https://docs.python.org/3/library/heapq.html) (Python)

## Graphs

Model problems as nodes and edges, then traverse, order, find shortest paths, connect components and build minimum spanning trees.

### Graph Representation, BFS and DFS

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

Store graphs as adjacency lists or grids and use BFS and DFS for connected components, flood fill, cycle detection and bipartite checks.

Graph problems are often hidden: a grid of land and water, a list of course prerequisites, or words that differ by one letter are all graphs.

#### Representation
- **Adjacency list** for sparse graphs (the default). Adjacency matrix only for small, dense graphs.
- **Grids as implicit graphs**: neighbours from direction arrays, no explicit edge list.
- Directed vs undirected, weighted vs unweighted.

#### Traversals
- **DFS** (recursive or stack): connected components, flood fill, cycle detection, path existence.
- **BFS** (queue): shortest path in an **unweighted** graph, level-by-level spread.
- **Multi-source BFS**: start from all sources at once (Rotting Oranges, 01 Matrix).
- Always mark visited when you push, not when you pop, to avoid duplicates in the queue.

#### Common checks
- Cycle in an undirected graph: DFS with parent, or DSU.
- Cycle in a directed graph: DFS with a recursion-stack array, or Kahn's algorithm.
- **Bipartite**: 2-colour with BFS or DFS (Is Graph Bipartite?).

#### Classic problems
Number of Islands, Flood Fill, Max Area of Island, Rotting Oranges, 01 Matrix, Surrounded Regions, Number of Enclaves, Clone Graph, Is Graph Bipartite?, Word Ladder, Number of Provinces.

#### Pitfalls
- Recursion depth on a 1000 x 1000 grid. Use BFS or an iterative DFS.
- Forgetting disconnected components: loop over every node as a start.

You are ready to move on when you can solve Rotting Oranges with multi-source BFS and explain why BFS finds shortest paths only in unweighted graphs.

Key concepts: Adjacency list vs matrix, Grids as graphs, DFS and connected components, BFS and unweighted shortest path, Multi-source BFS, Cycle detection, Bipartite check.

Mini project: Solve these 10 in 7 days, log time and pattern: Flood Fill, Number of Islands, Number of Provinces, Max Area of Island, Rotting Oranges, 01 Matrix, Surrounded Regions, Clone Graph, Is Graph Bipartite?, Word Ladder.

Self-check: Why should you mark a node visited when you push it into the BFS queue rather than when you pop it?

Resources:
- [cp-algorithms: Breadth-first search](https://cp-algorithms.com/graph/breadth-first-search.html) (cp-algorithms)
- [cp-algorithms: Depth-first search](https://cp-algorithms.com/graph/depth-first-search.html) (cp-algorithms)
- [takeUforward graph series](https://takeuforward.org/) (takeUforward)
- [CSES Problem Set: Graph Algorithms](https://cses.fi/problemset/) (CSES)

### Topological Sort

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/topological-sort

Order the nodes of a directed acyclic graph with Kahn's algorithm or DFS, and use it for scheduling and dependency problems.

Topological sort lists the nodes of a **DAG** so that every edge goes from earlier to later. Any problem about prerequisites, build orders or dependencies is probably this.

#### Two algorithms
- **Kahn's algorithm (BFS)**: compute in-degrees, push all zero in-degree nodes, pop and decrement neighbours. If you process fewer than n nodes, there is a cycle.
- **DFS-based**: push a node onto a stack after visiting all its descendants; reverse the finishing order.

#### Key patterns
- Cycle detection in a directed graph (Course Schedule).
- Producing an order (Course Schedule II).
- **Alien Dictionary**: build edges from the first differing character of adjacent words.
- Longest path in a DAG via DP over the topological order.
- **Find Eventual Safe States**: reverse the graph and run Kahn's.
- Parallel scheduling: minimum semesters = number of BFS levels (Parallel Courses).

#### Pitfalls
- In Alien Dictionary, missing the invalid case where a longer word appears before its own prefix.
- Using undirected cycle detection logic on a directed graph.

You are ready to move on when you can implement Kahn's algorithm from memory and use it to detect a cycle.

Key concepts: DAGs and in-degree, Kahn's algorithm, DFS finishing order, Cycle detection in directed graphs, Alien Dictionary, DP on a DAG.

Mini project: Solve these 8 in 7 days, log time and pattern: Course Schedule, Course Schedule II, Find Eventual Safe States, Alien Dictionary, Parallel Courses, Minimum Height Trees, Longest Increasing Path in a Matrix, Course Schedule (CSES).

Self-check: How does Kahn's algorithm tell you that the graph has a cycle?

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

### Shortest Paths

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

Choose between BFS, 0-1 BFS, Dijkstra, Bellman-Ford and Floyd-Warshall based on edge weights and graph size.

Shortest path questions differ only in their edge weights. Pick the algorithm by asking what weights are allowed.

#### Which algorithm
- **Unweighted**: plain BFS, O(V + E).
- **Weights 0 or 1**: 0-1 BFS with a deque (push 0-edges to the front).
- **Non-negative weights**: **Dijkstra** with a min-heap, O((V + E) log V). The workhorse.
- **Negative weights**: **Bellman-Ford**, O(V * E). One more relaxation round that still improves means a negative cycle.
- **All pairs, small V (up to ~400)**: **Floyd-Warshall**, O(V^3).

#### Key patterns
- Dijkstra on a grid where cost is the maximum step (Path With Minimum Effort).
- Dijkstra with extra state, such as stops used (Cheapest Flights Within K Stops, often solved with Bellman-Ford style rounds).
- Counting shortest paths (Number of Ways to Arrive at Destination).
- City with the fewest reachable neighbours within a threshold (Floyd-Warshall).

#### Classic problems
Network Delay Time, Path With Minimum Effort, Cheapest Flights Within K Stops, Shortest Path in Binary Matrix, Number of Ways to Arrive at Destination, Find the City With the Smallest Number of Neighbors, Swim in Rising Water.

#### Pitfalls
- Using Dijkstra with negative edges.
- Not skipping stale heap entries (if the popped distance is larger than the stored one, continue).
- Using int for distances that can exceed 2e9.

You are ready to move on when you can write Dijkstra with a priority queue from memory and say which algorithm to use for any weight pattern.

Key concepts: BFS for unweighted graphs, 0-1 BFS, Dijkstra with a min-heap, Bellman-Ford and negative cycles, Floyd-Warshall, Shortest path with extra state.

Mini project: Solve these 8 in 7 days, log time and pattern: Shortest Path in Binary Matrix, Network Delay Time, Path With Minimum Effort, Cheapest Flights Within K Stops, Number of Ways to Arrive at Destination, Find the City With the Smallest Number of Neighbors at a Threshold Distance, Swim in Rising Water, Shortest Routes I (CSES).

Self-check: Why does Dijkstra fail with negative edge weights? Give a three-node example.

Resources:
- [cp-algorithms: Dijkstra](https://cp-algorithms.com/graph/dijkstra.html) (cp-algorithms)
- [cp-algorithms: Bellman-Ford](https://cp-algorithms.com/graph/bellman_ford.html) (cp-algorithms)
- [cp-algorithms: Floyd-Warshall](https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html) (cp-algorithms)
- [VisuAlgo: SSSP](https://visualgo.net/en/sssp) (VisuAlgo)

### Disjoint Set Union (Union-Find)

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/dsu

Track connected components under merges in near O(1) per operation using path compression and union by rank or size.

DSU answers "are these two elements in the same group?" while groups keep merging. It is simpler than DFS when edges arrive one at a time.

#### Implementation
- parent[i] starts as i. find(x) follows parents to the root.
- **Path compression**: point every visited node directly at the root.
- **Union by rank or size**: attach the smaller tree under the larger.
- With both, operations are almost O(1) (inverse Ackermann).

#### Key patterns
- Number of connected components after a list of edges (Number of Provinces, Number of Operations to Make Network Connected).
- Detect a cycle in an undirected graph: an edge whose endpoints already share a root (Redundant Connection).
- Kruskal's MST (next topic).
- Grouping by shared attributes: Accounts Merge (union emails), Most Stones Removed with Same Row or Column.
- **Online connectivity**: Number of Islands II, where land is added one cell at a time.
- Map grid cells to ids with r * cols + c.

#### Pitfalls
- Comparing parent[a] == parent[b] instead of find(a) == find(b).
- Forgetting to decrement the component count only when a union actually merges two roots.
- Recursion depth in find without path compression on large inputs.

You are ready to move on when you can write DSU with both optimisations in under 15 lines and solve Accounts Merge.

Key concepts: find and union, Path compression, Union by rank or size, Counting components, Cycle detection with DSU, Mapping grid cells and strings to ids.

Mini project: Solve these 7 in 5 days, log time and pattern: Number of Provinces (with DSU), Redundant Connection, Number of Operations to Make Network Connected, Accounts Merge, Most Stones Removed with Same Row or Column, Satisfiability of Equality Equations, Number of Islands II.

Self-check: What goes wrong if you check parent[a] == parent[b] to test whether a and b are connected?

Resources:
- [cp-algorithms: 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)
- [takeUforward graph series](https://takeuforward.org/) (takeUforward)

### Minimum Spanning Trees

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/mst

Connect all nodes at the lowest total cost with Kruskal's (sort edges plus DSU) or Prim's (min-heap) algorithm.

A minimum spanning tree connects all V nodes of a weighted undirected graph with V - 1 edges and the smallest total weight. It appears in OAs as "connect all cities at minimum cost".

#### Kruskal's algorithm
Sort edges by weight. For each edge, add it if its endpoints are in different DSU components. O(E log E). Easy to write once DSU is solid.

#### Prim's algorithm
Grow the tree from one node. Use a min-heap of edges leaving the tree; pop the cheapest edge to an unvisited node. O(E log V). Natural when the graph is given as an adjacency list or is dense (points on a plane).

#### Key ideas
- **Cut property**: the cheapest edge crossing any cut belongs to some MST. This is why both greedy algorithms are correct.
- If the graph is disconnected you get a minimum spanning forest; check that V - 1 edges were added.
- MST also minimises the maximum edge on the path between two nodes, which helps in "minimum bottleneck" questions.

#### Classic problems
Min Cost to Connect All Points, Connecting Cities With Minimum Cost, Minimum Spanning Tree (GfG), Road Reparation (CSES), Find Critical and Pseudo-Critical Edges in MST.

#### Pitfalls
- Applying MST to a directed graph (that needs different algorithms).
- Confusing MST with shortest path trees; they are different.

You are ready to move on when you can implement both Kruskal's and Prim's and explain the cut property in two sentences.

Key concepts: Spanning tree definition, Kruskal's with DSU, Prim's with a min-heap, Cut property, MST vs shortest path tree, Critical edges.

Mini project: Implement Kruskal's and Prim's on the same input and confirm equal totals, then solve: Min Cost to Connect All Points, Connecting Cities With Minimum Cost, Road Reparation (CSES), and Find Critical and Pseudo-Critical Edges in MST. Log time and pattern.

Self-check: Why does Kruskal's algorithm need a DSU, and what would go wrong without one?

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

## Greedy and Dynamic Programming

Make locally optimal choices when they are provably safe, and break overlapping subproblems into states and transitions when they are not.

### Greedy Algorithms

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/greedy

Recognise when a locally best choice leads to a global optimum, and solve interval, scheduling and jump problems greedily.

A greedy algorithm makes the best-looking choice at each step and never revisits it. It is fast and short, but it is only correct when you can argue that the choice is safe.

#### Key patterns
- **Interval scheduling**: sort by end time and take the earliest finishing interval (Non-overlapping Intervals, Minimum Number of Arrows to Burst Balloons, N meetings in one room).
- **Sort and match**: Assign Cookies, Boats to Save People (two pointers after sorting).
- **Reachability**: Jump Game (track furthest reach), Jump Game II (BFS-like levels).
- **Running balance**: Gas Station (restart after a negative tank), Lemonade Change.
- **Exchange argument**: Fractional Knapsack by value per weight, Job Sequencing with deadlines.
- **Two passes**: Candy (left-to-right, then right-to-left).
- Huffman coding uses a heap and greedy merging.

#### Proving it
Use an **exchange argument**: take any optimal solution, swap in your greedy choice, and show the result is no worse. If you cannot argue it, try a small counterexample. Coin change with coins {1, 3, 4} and amount 6 breaks the "largest coin first" greedy, which is why it needs DP.

#### Pitfalls
- Sorting by the wrong key (start time instead of end time in interval scheduling).
- Applying greedy to 0/1 knapsack, which needs DP.

You are ready to move on when you can solve Non-overlapping Intervals and Gas Station and justify each greedy choice in one sentence.

Key concepts: Greedy choice property, Interval scheduling, Jump Game family, Exchange arguments, Fractional knapsack and job sequencing, Counterexamples to greedy, Huffman coding.

Mini project: Solve these 10 in 7 days, log time and pattern: Assign Cookies, Lemonade Change, Jump Game, Jump Game II, Gas Station, Non-overlapping Intervals, Minimum Number of Arrows to Burst Balloons, Boats to Save People, Candy, Job Sequencing Problem (GfG).

Self-check: Give a coin set and amount where picking the largest coin first gives a wrong answer.

Resources:
- [takeUforward greedy series](https://takeuforward.org/) (takeUforward)
- [Competitive Programmer's Handbook (Ch. 6)](https://cses.fi/book/book.pdf) (CSES)
- [NeetCode roadmap: Greedy](https://neetcode.io/roadmap) (NeetCode)

### Dynamic Programming: Foundations and 1D DP

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/dp-1d

Turn recursion into DP with memoisation and tabulation, define states clearly, and solve the classic one-dimensional DP problems.

DP is recursion plus remembering answers to repeated subproblems. Most students fear it because they try to jump straight to a table. Go step by step instead.

#### The four-step method
1. Write the **recursive** solution that tries all choices.
2. Identify the **state**: the parameters that change (usually an index, maybe a remaining capacity).
3. Add **memoisation** (top-down): cache results by state.
4. Convert to **tabulation** (bottom-up), then optimise space if each row depends only on the previous one or two.

#### Classic 1D problems
- Climbing Stairs and Fibonacci: dp[i] = dp[i - 1] + dp[i - 2].
- Frog Jump (with k jumps): minimum cost to reach the end.
- House Robber and House Robber II (circular: solve twice, excluding the first or the last house).
- Decode Ways, Word Break, Coin Change (minimum coins), Coin Change II (number of ways), Perfect Squares.
- Maximum Product Subarray (track both max and min).

#### Defining state well
Say the state in words: "dp[i] = the maximum money robbing houses 0..i". If you cannot say it, the recurrence will be wrong.

#### Pitfalls
- Using 0 as "not computed" in a memo when 0 is a valid answer. Initialise with -1.
- Coin Change II loop order: looping coins outside counts combinations; looping amount outside counts permutations.
- Forgetting the base cases for negative indices.

You are ready to move on when you can take House Robber through all four steps (recursion, memo, table, O(1) space) without help.

Key concepts: Overlapping subproblems, Memoisation (top-down), Tabulation (bottom-up), Space optimisation, Defining the state, Counting vs optimisation DP.

Mini project: Solve these 10 in 7 days, writing recursion, memo and table for each; log time and pattern: Climbing Stairs, Frog Jump (GfG), Min Cost Climbing Stairs, House Robber, House Robber II, Decode Ways, Coin Change, Coin Change II, Word Break, Maximum Product Subarray.

Self-check: In Coin Change II, why does swapping the order of the coin loop and the amount loop change the answer?

Resources:
- [takeUforward DP series](https://takeuforward.org/) (takeUforward)
- [AtCoder Educational DP Contest](https://atcoder.jp/contests/dp) (AtCoder)
- [NeetCode roadmap: 1-D DP](https://neetcode.io/roadmap) (NeetCode)

### 2D DP and DP on Grids

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/dp-2d-grids

Extend DP to two-dimensional states: grid paths, triangle and falling paths, and problems with an extra parameter such as a day or a choice.

Many DP problems need two parameters in the state. Grids are the easiest place to build that skill.

#### Grid DP
- **Unique Paths** and **Unique Paths II** (with obstacles): dp[r][c] = dp[r - 1][c] + dp[r][c - 1].
- **Minimum Path Sum**: take the minimum instead of the sum.
- **Triangle**: start from the bottom row for a cleaner recurrence.
- **Minimum Falling Path Sum**: variable start and end column.
- **Cherry Pickup II**: two walkers moving together, state (row, col1, col2), a 3D DP.
- **Dungeon Game**: solve backwards from the princess.

#### Index plus extra parameter
- Ninja's Training (GfG): state (day, last activity).
- Best Time to Buy and Sell Stock with cooldown, with fee, at most k transactions: state (index, holding or not, transactions left).
- Maximal Square: dp[r][c] = 1 + min of three neighbours.

#### Space optimisation
If row r depends only on row r - 1, keep two rows (or one, with care about overwrite order). Interviewers often ask this as a follow-up.

#### Pitfalls
- Off-by-one when padding the table with an extra row and column.
- Iterating in an order where a cell is read before it is computed.
- Treating a backward problem (Dungeon Game) as forward and getting wrong minimums.

You are ready to move on when you can write Minimum Path Sum with O(cols) space and explain the state in the stock problems in words.

Key concepts: Grid path counting, Minimum path sum and triangle, Variable start and end points, 3D DP with two walkers, Stock buy and sell state machines, Row-wise space optimisation.

Mini project: Solve these 10 in 7 days, log time and pattern: Unique Paths, Unique Paths II, Minimum Path Sum, Triangle, Minimum Falling Path Sum, Maximal Square, Ninja's Training (GfG), Best Time to Buy and Sell Stock with Cooldown, Best Time to Buy and Sell Stock IV, Cherry Pickup II.

Self-check: For Best Time to Buy and Sell Stock IV, what is the state, and how many states are there?

Resources:
- [takeUforward DP series](https://takeuforward.org/) (takeUforward)
- [AtCoder Educational DP Contest](https://atcoder.jp/contests/dp) (AtCoder)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Knapsack and Subset DP

core · intermediate · about 7 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/knapsack-dp

Master 0/1 knapsack, unbounded knapsack and subset-sum variants, the most reused DP template in placement tests.

Knapsack is the template behind a large share of DP questions. Once you see "pick or not pick with a capacity", you know the state is (index, remaining capacity).

#### 0/1 knapsack
dp[i][w] = max(dp[i - 1][w], value[i] + dp[i - 1][w - weight[i]]). Each item is used at most once. With one 1D array, loop capacity **downwards** so an item is not reused.

#### Unbounded knapsack
Items can be reused: dp[i][w] uses dp[i][w - weight[i]] (same row). With a 1D array, loop capacity **upwards**. Coin Change, Rod Cutting and Coin Change II are unbounded knapsacks.

#### Subset-sum family
- Subset Sum Equal to Target (boolean DP).
- Partition Equal Subset Sum: target = total / 2.
- Count subsets with sum k, Partition with given difference (reduce to counting subsets with sum (total + d) / 2).
- Target Sum: the same reduction with plus and minus signs.
- Minimum subset sum difference: fill the subset-sum table, then scan the last row.

#### Pitfalls
- Zeros in the array break count-of-subsets unless the base case handles them.
- Large capacities (1e9) make the table infeasible; look for a different state, like DP over value instead of weight.
- Loop direction mistakes in the 1D version.

You are ready to move on when you can reduce Target Sum to a count-subsets problem and explain why the 1D 0/1 knapsack loops capacity downwards.

Key concepts: 0/1 knapsack, Unbounded knapsack, Subset sum, Partition problems, Counting subsets with a target, 1D space optimisation and loop direction, DP over value for large capacity.

Mini project: Solve these 10 in 7 days, log time and pattern: Subset Sum Problem (GfG), Partition Equal Subset Sum, Partition a Set Into Two Subsets with Minimum Difference, Perfect Sum Problem (GfG), Partitions with Given Difference (GfG), 0/1 Knapsack, Target Sum, Coin Change II, Rod Cutting (GfG), Knapsack 2 (AtCoder DP E).

Self-check: Why does the 1D array version of 0/1 knapsack iterate capacity from high to low, while unbounded knapsack iterates low to high?

Resources:
- [AtCoder Educational DP Contest](https://atcoder.jp/contests/dp) (AtCoder)
- [takeUforward DP series](https://takeuforward.org/) (takeUforward)
- [USACO Guide: Knapsack DP](https://usaco.guide/) (USACO Guide)

### DP on Subsequences and Strings: LIS, LCS, Edit Distance

core · advanced · about 9 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/dp-sequences

Solve the classic sequence DPs: longest increasing subsequence, longest common subsequence and its variants, edit distance and wildcard matching.

Sequence DPs compare positions in one or two arrays or strings. They are the most asked DP problems in product-company interviews.

#### Longest Increasing Subsequence
- O(n^2) DP: dp[i] = 1 + max dp[j] for j < i with a[j] < a[i].
- O(n log n): keep tails[] where tails[k] is the smallest tail of an increasing subsequence of length k + 1; binary search each element into it.
- Variants: Number of LIS, Largest Divisible Subset, Russian Doll Envelopes (sort cleverly, then LIS), Longest String Chain, Longest Bitonic Subsequence.

#### Two-string DP, state (i, j)
- **Longest Common Subsequence**: match then 1 + dp[i - 1][j - 1], else max of skipping one side.
- From LCS: Longest Palindromic Subsequence (LCS with the reverse), minimum insertions to make a palindrome, Shortest Common Supersequence, Delete Operation for Two Strings.
- Longest Common Substring: reset to 0 on mismatch.
- **Edit Distance**: insert, delete, replace.
- Distinct Subsequences, Wildcard Matching, Regular Expression Matching.

#### Pitfalls
- Confusing subsequence (gaps allowed) with substring (contiguous).
- Index shifting: using 1-based dp with 0-based strings and reading s[i] instead of s[i - 1].
- Printing the actual LCS needs a backtrack through the table, a common follow-up.

You are ready to move on when you can solve Edit Distance and LIS in O(n log n) and print the actual LCS string, not just its length.

Key concepts: LIS in O(n^2), LIS in O(n log n), LCS and printing it, Longest palindromic subsequence, Edit distance, Distinct subsequences, Wildcard and regex matching, Subsequence vs substring.

Mini project: Solve these 10 in 7 days, log time and pattern: Longest Increasing Subsequence (both methods), Number of Longest Increasing Subsequence, Largest Divisible Subset, Russian Doll Envelopes, Longest Common Subsequence (print it too), Longest Palindromic Subsequence, Shortest Common Supersequence, Edit Distance, Distinct Subsequences, Wildcard Matching.

Self-check: In the O(n log n) LIS method, is the tails array itself a valid increasing subsequence? Why or why not?

Resources:
- [takeUforward DP series](https://takeuforward.org/) (takeUforward)
- [cp-algorithms: Longest increasing subsequence](https://cp-algorithms.com/sequences/longest_increasing_subsequence.html) (cp-algorithms)
- [NeetCode roadmap: 2-D DP](https://neetcode.io/roadmap) (NeetCode)

### Interval DP, DP on Trees and Bitmask DP

recommended · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/advanced-dp

Handle the harder DP families that appear in top product-company rounds: partition and interval DP, DP on trees and bitmask DP.

These families separate strong candidates in top product-company interviews. Learn them after the classic DPs feel easy.

#### Interval (partition) DP
State is a range (i, j); try every split point k inside it. Usually O(n^3).
- Matrix Chain Multiplication (the template).
- Minimum Cost to Cut a Stick, Burst Balloons (think of the last balloon burst), Palindrome Partitioning II, Boolean Parenthesization (Evaluate expression to true), Partition Array for Maximum Sum.

#### DP on trees
Compute answers bottom-up with DFS, often returning a pair (take node, skip node).
- House Robber III, Binary Tree Cameras, Maximum Path Sum (revisited), tree diameter.
- **Rerooting**: compute an answer for every node as root in O(n) (Sum of Distances in Tree).

#### DP on grids, revisited
Longest Increasing Path in a Matrix is DFS plus memo on a grid with no fixed direction.

#### Bitmask DP
When n is up to about 20, a mask can represent the set of chosen items.
- Travelling Salesman (dp[mask][last]), Shortest Path Visiting All Nodes (BFS over (node, mask)), Partition to K Equal Sum Subsets, assignment problems.

#### Pitfalls
- In Burst Balloons, choosing the first balloon to burst instead of the last makes subproblems dependent.
- Memory blow-up in bitmask DP: 2^20 x 20 ints is about 80 MB.

You are ready to move on when you can write Matrix Chain Multiplication from the recurrence and explain why Burst Balloons picks the last balloon.

Key concepts: Matrix chain multiplication, Partition DP over ranges, Burst Balloons, DP on trees, Rerooting, Memoised DFS on grids, Bitmask DP.

Mini project: Solve these 8 in 10 days, log time and pattern: Matrix Chain Multiplication (GfG), Minimum Cost to Cut a Stick, Palindrome Partitioning II, Burst Balloons, Partition Array for Maximum Sum, House Robber III, Longest Increasing Path in a Matrix, Shortest Path Visiting All Nodes.

Self-check: What is the state and transition for Matrix Chain Multiplication, and what is its time complexity?

Resources:
- [takeUforward DP series](https://takeuforward.org/) (takeUforward)
- [AtCoder Educational DP Contest](https://atcoder.jp/contests/dp) (AtCoder)
- [USACO Guide](https://usaco.guide/) (USACO Guide)

## Tries, Bits, Maths and Range Queries

Specialised tools that show up regularly in OAs: prefix trees, bit tricks, number theory basics, and segment trees for those aiming at top companies.

### Tries

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/tries

Store strings in a prefix tree for fast prefix search, autocomplete and word games, and use binary tries for maximum XOR problems.

A trie stores strings character by character so that common prefixes share nodes. Insert and search take O(length of word), independent of how many words are stored.

#### Implementation
Each node holds up to 26 children (array or map) and an end-of-word flag. Add counters (prefix count, end count) to support counting and deletion.

#### Key patterns
- Implement Trie (insert, search, startsWith).
- Autocomplete and Search Suggestions System.
- **Word Search II**: build a trie of words and DFS the grid once, pruning dead prefixes.
- Longest Word in Dictionary, Replace Words, Count distinct substrings (insert all suffixes).
- **Binary trie for XOR**: insert numbers bit by bit from the most significant bit; for each query, greedily go to the opposite bit (Maximum XOR of Two Numbers in an Array, Maximum XOR With an Element From Array).

#### Pitfalls
- Memory: 26 pointers per node times total characters can be large. Use a map per node if the alphabet is big or sparse.
- Forgetting the end-of-word flag, so "app" is reported present after inserting only "apple".
- In Word Search II, not removing found words, causing duplicates and TLE.

You are ready to move on when you can implement a trie with prefix counts and solve Maximum XOR of Two Numbers with a binary trie.

Key concepts: Trie node structure, Insert, search, startsWith, Prefix and end counters, Trie plus DFS on a grid, Binary trie for maximum XOR, Map vs array children.

Mini project: Implement a trie class with insert, search, startsWith, countWordsEqualTo and erase, then solve: Implement Trie (Prefix Tree),Longest Word in Dictionary, Replace Words, Search Suggestions System, Word Search II, Maximum XOR of Two Numbers in an Array. Log time and pattern.

Self-check: Why is a trie faster than a hash set for 'does any stored word start with this prefix?' queries?

Resources:
- [takeUforward trie series](https://takeuforward.org/) (takeUforward)
- [NeetCode roadmap: Tries](https://neetcode.io/roadmap) (NeetCode)
- [LeetCode problem set](https://leetcode.com/problemset/) (LeetCode)

### Bit Manipulation

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/bit-manipulation

Use binary operators to check, set and clear bits, solve XOR puzzles and enumerate subsets with masks.

Bit manipulation questions are short and come up often in service-company technical rounds and as OA warm-ups.

#### Operators and tricks
- AND, OR, XOR, NOT, left and right shifts.
- Check bit i: (n >> i) & 1. Set: n | (1 << i). Clear: n & ~(1 << i). Toggle: n ^ (1 << i).
- n & (n - 1) clears the lowest set bit: power of two check and counting set bits (Brian Kernighan).
- n & (-n) isolates the lowest set bit.
- XOR properties: a ^ a = 0, a ^ 0 = a, order does not matter.

#### Classic problems
Single Number (XOR all), Single Number II (count bits mod 3), Single Number III (split by a differing bit), Number of 1 Bits, Counting Bits (dp[i] = dp[i >> 1] + (i & 1)), Power of Two, Missing Number, Reverse Bits, Sum of Two Integers without +, Subsets via masks from 0 to 2^n - 1, XOR of numbers from 1 to n (pattern repeats every 4).

#### Number representation
Know two's complement, why ~n = -n - 1, and that signed right shift copies the sign bit. These come up in viva-style questions.

#### Pitfalls
- Operator precedence: in C++ and Java, == binds tighter than &, so write (n & 1) == 0 with brackets.
- 1 << 31 overflows a 32-bit int; use 1LL << i for long values.

You are ready to move on when you can solve Single Number III and explain how n & (n - 1) counts set bits.

Key concepts: Bitwise operators and shifts, Check, set, clear, toggle a bit, n & (n - 1) tricks, XOR properties, Subsets with bitmasks, Two's complement.

Mini project: Solve these 10 in 5 days, log time and pattern: Number of 1 Bits, Counting Bits, Power of Two, Missing Number, Single Number, Single Number II, Single Number III, Reverse Bits, Subsets (with bitmasks), Sum of Two Integers.

Self-check: Why does XOR-ing every element of an array find the one element that appears once when all others appear twice?

Resources:
- [cp-algorithms: 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)
- [takeUforward](https://takeuforward.org/) (takeUforward)

### Maths for Coding Rounds

recommended · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/math-for-dsa

Cover the number theory that OAs keep reusing: GCD, primes and sieve, modular arithmetic, fast exponentiation and basic combinatorics.

Many OA problems hide a little maths. You do not need olympiad level, just a reliable toolkit.

#### The toolkit
- **GCD and LCM**: Euclid's algorithm, lcm(a, b) = a / gcd(a, b) * b (divide first to avoid overflow).
- **Primes**: trial division up to sqrt(n); **Sieve of Eratosthenes** for all primes up to 1e6 or 1e7; smallest prime factor sieve for fast factorisation.
- **Divisors**: enumerate up to sqrt(n) in pairs.
- **Modular arithmetic**: answers "modulo 1e9 + 7"; add, subtract and multiply under mod; subtract carefully to avoid negatives.
- **Fast exponentiation**: a^b mod m in O(log b).
- **Modular inverse** with Fermat's little theorem when m is prime: a^(m - 2) mod m.
- **Combinatorics**: nCr with precomputed factorials and inverse factorials, Pascal's triangle for small n.
- Digit tricks: reverse a number, check palindrome number, Armstrong numbers (common in service-company tests).

#### Classic problems
Count Primes, Pow(x, n), GCD of an array, Prime Factorization using Sieve, Pascal's Triangle, Excel Sheet Column Number, Count Good Numbers, Exponentiation (CSES), Binomial Coefficients (CSES).

#### Pitfalls
- Overflow before taking mod: multiply in 64-bit, then mod.
- Taking mod of a subtraction and getting a negative number.

You are ready to move on when you can write a sieve, binary exponentiation and nCr mod p from memory.

Key concepts: GCD, LCM and Euclid, Sieve of Eratosthenes, Prime factorisation, Modular arithmetic, Binary exponentiation, Modular inverse, nCr with factorials.

Mini project: Build a personal maths template (gcd, sieve, spf factorisation, power mod, inverse, nCr) and solve: Count Primes, Pow(x, n), Pascal's Triangle, Count Good Numbers, Exponentiation (CSES), Counting Divisors (CSES), Binomial Coefficients (CSES). Log time and pattern.

Self-check: Why do you compute lcm as a / gcd(a, b) * b instead of a * b / gcd(a, b)?

Resources:
- [cp-algorithms: Sieve of Eratosthenes](https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html) (cp-algorithms)
- [cp-algorithms: Binary exponentiation](https://cp-algorithms.com/algebra/binary-exp.html) (cp-algorithms)
- [CSES Problem Set: Mathematics](https://cses.fi/problemset/) (CSES)

### Segment Trees and Fenwick Trees

optional · advanced · about 7 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/segment-tree-fenwick

Answer range queries with point or range updates in O(log n): advanced, but useful for competitive programming and top-tier OAs.

Prefix sums break as soon as values change. Segment trees and Fenwick trees support both updates and range queries in O(log n). They are rarely asked in normal interviews but appear in harder OAs and contests.

#### Fenwick tree (Binary Indexed Tree)
- Supports point update and prefix sum in O(log n) with very short code using i & (-i).
- Range sum = prefix(r) - prefix(l - 1).
- Also counts inversions and "count of smaller numbers after self" with coordinate compression.

#### Segment tree
- Each node stores an answer (sum, min, max, gcd) for a range; size about 4n.
- Build in O(n), query and point update in O(log n).
- **Lazy propagation** handles range updates (add v to all of [l, r]) in O(log n).

#### When to use what
- Static array, many range sums: prefix sums.
- Updates plus sum queries: Fenwick tree.
- Updates plus min, max or custom merges, or range updates: segment tree.

#### Classic problems
Range Sum Query - Mutable, Count of Smaller Numbers After Self, Count Inversions (BIT version), Dynamic Range Sum Queries and Dynamic Range Minimum Queries (CSES), Range Update Queries (CSES).

#### Pitfalls
- Fenwick trees are 1-indexed; an index of 0 loops forever.
- Forgetting to push lazy values down before recursing.

You are ready to move on when you can implement a segment tree for range minimum with point updates and explain when a Fenwick tree is enough.

Key concepts: Fenwick tree point update and prefix query, Segment tree build, query, update, Custom merge functions, Lazy propagation, Coordinate compression, Sparse table for static RMQ.

Mini project: Implement a Fenwick tree and a segment tree (with lazy propagation) as reusable templates, then solve: Range Sum Query - Mutable, Count of Smaller Numbers After Self, Dynamic Range Sum Queries (CSES), Dynamic Range Minimum Queries (CSES), Range Update Queries (CSES). Log time and pattern.

Self-check: Why does a segment tree need about 4n nodes, and what does lazy propagation postpone?

Resources:
- [cp-algorithms: Segment tree](https://cp-algorithms.com/data_structures/segment_tree.html) (cp-algorithms)
- [cp-algorithms: Fenwick tree](https://cp-algorithms.com/data_structures/fenwick.html) (cp-algorithms)
- [Codeforces EDU: Segment Tree](https://codeforces.com/edu/courses) (Codeforces)

## Problem Solving and How to Practise

Turn topic knowledge into speed and accuracy: a repeatable approach to new problems, a sheet with spaced revision, and regular timed contests.

### A Repeatable Approach to New Problems

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/problem-solving-framework

Follow a fixed routine for unseen problems: understand, find examples, brute force, map to a pattern, optimise, code, then test edge cases.

The goal of practice is not to memorise 500 solutions. It is to reliably solve a problem you have never seen. A fixed routine makes that possible under pressure.

#### The routine
1. **Restate** the problem and confirm input sizes, value ranges and edge cases.
2. Work **two or three examples by hand**, including a tricky one.
3. State a **brute force** and its complexity, even if it is too slow.
4. Use the constraints to pick a target complexity, then **map to a pattern**: sorted input suggests two pointers or binary search; contiguous range suggests sliding window or prefix sums; "all combinations" suggests backtracking; "minimum or maximum ways" with overlapping choices suggests DP; dependencies suggest graphs.
5. Write the code in small, named pieces.
6. **Dry-run** on your examples, then test empty input, single element, duplicates, negatives and maximum sizes.

#### When you are stuck
Give yourself 20 to 30 minutes on a medium problem. Then read only the hint or the pattern name, try again, and only then read the full solution. Re-solve it from scratch the next day.

#### Pattern recognition cues
Build a personal cue sheet: "k-th largest means heap", "minimise the maximum means binary search on answer", "next greater means monotonic stack". Add a line every time a problem surprises you.

#### Pitfalls
- Jumping into code before you have an approach.
- Reading the solution after five minutes, which trains recognition, not problem solving.

You are ready to move on when you can talk through steps 1 to 4 aloud on a new medium problem within 10 minutes.

Key concepts: Clarifying constraints and edge cases, Brute force first, Constraint-driven pattern choice, Dry runs and test cases, The 20-30 minute stuck rule, Personal pattern cue sheet.

Mini project: Pick 6 unseen medium problems from mixed topics. For each, write the six routine steps in a notebook before coding, time each step, and note which cue led you to the pattern.

Self-check: A problem asks for the minimum possible largest sum when splitting an array into k parts with n up to 1e5. Which pattern do the words and constraints point to?

Resources:
- [Tech Interview Handbook: coding interview](https://www.techinterviewhandbook.org/) (Tech Interview Handbook)
- [NeetCode roadmap](https://neetcode.io/roadmap) (NeetCode)
- [USACO Guide](https://usaco.guide/) (USACO Guide)

### DSA Sheets, Logs and Spaced Repetition

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/sheets-and-revision

Follow one curated sheet end to end, log every problem, and revisit them on a spaced schedule so patterns stick until interview day.

Most students solve problems and forget them in three weeks. A simple system fixes that.

#### Pick one sheet and finish it
Popular choices: **Striver's A2Z or SDE sheet** (takeUforward), **NeetCode 150**, **Blind 75**, **Love Babbar 450**, and LeetCode study plans. They overlap heavily, so choose one and finish it rather than hopping between several. Blind 75 or NeetCode 150 suit a short timeline; A2Z suits a 4 to 6 month runway.

#### Keep a problem log
A spreadsheet with: problem, link, pattern, difficulty, date, time taken, solved alone or with hint, and a one-line key insight. The insight line is what you revise.

#### Spaced repetition
Re-solve problems after about 3 days, 1 week, 3 weeks and 2 months. Mark each attempt as clean, slow or failed; failed ones go back to the start of the schedule. Anki or a filter in your spreadsheet works fine.

#### Volume and balance
Around 250 to 350 well-understood problems is enough for most product-company roles. Aim for a mix of roughly 30 percent easy, 55 percent medium and 15 percent hard. Quality of review beats raw count.

#### Pitfalls
- Counting problems solved as progress while never revisiting any.
- Chasing streaks with easy problems you already know.
- Copying solutions into the log without your own insight line.

You are ready to move on when you have a log with at least 50 entries and can re-solve a random 10 of them cleanly in one sitting.

Key concepts: Choosing one sheet, Problem log spreadsheet, Spaced repetition schedule, Easy, medium, hard balance, Anki for pattern cards.

Mini project: Set up a problem log spreadsheet with the columns above and a revision-date formula. Log the last 30 problems you solved, then do your first revision session of 10 problems and record clean, slow or failed.

Self-check: What should a log entry contain so that reading it later helps you re-solve the problem quickly?

Resources:
- [takeUforward: Striver's sheets](https://takeuforward.org/) (takeUforward)
- [NeetCode practice](https://neetcode.io/practice) (NeetCode)
- [AnkiWeb](https://ankiweb.net/) (Anki)

### Contests on LeetCode, Codeforces and CodeChef

recommended · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/contests

Use weekly timed contests to build speed, handle pressure, and gain a rating that strengthens a fresher resume.

OAs are timed contests in disguise. Regular contests are the best rehearsal you can get.

#### Where to compete
- **LeetCode** weekly (Sunday morning IST) and biweekly contests: interview-style problems, closest to product-company OAs.
- **Codeforces** Div 2, Div 3 and Div 4 rounds: harder thinking, strong for maths and greedy.
- **CodeChef** Starters (weekly, Wednesday evening IST): India-focused, divisions by rating.
- **AtCoder** Beginner Contests: clean, educational problems.
Use clist.by to see every upcoming contest in one calendar.

#### How to use contests well
- Compete live at least once a week, no matter how badly it goes.
- **Upsolve** every problem you could not finish within two days. This is where most learning happens.
- Track rating trends, not single results.

#### Ratings and the resume
A LeetCode rating of about 1800 or more (Knight), a Codeforces Specialist or Expert, or CodeChef 3 star and above is a credible signal on a fresher resume. Some companies shortlist directly from hiring contests such as TCS CodeVita and CodeChef or LeetCode sponsored rounds.

#### Pitfalls
- Skipping contests because of a fear of a low rating.
- Never upsolving, so the same gaps keep showing up.
- Using contest-specific macros and tricks in interviews, where readable code matters.

You are ready to move on when you have done 8 contests in a row and upsolved at least one extra problem from each.

Key concepts: LeetCode weekly and biweekly, Codeforces Div 2, 3, 4, CodeChef Starters, AtCoder Beginner Contests, Upsolving, Ratings on the resume.

Mini project: Take part in 4 consecutive weekly contests on one platform. After each, upsolve the next unsolved problem and write a short post-mortem: what slowed you down, which pattern you missed, and one thing to change next week.

Self-check: Why is upsolving after a contest more valuable than the contest itself?

Resources:
- [LeetCode contests](https://leetcode.com/contest/) (LeetCode)
- [Codeforces contests](https://codeforces.com/contests) (Codeforces)
- [CodeChef contests](https://www.codechef.com/contests) (CodeChef)
- [clist.by contest calendar](https://clist.by/) (clist)

## Aptitude: Quantitative, Logical and Verbal

The first filter in almost every mass-recruiter test and many product-company OAs: arithmetic speed, reasoning puzzles and English skills.

### Quantitative Aptitude: Arithmetic

core · beginner · about 12 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/quant-arithmetic

Build speed in percentages, ratios, profit and loss, interest, averages, time and work, and time, speed and distance.

Arithmetic topics make up most of the quant section in TCS, Infosys, Wipro, Accenture and Capgemini tests. They reward speed more than cleverness.

#### High-frequency topics
- **Percentages**: successive change (a + b + ab/100), percentage to fraction table (12.5 percent = 1/8).
- **Profit, loss and discount**: marked price, successive discounts, dishonest dealer questions.
- **Ratio, proportion and partnership**.
- **Averages** and **mixtures and alligation**.
- **Simple and compound interest**: CI for 2 and 3 years, difference between CI and SI.
- **Time and work**: work rates as fractions or the LCM method, pipes and cisterns.
- **Time, speed and distance**: relative speed, trains, boats and streams, average speed (2xy / (x + y)).
- Ages and number series.

#### Speed habits
- Memorise squares up to 30, cubes up to 15, and fractions up to 1/20 as percentages.
- Use the LCM method for work problems instead of fractions.
- Eliminate options using units digits or rough estimates.

#### Pitfalls
- Spending three minutes on one question in a 25-question, 40-minute section. Skip and return.
- Ignoring negative marking rules; most mass-recruiter tests have none, so never leave a question blank.

You are ready to move on when you can solve 20 mixed arithmetic questions in 25 minutes with at least 80 percent accuracy.

Key concepts: Percentages and successive change, Profit, loss and discount, Ratio, proportion, partnership, Averages, mixtures, alligation, Simple and compound interest, Time and work, pipes and cisterns, Time, speed, distance, trains, boats, Mental maths tables.

Mini project: For 14 days, do one timed 20-question arithmetic set daily from IndiaBix or PrepInsta. Log score, time and the topic of every wrong answer, and redo the weakest topic on the weekend.

Self-check: A can finish a job in 12 days and B in 18 days. Using the LCM method, how many days do they take together?

Resources:
- [IndiaBix: Aptitude questions](https://www.indiabix.com/aptitude/questions-and-answers/) (IndiaBix)
- [PrepInsta: quants](https://prepinsta.com/) (PrepInsta)
- [Khan Academy: Arithmetic](https://www.khanacademy.org/math/arithmetic) (Khan Academy)

### Quantitative Aptitude: Numbers, Probability and Data Interpretation

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/quant-advanced

Cover number systems, permutations and combinations, probability, and data interpretation from tables and charts.

The second half of the quant syllabus has fewer formulas but trickier questions. These separate high scorers, especially in TCS Digital, Infosys and product-company aptitude rounds.

#### Number system
Divisibility rules, HCF and LCM word problems, remainders (cyclicity of unit digits, remainder theorem), factors and trailing zeroes in n! (divide by 5, 25, 125 and add).

#### Permutations, combinations and probability
- nPr and nCr, arrangements with repeated letters (n! divided by repeats), circular arrangements ((n - 1)!), selections with restrictions.
- Probability with coins, dice and cards; "at least one" = 1 - P(none); independent vs dependent events; basic conditional probability.

#### Data interpretation
Tables, bar charts, line graphs and pie charts with 4 to 5 questions on one data set. Approximate aggressively and calculate only what the options require.

#### Also seen
Clocks (angle = |30H - 5.5M|), calendars (odd days), mensuration basics (areas, volumes), and simple algebra and inequalities.

#### Pitfalls
- Counting arrangements when the question asks for selections.
- Exact calculations in DI when options are far apart.

You are ready to move on when you can solve a 5-question DI set in 7 minutes and explain why "at least one" questions use the complement.

Key concepts: Number system and remainders, Trailing zeroes and factors, Permutations and combinations, Probability, Data interpretation, Clocks and calendars, Mensuration basics.

Mini project: Over 10 days, complete 5 timed DI sets, 50 P&C and probability questions and 30 number system questions. Track accuracy per topic and make a one-page formula sheet from your mistakes.

Self-check: How many trailing zeroes does 100! have, and what is the method?

Resources:
- [IndiaBix: Aptitude questions](https://www.indiabix.com/aptitude/questions-and-answers/) (IndiaBix)
- [IndiaBix: Data Interpretation](https://www.indiabix.com/data-interpretation/questions-and-answers/) (IndiaBix)
- [Math is Fun: Probability](https://www.mathsisfun.com/data/probability.html) (Math is Fun)

### Logical Reasoning

core · beginner · about 10 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/logical-reasoning

Solve seating arrangements, puzzles, blood relations, syllogisms, coding-decoding, series and directions quickly and accurately.

Logical reasoning is a separate section in TCS NQT, Infosys, Accenture, Cognizant and Capgemini tests, and puzzle-style questions also appear in product-company interviews.

#### High-frequency topics
- **Seating and arrangements**: linear and circular, facing in or out. Draw the diagram and fix the most constrained person first.
- **Puzzles**: floor, box and scheduling puzzles with a grid of attributes.
- **Blood relations**: draw a family tree with symbols for gender.
- **Syllogisms**: Venn diagrams; check every possible case before marking "definitely follows".
- **Coding-decoding**: letter shifts, reversed positions (A = 1 and Z = 26, A and Z as opposites).
- **Number and letter series**, odd one out, analogies.
- **Direction sense**: track turns and use Pythagoras for the final distance.
- **Data sufficiency**, statement and assumptions, cause and effect.
- Non-verbal reasoning: pattern completion, mirror and water images (Accenture and Cognizant often include these).

#### Interview puzzles
Product companies sometimes ask classic puzzles: 25 horses and 5 tracks, the two-egg drop, measuring water with two jugs, the burning ropes. Practise explaining your reasoning out loud.

#### Pitfalls
- Solving arrangements in your head instead of drawing them.
- Treating "possibility" questions in syllogisms like "definite" ones.

You are ready to move on when you can solve a 5-question seating arrangement set in 8 minutes and a mixed 15-question reasoning set with 80 percent accuracy.

Key concepts: Seating arrangements, Grid puzzles, Blood relations, Syllogisms, Coding-decoding, Series and analogies, Direction sense, Non-verbal reasoning, Classic interview puzzles.

Mini project: For 10 days, solve one arrangement or puzzle set and 15 mixed reasoning questions daily under time. Keep a mistakes log by topic and solve 5 classic interview puzzles aloud, recording yourself once.

Self-check: All roses are flowers. Some flowers are red. Does 'some roses are red' definitely follow? Draw the Venn diagram to justify.

Resources:
- [IndiaBix: Logical Reasoning](https://www.indiabix.com/logical-reasoning/questions-and-answers/) (IndiaBix)
- [IndiaBix: Verbal Reasoning](https://www.indiabix.com/verbal-reasoning/questions-and-answers/) (IndiaBix)
- [PrepInsta: logical reasoning](https://prepinsta.com/) (PrepInsta)

### Verbal Ability and Communication

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/verbal-ability

Score well on reading comprehension, grammar, vocabulary and sentence questions, and prepare for email writing and communication tests.

Verbal sections are often the easiest marks to gain and the most commonly neglected. Some companies also run separate communication assessments.

#### What gets tested
- **Reading comprehension**: 1 to 3 passages with inference, main idea and tone questions. Read the questions first, then the passage.
- **Grammar**: error spotting, sentence correction, subject-verb agreement, tenses, articles, prepositions.
- **Vocabulary**: synonyms, antonyms, fill in the blanks, contextual meaning.
- **Sentence arrangement** (para jumbles): find the opening sentence and linked pairs.
- **Email writing** (TCS and Accenture have used this): a short professional email using given phrases.
- **Spoken English tests** (for example in Accenture and some BPO-linked roles): reading aloud, repeating sentences, listening comprehension.

#### How to improve in weeks, not months
- Read one quality editorial or long-form article daily and summarise it in three lines.
- Learn grammar rules from your own mistakes, not from a full grammar book.
- Keep a vocabulary list of words met in context, about 10 a day.

#### Pitfalls
- Choosing answers in RC from outside knowledge instead of the passage.
- Informal tone, missing subject lines or no closing in email writing tasks.

You are ready to move on when you can finish a 20-question verbal set in 20 minutes with 80 percent accuracy and write a clear 120-word professional email in 10 minutes.

Key concepts: Reading comprehension, Error spotting and sentence correction, Synonyms, antonyms, fill in the blanks, Para jumbles, Professional email writing, Spoken English assessments.

Mini project: For 14 days: read one editorial and write a 3-line summary, do 15 verbal questions under time, and add 10 words to a vocabulary list. On days 7 and 14, write a timed professional email and review it against a checklist (subject, greeting, purpose, closing).

Self-check: In a reading comprehension question, why is the option that is true in real life sometimes the wrong answer?

Resources:
- [IndiaBix: Verbal Ability](https://www.indiabix.com/verbal-ability/questions-and-answers/) (IndiaBix)
- [Purdue OWL: grammar and writing](https://owl.purdue.edu/owl/purdue_owl.html) (Purdue University)
- [Vocabulary.com](https://www.vocabulary.com/) (Vocabulary.com)

## CS Core Subjects for Interviews

The theory rounds every fresher faces: OOP, DBMS and SQL, operating systems and computer networks, at the depth interviewers actually ask.

### Object-Oriented Programming

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/oop

Explain and apply encapsulation, abstraction, inheritance and polymorphism with code, plus the OOP questions asked in almost every fresher interview.

OOP is the most asked theory topic in fresher interviews, especially at service companies. Expect definitions, small code examples and "what is the output" questions in your chosen language.

#### The four pillars
- **Encapsulation**: bundle data with methods and hide it behind access modifiers (private, protected, public).
- **Abstraction**: expose what an object does, hide how. Abstract classes and interfaces.
- **Inheritance**: reuse and extend behaviour. Types: single, multilevel, hierarchical, multiple (via interfaces in Java), and the diamond problem (virtual inheritance in C++).
- **Polymorphism**: compile-time (method overloading, operator overloading in C++) and runtime (method overriding through virtual functions or dynamic dispatch).

#### Frequently asked questions
- Class vs object, constructor types (default, parameterised, copy), destructors.
- Abstract class vs interface, and when to use each.
- Overloading vs overriding.
- static and final (Java), virtual functions and vtables (C++), this and super.
- Composition vs inheritance; "has-a" vs "is-a".
- Shallow vs deep copy.
- A short intro to **SOLID** principles and one or two design patterns (Singleton, Factory, Observer) for product-company rounds.

#### Pitfalls
- Reciting textbook definitions without a code example. Always back each pillar with a 3 to 5 line snippet.
- Confusing abstraction with encapsulation.

You are ready to move on when you can explain all four pillars with your own code examples and answer overloading vs overriding with output prediction.

Key concepts: Classes, objects, constructors, Encapsulation and access modifiers, Abstraction: abstract classes and interfaces, Inheritance types and diamond problem, Overloading vs overriding, Virtual functions and dynamic dispatch, Composition vs inheritance, SOLID and common design patterns.

Mini project: Build a small console Library Management system in your language with Book, Member and Librarian classes, an abstract LibraryItem, an interface for borrowable items, overloading and overriding examples, and a README mapping each OOP pillar to a line of code.

Self-check: What is the difference between an abstract class and an interface, and when would you choose each?

Resources:
- [Oracle Java Tutorials: OOP concepts](https://docs.oracle.com/javase/tutorial/java/concepts/) (Oracle)
- [Refactoring.Guru: design patterns](https://refactoring.guru/design-patterns) (Refactoring.Guru)
- [LearnCpp.com](https://www.learncpp.com/) (LearnCpp)

### DBMS Concepts

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/dbms

Cover keys, ER models, normalisation, transactions and ACID, concurrency control and indexing at interview depth.

DBMS questions appear in nearly every technical interview for freshers. Interviewers want clear definitions plus one example each.

#### Core concepts
- **Keys**: super, candidate, primary, alternate, foreign and composite keys.
- **ER model**: entities, attributes, relationships, cardinality (1:1, 1:N, M:N) and converting ER diagrams to tables.
- **Normalisation**: 1NF, 2NF, 3NF and BCNF, with functional dependencies; explain the anomalies (insert, update, delete) each one removes. Know when denormalisation helps reads.
- **Transactions and ACID**: atomicity, consistency, isolation, durability with a bank transfer example.
- **Concurrency**: dirty read, non-repeatable read, phantom read; isolation levels; locking and two-phase locking; deadlocks in databases.
- **Indexing**: why B+ trees, clustered vs non-clustered indexes, when an index is not used.
- SQL vs NoSQL at a high level, and the CAP theorem in one paragraph.

#### Pitfalls
- Defining 2NF and 3NF without a concrete example table.
- Saying "indexes make everything faster" without mentioning write cost and storage.

You are ready to move on when you can normalise a messy student-course table to 3NF on a whiteboard and explain ACID with a money transfer.

Key concepts: Types of keys, ER model to tables, Functional dependencies, Normal forms: 1NF to BCNF, Transactions and ACID, Isolation levels and anomalies, Indexing and B+ trees, SQL vs NoSQL and CAP.

Mini project: Design a college placement database (students, companies, drives, applications, offers): draw the ER diagram, convert it to tables in 3NF, mark all keys, and write a one-page note on which columns you would index and why.

Self-check: Explain a non-repeatable read with a two-transaction example, and which isolation level prevents it.

Resources:
- [Database System Concepts (Silberschatz) companion site](https://www.db-book.com/) (db-book.com)
- [Use The Index, Luke](https://use-the-index-luke.com/) (Markus Winand)
- [GeeksforGeeks](https://www.geeksforgeeks.org/) (GeeksforGeeks)

### SQL for Interviews and OAs

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/sql-interviews

Write the queries interviewers ask: joins, GROUP BY with HAVING, subqueries, nth highest salary and window functions.

Many OAs include 1 or 2 SQL questions, and technical interviewers often ask you to write a query on paper. Practice by writing, not by reading.

#### Must-know syntax
- SELECT, WHERE, ORDER BY, LIMIT, DISTINCT.
- **Joins**: INNER, LEFT, RIGHT, FULL, SELF and CROSS joins; know which rows each keeps.
- **Aggregation**: COUNT, SUM, AVG, MIN, MAX with GROUP BY; filter groups with HAVING.
- **Subqueries**: in WHERE, in FROM, and correlated subqueries.
- **Window functions**: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, running totals with SUM() OVER.
- DDL vs DML vs DCL; DELETE vs TRUNCATE vs DROP; UNION vs UNION ALL.

#### Classic interview queries
Second or Nth highest salary (DENSE_RANK or LIMIT OFFSET), employees earning more than their managers (self join), department-wise highest salary, duplicate emails, customers who never ordered (LEFT JOIN with IS NULL), consecutive numbers, rank scores.

#### Pitfalls
- Using WHERE to filter aggregates instead of HAVING.
- NULL handling: NULL = NULL is not true; use IS NULL, and remember COUNT(column) skips NULLs.
- Selecting non-aggregated columns that are not in GROUP BY.

You are ready to move on when you can write the Nth highest salary query three different ways and explain the difference between RANK and DENSE_RANK.

Key concepts: SELECT, WHERE, ORDER BY, Joins, GROUP BY and HAVING, Subqueries and correlated subqueries, Window functions, NULL handling, DELETE vs TRUNCATE vs DROP.

Mini project: Solve 25 SQL problems in 7 days on HackerRank SQL or LeetCode's database problems, including Second Highest Salary, Nth Highest Salary, Employees Earning More Than Their Managers, Department Highest Salary, Duplicate Emails, Customers Who Never Order, Rank Scores and Consecutive Numbers. Log the concept each one tested.

Self-check: Why does SELECT dept, MAX(salary) FROM emp WHERE MAX(salary) > 50000 GROUP BY dept fail, and how do you fix it?

Resources:
- [SQLBolt interactive lessons](https://sqlbolt.com/) (SQLBolt)
- [HackerRank SQL practice](https://www.hackerrank.com/domains/sql) (HackerRank)
- [W3Schools SQL tutorial](https://www.w3schools.com/sql/) (W3Schools)

### Operating Systems

core · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/operating-systems

Cover processes and threads, CPU scheduling, synchronisation, deadlocks, memory management and virtual memory at interview depth.

OS is a favourite theory topic in both service and product-company interviews. Focus on clear explanations with small examples.

#### Core concepts
- **Process vs thread**, process states, PCB, context switching, user vs kernel mode, system calls.
- **CPU scheduling**: FCFS, SJF, SRTF, Round Robin and priority scheduling. Be ready to compute average waiting and turnaround time for a small example. Starvation and aging.
- **Synchronisation**: race conditions, critical section, mutex vs semaphore (binary and counting), producer-consumer, readers-writers and dining philosophers.
- **Deadlocks**: four necessary conditions (mutual exclusion, hold and wait, no preemption, circular wait), prevention, avoidance with the Banker's algorithm, detection.
- **Memory management**: paging, segmentation, fragmentation (internal vs external), TLB.
- **Virtual memory**: demand paging, page faults, page replacement (FIFO, LRU, Optimal), Belady's anomaly, thrashing.
- Basics of file systems and disk scheduling (often asked at service companies).

#### Pitfalls
- Saying mutex and binary semaphore are the same; ownership is the key difference.
- Memorising scheduling definitions without being able to draw a Gantt chart.

You are ready to move on when you can draw a Round Robin Gantt chart, list the four deadlock conditions with one way to break each, and run LRU on a page reference string.

Key concepts: Processes, threads, context switch, CPU scheduling algorithms, Mutex, semaphores, critical section, Classic synchronisation problems, Deadlock conditions and Banker's algorithm, Paging, segmentation, fragmentation, Virtual memory and page replacement, Disk scheduling.

Mini project: Write a small simulator that takes a list of processes and prints Gantt charts and average waiting time for FCFS, SJF and Round Robin, plus a page replacement simulator for FIFO and LRU that counts page faults. Use it to answer 10 textbook numericals.

Self-check: What are the four necessary conditions for deadlock, and how does the Banker's algorithm avoid it?

Resources:
- [Operating Systems: Three Easy Pieces](https://pages.cs.wisc.edu/~remzi/OSTEP/) (OSTEP)
- [NPTEL courses](https://nptel.ac.in/) (NPTEL)
- [GeeksforGeeks](https://www.geeksforgeeks.org/) (GeeksforGeeks)

### Computer Networks

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/computer-networks

Explain the OSI and TCP/IP models, TCP vs UDP, IP addressing and subnetting, DNS, HTTP and HTTPS, and what happens when you type a URL.

Computer Networks questions are common in technical rounds, and "what happens when you type google.com in a browser?" is one of the most asked fresher questions in India.

#### Core concepts
- **OSI (7 layers) vs TCP/IP (4 layers)**: what each layer does, with a protocol example for each.
- **TCP vs UDP**: connection-oriented vs connectionless, three-way handshake, four-way teardown, flow control (sliding window), congestion control (slow start), and where each is used.
- **IP addressing**: IPv4 classes, private ranges, CIDR and subnetting (compute network, broadcast and host count), IPv6 basics, NAT.
- **Application layer**: DNS resolution (recursive and iterative), HTTP methods and status codes, HTTP vs HTTPS and the TLS handshake at a high level, cookies and sessions.
- **Devices**: hub vs switch vs router; MAC vs IP address; ARP; DHCP.
- Basics of sockets and ports (80, 443, 22, 53).

#### The URL question
Walk through: browser cache, DNS lookup, TCP handshake, TLS handshake, HTTP request, server processing, response, rendering. Mention load balancers and CDNs for bonus points.

#### Pitfalls
- Mixing up which layer handles routing (network) vs reliable delivery (transport).
- Getting the subnet host count wrong by forgetting to subtract network and broadcast addresses.

You are ready to move on when you can walk through the URL question for 3 minutes without notes and subnet 192.168.1.0/26 correctly.

Key concepts: OSI and TCP/IP models, TCP vs UDP and the handshake, Flow and congestion control, IP addressing and subnetting, DNS, DHCP, ARP, HTTP, HTTPS and TLS, Switches, routers, NAT, What happens when you type a URL.

Mini project: Use Wireshark or browser DevTools to capture a visit to a website, and write a one-page annotated walkthrough of DNS, TCP handshake, TLS and HTTP in that capture. Then solve 10 subnetting questions and check them with an online calculator.

Self-check: Why does a video call usually use UDP while a file download uses TCP?

Resources:
- [Cloudflare Learning Center](https://www.cloudflare.com/learning/) (Cloudflare)
- [Kurose and Ross: Computer Networking resources](https://gaia.cs.umass.edu/kurose_ross/) (UMass)
- [MDN: An overview of HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview) (MDN)

## Online Assessments

Know the formats of mass-recruiter tests and product-company coding OAs, and how to score well under time pressure and proctoring.

### Mass-Recruiter Tests: TCS NQT, Infosys, Accenture and Others

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/mass-recruiter-tests

Learn the section structure, cut-offs and question styles of TCS NQT, Infosys, Wipro, Accenture, Cognizant and Capgemini tests.

Service-company tests filter thousands of candidates with sectional cut-offs. Knowing the exact format is worth as much as extra practice. Patterns change every year, so always confirm the latest one from your placement cell or recent candidates.

#### Typical structures
- **TCS NQT**: a foundation section (numerical, verbal and reasoning ability) and an advanced section (advanced quant and reasoning plus coding). Your score decides the band: Ninja, Digital or Prime.
- **Infosys**: reasoning, maths, verbal and pseudocode sections; higher roles (Specialist Programmer, Digital Specialist Engineer) have a hard coding round, and HackWithInfy is an alternate route.
- **Accenture**: cognitive and technical assessment, a coding round with 2 problems, and a communication assessment.
- **Wipro (NLTH and Elite)**, **Cognizant (GenC)**, **Capgemini**: aptitude, logical, verbal, essay or email writing, and 1 to 2 coding problems. Capgemini also uses game-based aptitude.

#### Question styles
- **Pseudocode and output prediction**: trace loops, recursion and bitwise operations by hand.
- **Coding**: easy-to-medium problems (strings, arrays, number patterns, simple DP), usually with all test cases needed for full marks.
- **Psychometric or behavioural** sections in some tests.

#### Pitfalls
- Clearing the overall cut-off but missing a sectional one.
- Ignoring pseudocode practice, which is a distinct skill.
- Using unusual input handling; read exactly the format given.

You are ready to move on when you have completed one full-length mock for each of your target companies within time and know every section's duration and cut-off.

Key concepts: TCS NQT and its bands, Infosys test and HackWithInfy, Accenture cognitive and coding, Wipro, Cognizant, Capgemini, Pseudocode and output prediction, Sectional cut-offs, Game-based and psychometric tests.

Mini project: Take one full-length timed mock each for TCS NQT, Infosys and Accenture over 10 days. After each, write a section-wise score table, list the 5 slowest questions and redo them, and adjust your time split for the next mock.

Self-check: Why might a candidate with a high total score still be rejected in a mass-recruiter test?

Resources:
- [PrepInsta: company-wise placement papers](https://prepinsta.com/) (PrepInsta)
- [TCS careers](https://www.tcs.com/careers) (TCS)
- [Infosys careers](https://www.infosys.com/careers/) (Infosys)
- [IndiaBix: placement papers and aptitude](https://www.indiabix.com/) (IndiaBix)

### Product Company Coding OAs

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/product-company-oas

Prepare for 60 to 120 minute coding OAs on HackerRank, HackerEarth, CodeSignal and in-house platforms used by product companies and startups.

Product-company OAs usually give 2 to 4 problems in 60 to 120 minutes, scored by hidden test cases. Many students lose marks not from lack of knowledge but from poor test-taking.

#### Common formats
- **HackerRank**: function-signature problems, sometimes with MCQs on CS core and SQL. Many companies use it.
- **HackerEarth** and **CodeSignal**: similar, sometimes with full stdin and stdout handling.
- In-house platforms: Amazon, Google and others have their own; some add work-style or debugging sections.
- Typical mix: one easy-medium array or string problem, one medium (greedy, binary search, graph or DP), and occasionally a hard one.

#### Strategy during the test
- Read all problems first; start with the one you are most confident about.
- Write a brute force that passes small cases if the optimal idea is not coming. **Partial scores count**.
- Watch constraints for the expected complexity, and use 64-bit integers by default.
- Test with edge cases using the custom input box before submitting.
- Keep 10 minutes at the end to recheck.

#### Integrity and environment
Tests are proctored (webcam, tab switching, plagiarism checks). Use a stable connection, a quiet room, and only allowed resources. Plagiarism flags lead to rejection and sometimes blacklisting.

#### Pitfalls
- Spending 50 minutes on the hardest problem and leaving an easy one unsolved.
- Printing debug output that breaks the expected format.

You are ready to move on when you can score 2 out of 3 problems fully on a timed 90-minute mock OA built from LeetCode mediums.

Key concepts: HackerRank and HackerEarth formats, Function signature vs stdin problems, Problem ordering strategy, Partial scoring with brute force, Custom test cases, Proctoring and integrity rules, MCQ sections on CS core.

Mini project: Run 4 self-made mock OAs over 2 weeks: 3 random LeetCode mediums (or 2 mediums and 1 hard) in 90 minutes on HackerRank's interview kit or a LeetCode virtual contest. Record score, time per problem and the reason for every failed test case.

Self-check: With 30 minutes left and one unsolved medium problem, what is the best way to maximise your score?

Resources:
- [HackerRank Interview Preparation Kit](https://www.hackerrank.com/interview/interview-preparation-kit) (HackerRank)
- [HackerEarth practice](https://www.hackerearth.com/practice/) (HackerEarth)
- [LeetCode contests (virtual participation)](https://leetcode.com/contest/) (LeetCode)

## Resume, Projects and Applications

Get shortlisted: a one-page ATS-friendly resume, two projects you can defend, and coding and professional profiles that open off-campus doors.

### The Fresher Resume

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/fresher-resume

Write a one-page, ATS-friendly resume with quantified project bullets, relevant skills and coding achievements.

Your resume decides whether you get to the test or interview at all, especially off campus. Recruiters spend under a minute on it, so it must be easy to scan.

#### Structure (one page)
1. Name, phone, professional email, LinkedIn, GitHub and coding profile links.
2. **Education**: college, degree, CGPA, graduation year; class 10 and 12 percentages if your college or target companies ask for them.
3. **Skills**: languages, frameworks, tools, CS fundamentals. Only list what you can be questioned on.
4. **Projects**: 2 or 3, each with a tech stack line and 2 to 3 bullet points.
5. **Experience**: internships, freelance or open-source work.
6. **Achievements**: contest ratings, hackathon results, problems solved, relevant certifications.

#### Writing strong bullets
Use action verb + what you built + how + measurable result. "Built a placement tracker in React and Node.js used by 300 students, reducing spreadsheet updates by 80 percent" beats "Worked on a web app".

#### ATS basics
Use a simple single-column template (LaTeX on Overleaf or a clean doc), standard section names, no tables or images for key text, and export to PDF. Mirror important keywords from the job description honestly.

#### Pitfalls
- Two pages, photos, objectives like "seeking a challenging role", or long skill lists.
- Listing technologies you cannot answer basic questions on. Interviewers will ask.
- Typos and inconsistent date formats.

You are ready to move on when a senior or mentor can read your resume in 30 seconds and correctly tell you your two strongest points.

Key concepts: One-page structure, Quantified project bullets, Skills you can defend, ATS-friendly formatting, Achievements and coding ratings, Tailoring per role.

Mini project: Create your resume on an Overleaf or clean single-column template, rewrite every bullet in action-how-result form, get feedback from two seniors who were placed, and keep a changelog of three versions.

Self-check: Rewrite the bullet 'Made a chat app using MERN' into an action-how-result bullet.

Resources:
- [Tech Interview Handbook: resume](https://www.techinterviewhandbook.org/resume/) (Tech Interview Handbook)
- [Overleaf resume templates](https://www.overleaf.com/latex/templates) (Overleaf)

### Projects That Get Interviews

core · intermediate · about 30 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/projects-for-freshers

Build two solid, deployed projects that solve a real problem, and prepare to explain every design decision in an interview.

Interviewers spend 10 to 20 minutes on your projects. Two projects you understand deeply beat six tutorial clones.

#### What makes a project strong
- Solves a real problem, ideally one you or your college faced.
- **Deployed** with a live link and a clean GitHub README (problem, features, tech stack, screenshots, setup steps).
- Has at least one non-trivial part: authentication, a database with relationships, caching, a background job, search, payments, real-time updates or an ML model served behind an API.
- Shows engineering habits: meaningful commits, environment variables for secrets, basic tests or validation.

#### Project ideas by track
- Web: a placement or internship tracker, a college event portal with role-based access, a URL shortener with analytics.
- Backend: a rate-limited REST API with caching, a job queue for sending emails.
- Data or ML: a resume-to-job matcher, a model with a simple web UI and a clear evaluation.
- Mobile: an offline-first expense splitter.

#### Prepare to defend it
For each project, prepare answers to: why this stack, what the database schema looks like, the hardest bug and how you fixed it, how it would scale to 10x users, and what you would do differently.

#### Pitfalls
- Copying a tutorial project and being unable to explain parts of the code.
- Claiming team projects as solo work; be clear about your contribution.

You are ready to move on when you can give a 2-minute overview of each project and answer five follow-up questions about it without hesitation.

Key concepts: Choosing a real problem, Deployment and live links, README and documentation, One non-trivial technical feature, Git hygiene, Scaling and trade-off talking points.

Mini project: Ship one project end to end in 3 weeks: a deployed app with authentication, a relational database and one non-trivial feature, a README with screenshots, and a one-page interview prep doc covering stack choice, schema, hardest bug and how it would scale.

Self-check: If an interviewer asks how your project would handle 10 times the current users, what three things would you discuss?

Resources:
- [GitHub Docs: About READMEs](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-readmes) (GitHub)
- [GitHub Pages](https://docs.github.com/en/pages) (GitHub)
- [freeCodeCamp News](https://www.freecodecamp.org/news/) (freeCodeCamp)

### Profiles, Referrals and Off-Campus Applications

recommended · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/profiles-and-off-campus

Use LinkedIn, GitHub and coding profiles, referrals, careers pages and hiring challenges to get interviews beyond your campus drives.

Many strong offers, especially from startups and product companies, come off campus. That needs visibility and a steady application routine.

#### Profiles that work for you
- **LinkedIn**: clear headline ("Final-year CSE | Java, Spring Boot | 1900 LeetCode"), a short about section, projects in the featured section, and regular posts about what you build.
- **GitHub**: pinned repositories with READMEs; consistent activity matters less than quality.
- **Coding profiles**: LeetCode, Codeforces or CodeChef links on your resume once your rating is decent.

#### Channels
- **Referrals**: the highest conversion. Message employees with a short note, your resume and the specific job ID. Ask alumni from your college first.
- **Careers pages** and job boards (LinkedIn Jobs, Naukri, Wellfound for startups, Instahyre).
- **Hiring challenges**: TCS CodeVita, Infosys HackWithInfy, Flipkart GRiD, Amazon and Microsoft programmes for students, and competitions on Unstop.
- Internship to PPO (pre-placement offer) conversion: often the best route to a good first job.

#### Application routine
Track every application in a spreadsheet: company, role, date, channel, referral, status, follow-up date. Aim for a steady weekly number rather than mass-applying once.

#### Pitfalls
- Sending generic "please refer me" messages without a job ID or resume.
- Applying without tailoring the resume to the role's key skills.

You are ready to move on when you have an updated LinkedIn and GitHub, a tracker with at least 20 applications and at least 5 referral requests sent.

Key concepts: LinkedIn profile and headline, GitHub pinned repositories, Referral messages, Job boards and careers pages, Hiring challenges, Internship to PPO, Application tracker.

Mini project: Over 2 weeks: rewrite your LinkedIn headline and about section, pin 3 GitHub repos with READMEs, register for one hiring challenge, send 10 personalised referral requests with job IDs, and track 20 applications in a spreadsheet.

Self-check: What three things should a referral request message include so that the employee can act on it in one minute?

Resources:
- [Unstop: hiring challenges](https://unstop.com/) (Unstop)
- [LinkedIn](https://www.linkedin.com/) (LinkedIn)
- [Wellfound startup jobs](https://wellfound.com/) (Wellfound)

## Interview Rounds

Turn preparation into offers: perform in technical rounds, practise with mocks, and handle the HR round with confidence.

### Technical Interview Rounds

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/technical-interviews

Handle live coding, CS fundamentals and project discussions by thinking aloud, writing clean code and testing it in front of the interviewer.

In a technical round, the interviewer is judging how you think and communicate, not only whether you reach the answer.

#### Live coding flow (about 40 minutes)
1. Clarify the problem, inputs, constraints and edge cases. Ask questions.
2. Explain a brute force and its complexity.
3. Discuss the optimised approach and get the interviewer's agreement before coding.
4. Code cleanly: meaningful names, small helper functions, no contest macros.
5. Dry-run with an example, then cover edge cases.
6. State final time and space complexity and mention possible improvements.

#### Other parts of the round
- **CS fundamentals**: OOP, DBMS, OS and CN questions, often linked to your projects ("how did you handle concurrent bookings?").
- **Project deep dive**: architecture, schema, trade-offs, what you would change.
- **Output and debugging questions** in your language at service companies.
- **Low-level design** basics at some product companies: design a parking lot or an LRU cache with classes.

#### Communicating well
Think aloud, especially when stuck. Use hints quickly and gracefully; they are part of the process. If you do not know a theory answer, say what you do know and how you would find out.

#### Pitfalls
- Silent coding for 15 minutes.
- Jumping to an optimal solution you half-remember and getting lost.
- Ignoring the interviewer's hints.

You are ready to move on when you can solve a medium problem in 30 minutes while explaining each step aloud, and answer a follow-up on its complexity.

Key concepts: Clarifying questions, Brute force to optimal, Thinking aloud, Clean interview code, Testing and dry runs, Project deep dives, Low-level design basics.

Mini project: Record yourself solving 5 medium problems on video, explaining aloud as in an interview. Watch each recording and score yourself on clarification, approach, code quality, testing and complexity, then repeat the weakest two.

Self-check: Why should you explain a brute force solution even when you already know the optimal one?

Resources:
- [Tech Interview Handbook](https://www.techinterviewhandbook.org/) (Tech Interview Handbook)
- [InterviewBit](https://www.interviewbit.com/) (InterviewBit)
- [NeetCode](https://neetcode.io/) (NeetCode)

### Mock Interviews

recommended · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/mock-interviews

Practise with peers, seniors and platforms under realistic conditions, and use structured feedback to fix specific weaknesses.

Interviewing is a performance skill. You only get better by doing it under realistic pressure and getting honest feedback.

#### Ways to get mocks
- **Peer mocks**: pair with a friend; alternate interviewer and candidate roles. Being the interviewer teaches you what good answers sound like.
- **Seniors and alumni** who were recently placed; they know current question patterns.
- **Platforms**: interviewing.io and other mock-interview services, plus college placement cell mocks.

#### Running a good mock
- 45 minutes: 5 minutes intro, 30 minutes coding, 10 minutes CS or project questions.
- Use a plain editor or shared doc without autocomplete, as in many real rounds.
- Feedback form: problem solving, communication, code quality, testing, CS knowledge, each scored 1 to 4 with one specific example.

#### Using feedback
Keep a running list of recurring issues (for example "forgets edge cases", "rambles in project explanation") and fix one per week with targeted practice.

#### Pitfalls
- Doing mocks only with friends who are too polite to criticise.
- Waiting until the week before placements to start mocks.

You are ready to move on when you have done at least 6 mocks and your feedback no longer repeats the same top issue.

Key concepts: Peer mock pairs, Alumni and senior mocks, Mock interview platforms, Structured feedback forms, Tracking recurring issues.

Mini project: Run 6 mock interviews in 3 weeks with at least 3 different people. Use the same feedback form each time, chart your scores per category, and write down the one change you made after each mock.

Self-check: Why is acting as the interviewer in a peer mock useful for your own preparation?

Resources:
- [interviewing.io](https://interviewing.io/) (interviewing.io)
- [Tech Interview Handbook](https://www.techinterviewhandbook.org/) (Tech Interview Handbook)

### The HR and Behavioural Round

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/hr-round

Prepare honest, structured answers for HR questions using STAR, and handle relocation, bond, salary and offer questions professionally.

The HR round rarely gets you an offer on its own, but it can lose you one. Prepare it like any other round.

#### Common questions
- Tell me about yourself (a 60 to 90 second story: education, what you build, why this role).
- Why this company? Why should we hire you?
- Strengths and weaknesses (a real weakness with what you are doing about it).
- A challenge, a failure, a conflict in a team, leading something.
- Where do you see yourself in 5 years?
- Are you willing to relocate, work in shifts or sign a service agreement (bond)?
- Do you have other offers? What are your salary expectations?
- Do you have any questions for us?

#### STAR for behavioural answers
Situation, Task, Action, Result. Keep it under 2 minutes, focus on your own actions, and end with a measurable result or a lesson. Prepare 5 or 6 stories from projects, internships, clubs and hackathons that you can adapt to many questions.

#### Professional basics
Research the company (products, recent news, values). Be honest about other offers and flexibility. For mass recruiters, salary is usually fixed by band; for others, give a researched range.

#### Pitfalls
- Memorised, robotic answers or generic praise of the company.
- Speaking negatively about your college, a teammate or a previous employer.
- Saying you have no questions at the end.

You are ready to move on when you can deliver your introduction and three STAR stories naturally, without notes, in a recorded practice session.

Key concepts: Tell me about yourself, STAR method, Story bank of 5-6 experiences, Company research, Relocation, shifts and bonds, Salary and offer questions, Questions to ask the interviewer.

Mini project: Write a 90-second introduction and 6 STAR stories (challenge, failure, conflict, leadership, learning fast, a proud project). Record yourself answering 10 common HR questions and refine any answer that goes over 2 minutes.

Self-check: Give a weakness you could honestly share in an HR round and explain how you would frame what you are doing about it.

Resources:
- [Tech Interview Handbook: behavioral interviews](https://www.techinterviewhandbook.org/behavioral-interview/) (Tech Interview Handbook)
- [IndiaBix: HR interview questions](https://www.indiabix.com/hr-interview/questions-and-answers/) (IndiaBix)

## Your 8-12 Week Placement Plan

Tie everything together into a weekly schedule, then handle the final week, multiple offers and the move into your first job.

### The 8-12 Week Placement Timeline

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/placement-timeline

Follow a week-by-week plan that balances DSA, aptitude, CS core subjects, projects and mocks in the months before placement season.

This plan assumes about 4 to 5 hours a day alongside college and that you know the basics of one language. Stretch it to 12 weeks if you are starting DSA from scratch or have heavy coursework.

#### Weeks 1 to 3: foundations
- DSA: complexity, arrays, strings, hashing, two pointers, sliding window, prefix sums, sorting, binary search (about 60 problems).
- Aptitude: 30 minutes daily of arithmetic.
- Resume first draft; pick your two projects.

#### Weeks 4 to 6: core data structures
- DSA: recursion, backtracking, linked lists, stacks and queues, trees, BST, heaps (about 70 problems).
- CS core: OOP and DBMS plus SQL practice.
- Reasoning and verbal: alternate days.
- Start one weekly contest.

#### Weeks 7 to 9: graphs and DP
- DSA: graphs, greedy, DP families, tries and bit manipulation (about 70 problems).
- CS core: OS and Computer Networks.
- Finish and deploy the main project.
- Begin peer mocks.

#### Weeks 10 to 12: tests and interviews
- Company-specific mocks (TCS NQT, Infosys, Accenture, product OAs).
- Revise your problem log with spaced repetition; no new topics.
- Two mock interviews a week; HR story bank.

#### Daily shape
Roughly 2.5 hours DSA, 45 minutes aptitude, 45 minutes CS core or project, and 15 minutes revising your log. Take one lighter day a week.

#### Pitfalls
- Overplanning and underexecuting. Track hours and problems weekly.
- Dropping aptitude for DSA (or the reverse) depending on mood.

You are ready to move on when you have a weekly plan in a calendar, a tracker for problems and hours, and your week 1 targets completed.

Key concepts: Weeks 1-3: arrays to binary search, Weeks 4-6: recursion, lists, trees, heaps, Weeks 7-9: graphs, greedy, DP, Weeks 10-12: mocks and revision, Daily time split, Weekly review and tracking.

Mini project: Turn this plan into your own calendar with dates, weekly problem targets, CS subject slots and mock dates. Keep a weekly review note (hours, problems, mock scores, what slipped) for every week until placements.

Self-check: You are in week 8 and behind on DP but ahead on aptitude. How would you rebalance the next two weeks?

Resources:
- [takeUforward: Striver's sheets](https://takeuforward.org/) (takeUforward)
- [NeetCode roadmap](https://neetcode.io/roadmap) (NeetCode)
- [Tech Interview Handbook: study plan](https://www.techinterviewhandbook.org/coding-interview-study-plan/) (Tech Interview Handbook)

### Placement Day, Offers and Joining

recommended · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/dsa-placement/offers-and-final-week

Prepare for the drive day itself, compare and accept offers sensibly, and get ready for onboarding and your first months as an engineer.

The last stretch is about execution and good decisions.

#### The week before and the day of the drive
- Revise your problem log and formula sheets; avoid new topics.
- Re-read the company's process, past questions and your resume line by line.
- Prepare documents (ID, mark sheets, resume copies), test your laptop, webcam and internet for online rounds.
- Sleep well. A rested mind solves more than a last-night cram.

#### Comparing offers
Look beyond the headline CTC: fixed vs variable pay, joining bonus, stock vesting schedule, service agreement or bond, location, role (SDE vs support or testing), training period, and team or tech stack. A lower CTC with strong learning can be the better first job.

#### Accepting and joining
- Read the offer letter fully; ask HR about anything unclear.
- Follow your college policy before accepting or declining.
- Respond professionally to every offer, including ones you decline.
- Some service companies have long onboarding gaps; use them to learn the stack you will work on.

#### Pitfalls
- Reneging on accepted offers without strong reason, which hurts your college's relationship with the company.
- Comparing only CTC numbers that include one-time or variable components.

You are ready when you can explain your offer's fixed pay, variable pay, bond terms and role to someone else in two minutes.

Key concepts: Final week revision, Drive day checklist, Reading CTC breakdowns, Bonds and service agreements, College offer policies, Preparing for onboarding.

Mini project: Create a drive-day checklist (documents, devices, revision list, logistics) and an offer comparison sheet with fixed pay, variable pay, bonus, stock, bond, location, role and learning potential. Fill it with two real or sample offers and write which you would pick and why.

Self-check: Two offers show 12 LPA and 10 LPA. What details would you check before deciding the first is better?

Resources:
- [Tech Interview Handbook: negotiation](https://www.techinterviewhandbook.org/negotiation/) (Tech Interview Handbook)
- [AmbitionBox company reviews and salaries](https://www.ambitionbox.com/) (AmbitionBox)

## Related

- [Career roadmaps](https://www.internhack.in/roadmaps)
