DSA Logic Building Playbook
Code nahi, logic banana seekho — Test case se optimal code tak
Golden Rules — 5 Non-Negotiable Principles
Har coding session shuru karne se pehle ye 5 rules dimag me baitha lo. Zyada log DSA me code nahi, logic me atakte hain — ye guide logic banana sikhati hai.
| Rule | Kya matlab hai |
|---|---|
| 01 Code se pehle logic | Keyboard tab chhuo jab paper pe pata ho ki exact kya likhna hai. |
| 02 Seedha optimal nahi aata | Pehle working brute force banao, phir bottleneck dekh ke improve karo. |
| 03 Test case sabse bada hint hai | Input se output kaise bana, haath se pen-paper pe trace karke dekho. |
| 04 Constraints batate hain technique | Problem ka n kitna bada hai, wahi bata deta hai kaunsa algorithm chalega. |
| 05 Problem naya nahi hota, pattern purana hota hai | DSA me ginke sirf 15–20 fundamental patterns hote hain. |
Seven Step Framework
Har problem pe ye structured sequence follow karo. Total lagbhag 16 minute — isme se 7 minute sirf soch-vichar, code uske baad.
| Step | Kya karna hai | Time | Key focus |
|---|---|---|---|
| 1 | Problem dobara apne words me bolo | 1 min | Misunderstandings clear karo |
| 2 | Input, Output, Constraints likho | 1 min | Bounds aur data types check karo |
| 3 | Test case ko haath se solve karo | 3 min | Mental steps observe karo |
| 4 | Brute force socho aur complexity nikalo | 2 min | Base working solution |
| 5 | Constraints dekh ke target complexity decide karo | 1 min | O(n), O(n log n) target fix |
| 6 | Pattern pehchano, brute force ko optimize karo | 3 min | Waste hatao using right tool |
| 7 | Edge cases check karo, phir code likho | 5 min | Off-by-one, empty input safety |
Problem Ko Samjho
Problem padhte hi apne aap se ye 5 basic sawal poochho:
- Input kya hai? Array, string, number, tree, graph ya matrix?
- Output kya chahiye? Single number, boolean true/false, index, array, count, min/max value?
- Kya input sorted hai? Agar sorted ho to Binary Search ya Two Pointers ke 90% chances hote hain.
- Duplicates, negatives, empty input allowed hain?
- Constraints kya hain? n kitna bada hai? (limits of 105, 109, etc.)
Output type se hint
Output ka structure hi aksar data structure reveal kar deta hai:
| Output type | Aksar kaunsi technique lagti hai |
|---|---|
| Sirf true / false | Hashing, Two Pointers, Dynamic Programming, Graph Traversal |
| Count of ways | DP (combinations), Combinatorics, Backtracking |
| Min / Max value | Dynamic Programming, Greedy, Binary Search on Answer |
| Saare subsets / permutations / combinations | Backtracking, Recursion (decision tree) |
| Index ya specific pair | HashMap, Two Pointers, Binary Search |
| Shortest path / min steps | BFS (unweighted), Dijkstra (weighted) |
| Top K / K-th element | Heap (PriorityQueue), Quickselect, Sorting |
Test Case Se Logic Kaise Nikale
Method: Insaan ki tarah solve karo (bina computer, bina code)
- Sample input kagaz pe likho.
- Output tak kaise pahunche, step by step likho — dimag me nahi, paper pe.
- Poochho: "Maine kaunsa kaam baar baar kiya?" → wahi tumhara loop hai.
- Poochho: "Pichhle step ka kya yaad rakha?" → wahi tumhara variable / data structure hai.
- Poochho: "Kab ruka?" → wahi tumhari stopping / boundary condition hai.
Example: Maximum Subarray Sum
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4] | Expected output: 6
- Pehla element -2 → running sum = -2.
- Agla element 1 → pichhla sum negative hai (-2), usko saath leke chalna nuksan hai. Naya sum 1 se fresh start.
- -3 aaya → sum = 1 + (-3) = -2. Phir negative, restart ready rakho.
- 4 aaya → fresh start sum = 4. Aage -1, 2, 1 jodte gaye → running sums: 3, 5, 6.
- Max dekha = 6.
public int maxSubArray(int[] nums) {
int cur = nums[0], best = nums[0];
for (int i = 1; i < nums.length; i++) {
cur = Math.max(nums[i], cur + nums[i]); // restart ya jodte jao
best = Math.max(best, cur);
}
return best;
}
Chhote input se bade ki taraf jao
- Pehle bahut chhota input (2–3 elements) pe pen-paper solve karo.
- Phir thoda medium input pe test karo.
- Dekho tumhara tareeka kahan fail ho raha hai — wahi failure point tumhe asli edge-case logic sikhata hai.
Apne khud ke test cases banao
Sirf question ke diye test case pe rely mat karo: empty/single element [] [5], sab identical [2,2,2,2], sorted / reverse sorted [1,2,3] [3,2,1], all negative [-5,-2,-9], aur max constraint limit.
Test Case Padhne Ki 6 Techniques
Jab logic bilkul na soojh raha ho, sample test case ko in 6 nazron se dekho:
| # | Nazariya | Kya dekhna hai | Kaunse problems me kaam aata hai |
|---|---|---|---|
| 1 | Haath se trace karo | Tumhari aankhein aur dimag pen-paper pe kya steps follow kar rahe hain? | Greedy, Two Pointers, Simulation |
| 2 | Kya badla, kya same | Kaunse elements apni jagah pe hain aur kaunse shift hue? | Array partition, in-place sorting, rotation |
| 3 | Chhota bana ke dekho | n = 1, 2, 3, 4 ke answers paper pe manually likho | Recurrence relation, DP base cases, math sequences |
| 4 | Ulta chalo | Final output se input ki taraf reverse calculate karo | Binary Search on Answer, Prefix Sum + Map lookups |
| 5 | Extreme cases | Sab identical, already sorted, negatives, extreme bounds | Greedy assumptions test karna, edge bug discovery |
| 6 | Counter-example banao | Khud aisa input design karo jo tumhari trick ko break kare | Greedy confirm ya reject karne ke liye |
Fill-in-the-blank template
Har tough problem pe ye 7 sentences complete karo. Agar sab fill ho gaye to logic ban chuka hai — bas syntax likhna bacha hai.
- "Input ____________ hai aur output ____________ chahiye."
- "Haath se paper pe karte waqt maine ____________ kaam baar-baar kiya, aur ____________ yaad rakha."
- "Brute force solution ____________ hai (complexity ____________), par constraints ____________ hain, isliye ye TLE dega / chalega."
- "Brute force me ____________ computation baar-baar repeat ho raha hai (waste)."
- "Is waste ko hatane ke liye main ____________ (tool / data structure) use kar sakta hoon."
- "Ye tool 100% kaam karega kyunki ____________."
- "Edge cases jo handle karne hain: ____________, ____________, ____________."
Brute Force Hamesha Pehle
Brute force ek safety net hai. Ye prove karta hai ki tumhe problem 100% samajh aa chuki hai.
| Problem ka shabd | Brute force kaisa hoga | Complexity |
|---|---|---|
| "Saari possibilities try karo" | Nested loops ya recursion | depends |
| "Har pair check karo" | Do nested loops | O(n2) |
| "Har subarray check karo" | Start, end loops (+ sum loop) | O(n2) ya O(n3) |
| "Har subset check karo" | Include / exclude recursion | O(2n) |
Constraints Se Complexity Pehchano
Ye table memorise kar lo. Problem me n dekhte hi pata chal jata hai ki kitni fast solution chahiye.
| n ka size | Allowed complexity | Speed | Kaunsi techniques lag sakti hain |
|---|---|---|---|
| n ≤ 10 | O(n!) | Extremely slow | Permutations, Backtracking |
| n ≤ 20 | O(2n) | Exponential | Subsets generation, Bitmask DP, Backtracking |
| n ≤ 500 | O(n3) | Cubic | 3 nested loops, Floyd-Warshall, 3D DP |
| n ≤ 5,000 | O(n2) | Quadratic | 2 nested loops, 2D DP |
| n ≤ 105 | O(n log n) | Linearithmic (optimal) | Sorting, Heap, Binary Search, Divide & Conquer |
| n ≤ 106 | O(n) | Linear (fast) | Hashing, Two Pointers, Sliding Window, Prefix Sum |
| n ≥ 109 | O(log n) ya O(1) | Lightning fast | Binary Search, math formula, bit manipulation |
Example: Agar n = 105 hai aur brute force O(n2) hai, to operations = (105)2 = 1010. Ye guaranteed TLE dega! Solution O(n log n) ya O(n) hi hona chahiye — ab sirf wahi techniques dimag me lao.
Keyword Se Technique Pehchano
Problem statement ke words me hi solution ka hint chhupa hota hai.
Master pattern decision tree
| Input | Decision |
|---|---|
| Array / String | Sorted? → Two Pointers / Binary Search |
| Array / String | Unsorted + contiguous subarray, no negatives → Sliding Window |
| Array / String | Unsorted + contiguous, sum = K ya negatives → Prefix Sum + Map |
| Array / String | Pairs / lookup → HashMap / HashSet |
| Array / String | Next greater / Top K → Monotonic Stack / Heap |
| Optimization | Overlapping subproblems → Dynamic Programming |
| Optimization | Locally best choice → Greedy (sort first) |
| Optimization | Monotonic feasibility → Binary Search on Answer |
| Tree / Graph | Shortest path / level order → BFS (Queue) |
| Tree / Graph | Path / island sink → DFS (Recursion) |
| Tree / Graph | Prerequisites → Topological Sort |
| All subsets / paths | Backtracking tree |
Direct keyword to pattern table
| Problem me ye keyword / requirement dikhe | Ye technique dimag me lao |
|---|---|
| Sorted array, pair ya triplet dhoondna | Two Pointers, Binary Search |
| Subarray / substring, contiguous, max/min length | Sliding Window |
| Subarray sum, range sum query multiple times | Prefix Sum |
| Duplicate, frequency count, "pehle dekha hai?", pair sum | HashMap / HashSet |
| Sorted + search, "minimum X jo condition satisfy kare" | Binary Search (on answer pattern) |
| Brackets matching, next greater element, undo, nested | Stack, Monotonic Stack |
| Top K largest / smallest, running median, merge K lists | Heap / PriorityQueue |
| Linked list me cycle, middle node dhoondna | Fast & Slow Pointers (Floyd's Cycle) |
| Tree traversal, height, max path sum | DFS, BFS, Tree Recursion |
| Shortest path, level-order, min steps | BFS |
| Connected components, islands, clusters | DFS, BFS, Union-Find (DSU) |
| Dependencies, prerequisite ordering (course schedule) | Topological Sort (Kahn's / DFS) |
| Saare subsets, permutations, combinations | Backtracking |
| Har step pe locally best choice, intervals, scheduling | Greedy (aksar sorting ke baad) |
| Count ways, min cost, max profit, overlapping subproblems | Dynamic Programming |
| Prefix match, dictionary words, autocomplete | Trie (Prefix Tree) |
| Bit operations, single non-duplicate, power of 2 | Bit Manipulation |
| Intervals merge ya overlap check | Sort by start time, phir merge loop |
Core Patterns With Java Templates
Ye 11 patterns DSA ke 90% interview problems solve karte hain. Har pattern ka core intuition samjho aur code template yaad rakho.
9.1 Two Pointers
- Core idea: Do pointers (l, r) ko opposite ends ya same direction se move karo, nested loops se bacho.
- Kab lagayein: Sorted array, pair sum, palindrome check, in-place array reverse.
int l = 0, r = arr.length - 1;
while (l < r) {
int sum = arr[l] + arr[r];
if (sum == target) {
// target pair mil gaya
break;
} else if (sum < target) {
l++;
} else {
r--;
}
}
9.2 Sliding Window
- Core idea: Ek dynamic window [l, r] maintain karo. Right pointer badhao; condition violate ho to left se shrink karo.
- Kab lagayein: "Longest ya shortest contiguous subarray / substring jisme koi condition satisfy ho."
- Flow: EXPAND (arr[r] include) → window valid? nahi to SHRINK (arr[l] hatao, l++) → RECORD (best = max(best, len)).
int l = 0, best = 0;
for (int r = 0; r < n; r++) {
// 1. arr[r] ko current window me include karo
// 2. jab tak window invalid ho, shrink from left
while (/* window invalid condition */ false) {
// arr[l] ko window se hatao
l++;
}
// 3. valid window size record karo
best = Math.max(best, r - l + 1);
}
9.3 Prefix Sum
- Core idea: Running cumulative sum pehle store kar lo, taaki kisi bhi range [l, r] ka sum O(1) me mile.
int[] prefix = new int[n + 1];
for (int i = 0; i < n; i++) {
prefix[i + 1] = prefix[i] + arr[i];
}
// Range sum for arr[l..r]: sum = prefix[r + 1] - prefix[l]
9.4 HashMap
- Core idea: Expensive O(n) linear search ko O(1) lookup me badal do. "Pehle kaunsa element dekha tha" yaad rakho.
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int complement = target - arr[i];
if (map.containsKey(complement)) {
// pair mil gaya: indices i and map.get(complement)
}
map.put(arr[i], i);
}
9.5 Binary Search
- Core idea: Har step pe search space ko exactly aadha kar do.
- Kab lagayein: Sorted data me target dhoondna, ya answer monotonic ho jisme check(x) yes/no return kare.
int lo = 0, hi = n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // integer overflow protection
if (arr[mid] == target) return mid;
else if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
9.6 Stack
- Core idea: Last-In-First-Out. Jo element sabse recent aaya, uski state sabse pehle resolve karni ho.
- Kab lagayein: Valid Parentheses, Next Greater Element, Daily Temperatures.
Deque<Character> stack = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
9.7 Recursion and Backtracking
- Core idea: Choice lo, aage explore karo, galat rasta nikla to wapas aakar step undo karo. 3 mantras: Choose → Explore → Undo.
void solve(List<Integer> path) {
if (/* base case reached */ false) {
result.add(new ArrayList<>(path));
return;
}
for (int choice : choices) {
path.add(choice); // 1. Choose
solve(path); // 2. Explore
path.remove(path.size() - 1); // 3. Undo (Backtrack)
}
}
9.8 Dynamic Programming (DP)
- Core idea: Bade problem ko chhote overlapping subproblems me todo aur results cache (memoize / table) kar lo, taaki recalculation zero ho.
- DP kaise pehchano: "Count number of ways", "Min / Max value", "Is it possible?" + har element pe choice (include / exclude).
| DP ke 4 core steps | Sawal |
|---|---|
| 1. State | dp[i] ka exact matlab kya hai? Pehle plain words me likho. |
| 2. Transition | dp[i] ko pichhle calculated subproblems se kaise compute karein? |
| 3. Base case | Sabse chhota / trivial answer kya hai (dp[0])? |
| 4. Final answer | Answer table me kahan milega (dp[n] ya max(dp))? |
9.9 BFS and DFS
- BFS (Queue): level-by-level traversal. Unweighted graphs me shortest path guarantee karta hai.
- DFS (Recursion / Stack): ek raaste pe ant tak jao, phir backtrack. Connected components, cycle detection, tree traversals.
- Rule: Graphs aur 2D grids me hamesha visited state track karo, infinite loop se bachne ke liye.
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[]{startR, startC});
boolean[][] visited = new boolean[R][C];
visited[startR][startC] = true;
while (!q.isEmpty()) {
int[] cur = q.poll();
// 4 directions (up, down, left, right) explore karo:
// cell valid aur unvisited ho to visited mark karke queue me push karo
}
9.10 Greedy
- Core idea: Har step pe locally best / safest choice lo, bina aage ka soche. Tab kaam karta hai jab local optimum hi global optimum banaye.
- Verification: Aksar data sort karne ke baad lagta hai. Apne logic pe counter-example dhoondo; na mile to greedy safe hai.
9.11 Heap (PriorityQueue)
- Core idea: Sabse chhota (min-heap) ya bada (max-heap) element O(1) me dekho, O(log n) me extract karo.
- Pro trick: "Top K largest" ke liye hamesha min-heap of size K maintain karo.
PriorityQueue<Integer> pq = new PriorityQueue<>(); // Java default = Min-Heap
for (int x : arr) {
pq.add(x);
if (pq.size() > k) {
pq.poll(); // jo sabse chhota hai wo bahar
}
}
// pq.peek() ab exact k-th largest element hai
Thinking Ladder — 8 Steps
Ye ladder aapko test case se optimal code tak systematically guide karta hai. 4 phases me structured hai:
Phase 1 — Problem breakdown
| Step | Sawal | Action | Trap |
|---|---|---|---|
| 1 Samjho (apne words me) | Mujhe kya diya hai aur kya nikalna hai? | Bina code soche 2 sentences me bolo. | Sawal poora padhe bina coding shuru. |
| 2 Bounds aur Constraints | n kitna bada hai? Corner cases kya hain? | Negatives, empty, duplicates note karo. Target complexity fix. | Constraints ignore karna → TLE. |
Phase 2 — Manual observation
| Step | Sawal | Action | Trap |
|---|---|---|---|
| 3 Haath se solve (loop & variables) | Sample input pe maine kaunsa kaam baar-baar kiya, aur kya yaad rakha? | Dimag ke steps observe karo. Loop = baar-baar kaam; Yaad = variable / data structure. | Pehle se variables declare karna. |
| 4 Brute force (safety net) | Sabse basic, bina trick ka tareeka kya? Complexity? | Nested loops ya simple recursion jo 100% correct ho (bhale slow). | Brute force ko bekaar samajh ke skip karna. |
Phase 3 — Optimization breakthrough
| Step | Sawal | Action | Trap |
|---|---|---|---|
| 5 Waste dhoondo (bottleneck) | Brute force me kaunsa computation repeat / bekaar ho raha hai? | Dekho kahan loop baar-baar poora array scan kar raha hai ya subproblem recalculate ho raha hai. | Code optimize karna jabki algorithm hi inefficient hai. |
| 6 Tool chuno (pick the weapon) | Is waste ko hatane wala exact DS / algorithm kaunsa? | Neeche Prescription Matrix se match karo. | Random data structures guess karna. |
Phase 4 — Execution and verification
| Step | Sawal | Action | Trap |
|---|---|---|---|
| 7 Dry run (trace table) | Kya ye tool mere test case pe step-by-step sahi chal raha hai? | Chhota trace table banao (har iteration me variables). Extreme edge cases check karo. | Dry run kiye bina seedha IDE me code likhna. |
| 8 Optimal code (clean Java) | Dry run table ko clean code me kaise convert karun? | Verified trace ko line-by-line syntax me likho. Boundary checks pehle. | — (Result: first submission pe AC, bina TLE) |
Prescription Matrix — waste ko tool se match karo
| # | Brute force me waste / bottleneck | Exact ilaaj (tool) | Complexity drop | Example problems |
|---|---|---|---|---|
| 1 | Baar-baar linear search: "ye element pehle dekha tha?" | HashMap / HashSet | O(n) → O(1) | Two Sum, Subarray Sum Equals K |
| 2 | Har query pe range sum / product baar-baar calculate | Prefix Sum / Suffix array | O(n) → O(1) | Range Sum Query, Product Except Self |
| 3 | Har pair check, jabki array sorted hai ya sort ho sakta hai | Sort + Two Pointers | O(n2) → O(n) | 3Sum, Container With Most Water |
| 4 | Window ka common part har step pe recalculate | Sliding Window | O(n2) → O(n) | Longest Substring Without Repeating |
| 5 | Monotonic sequence me ek-ek step aage badhna | Binary Search (on answer) | O(n) → O(log n) | Koko Bananas, Search Rotated Array |
| 6 | Same subproblem recursion tree me baar-baar solve | Dynamic Programming | O(2n) → O(n) | Coin Change, Climbing Stairs |
| 7 | Pichhle elements ka order yaad rakhna ya matching pairs (LIFO) | Monotonic Stack | O(n2) → O(n) | Daily Temperatures, Valid Parentheses |
| 8 | Har step pe continuous dynamic min / max dhoondna | Heap / PriorityQueue | O(n) → O(log n) | Top K Frequent, Merge K Sorted Lists |
| 9 | Random unordered intervals me overlap check | Sort by start time | O(n2) → O(n log n) | Merge Intervals, Meeting Rooms |
Edge Cases Checklist
Final code submit karne se pehle ye 9 checks zaroor verify karo (tick lagao):
Jab Atak Jao To Kya Karo
Dimag blank ho jaye ya code TLE de raha ho, to is diagnostic flow ko follow karo:
| Paper pe trace kiya? | Brute force hai? | TLE aayega? | Remedy |
|---|---|---|---|
| Nahi | — | — | Chhota input (2–3 elements) paper pe trace karo |
| Haan | Nahi | — | Saare combinations / possibilities ka loop socho |
| Haan | Haan | Nahi | Seedha submit (pehle edge cases dekh lo) |
| Haan | Haan | Haan — search slow | HashMap / HashSet |
| Haan | Haan | Haan — range slow | Prefix Sum |
| Haan | Haan | Haan — overlapping | Dynamic Programming |
| Haan | Haan | Haan — monotonic | Binary Search on Answer |
| Haan | Haan | Haan — sorted pair | Two Pointers |
Situation-wise action plan
| Situation | Immediate action plan |
|---|---|
| Kuch samajh nahi aa raha | Sabse chhota input (2–3 elements) lo aur paper pe manually solve karo. |
| Brute force bhi nahi soojh raha | "Saare combinations / possibilities explore karo" socho, phir loops ya recursion me convert karo. |
| Brute force hai par slow (TLE) | Bottleneck identify karo: search slow, sorting baar-baar, ya duplicate computation? |
| Pattern pehchan nahi aa raha | Section 8 ka keyword-technique cheat-sheet dekho. |
| Do approaches me confusion | Dono ki time aur space complexity compare karo aur constraints se match karo. |
| Sorting se faayda dikh raha hai? | Data sort karo, phir Two Pointers, Binary Search ya Greedy try karo. |
| Extra memory use kar sakte ho? | Haan to HashMap, HashSet ya frequency array se time complexity girao. |
| DP lag raha hai par state nahi mil rahi | Pehle brute recursion likho; jo function parameters change ho rahe hain, wahi DP state hai. |
| 15–20 min se stuck ho | Solution dekh lo! Samjho kyun aur kaise kaam karta hai, phir 2 din baad bina dekhe scratch se likho. |
Worked Examples — Step by Step
Har example me wahi Thinking Ladder laga hai: test case observation se shuru, clean Java code pe khatam.
| # | Problem | Core pattern | Time | Space |
|---|---|---|---|---|
| 13.1 | Product of Array Except Self | Prefix & Suffix Product | O(n) | O(1) |
| 13.2 | Subarray Sum Equals K | Prefix Sum + HashMap | O(n) | O(n) |
| 13.3 | Container With Most Water | Two Pointers (greedy choice) | O(n) | O(1) |
| 13.4 | Merge Intervals | Sort by start + Greedy | O(n log n) | O(n) |
| 13.5 | Koko Eating Bananas | Binary Search on Answer | O(n log max) | O(1) |
| 13.6 | Coin Change | Bottom-up DP | O(amount × coins) | O(amount) |
| 13.7 | Number of Islands | 2D Grid DFS (in-place sink) | O(R × C) | O(R × C) |
| 13.8 | Subsets | Backtracking (decision tree) | O(n × 2n) | O(n) |
13.1 Product of Array Except Self
Problem: Har index i ke liye baaki sab elements ka product nikalo. Division strictly disallowed hai.
Test case: nums = [1,2,3,4] → [24,12,8,6]
| Thinking Ladder | Is problem me |
|---|---|
| Observe + Manual | Index 0: 24 = 2×3×4; Index 1: 12 = 1×3×4; Index 2: 8 = 1×2×4; Index 3: 6 = 1×2×3. Index 2 ka answer = (left ka product) × (right ka product) = (1×2) × 4 = 8. Matlab answer[i] = left[i] * right[i]. |
| Brute force | Har index ke liye doosra loop chala kar baaki array multiply karo → O(n2). |
| Waste analysis | Left product har step pe baar-baar calculate ho raha hai. Index 3 ka left (1×2×3) darasal Index 2 ke left (1×2) me bas 3 multiply karne se mil jata hai! |
| Tool | Prefix Product (left pass) aur Suffix Product (right pass). |
Dry run trace:
| i | nums[i] | left (prefix) | right (suffix) | answer[i] |
|---|---|---|---|---|
| 0 | 1 | 1 | 2×3×4 = 24 | 24 |
| 1 | 2 | 1 | 3×4 = 12 | 12 |
| 2 | 3 | 1×2 = 2 | 4 | 8 |
| 3 | 4 | 1×2×3 = 6 | 1 | 6 |
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
// Pass 1: Left prefix products
int left = 1;
for (int i = 0; i < n; i++) {
ans[i] = left;
left *= nums[i];
}
// Pass 2: Right suffix products multiply karo
int right = 1;
for (int i = n - 1; i >= 0; i--) {
ans[i] *= right;
right *= nums[i];
}
return ans;
}
13.2 Subarray Sum Equals K
Problem: Kitne contiguous subarrays ka sum exactly k hai? (Negative numbers allowed.)
Test case: nums = [1,2,3], k = 3 → 2 (subarrays [1,2] aur [3])
| Thinking Ladder | Is problem me |
|---|---|
| Observe + Manual | Saare subarrays: [1]=1, [1,2]=3 OK, [1,2,3]=6, [2]=2, [2,3]=5, [3]=3 OK. Total = 2. |
| Brute force | Har start i aur end j ke liye sum calculate karo → O(n2). |
| Waste analysis | Prefix sum se range sum O(1) me nikal jata hai, par hum phir bhi saare (i, j) pairs manually check kar rahe hain. |
| Click moment | P[j] = index j tak ka prefix sum. Subarray (i+1..j) ka sum = P[j] - P[i]. Hume chahiye P[j] - P[i] = k, yani P[i] = P[j] - k. Har j pe poochho: "pehle koi prefix P[j]-k ke barabar mila tha, kitni baar?" |
| Tool | Prefix Sum + HashMap (prefix value → frequency). |
Dry run trace:
| x | prefix | need = prefix - k | seen me need ka count | total | Updated seen |
|---|---|---|---|---|---|
| 1 | 1 | 1 - 3 = -2 | 0 | 0 | {0:1, 1:1} |
| 2 | 3 | 3 - 3 = 0 | 1 | 1 | {0:1, 1:1, 3:1} |
| 3 | 6 | 6 - 3 = 3 | 1 | 2 | {0:1, 1:1, 3:1, 6:1} |
public int subarraySum(int[] nums, int k) {
int count = 0, prefix = 0;
Map<Integer, Integer> seen = new HashMap<>();
seen.put(0, 1); // base: empty prefix sum is 0
for (int x : nums) {
prefix += x;
count += seen.getOrDefault(prefix - k, 0);
seen.put(prefix, seen.getOrDefault(prefix, 0) + 1);
}
return count;
}
13.3 Container With Most Water
Problem: Non-negative heights di gayi hain. Do vertical lines chuno jisse beech me sabse zyada paani hold ho.
Test case: height = [1,8,6,2,5,4,8,3,7] → 49
| Thinking Ladder | Is problem me |
|---|---|
| Observe + Manual | Area = width × min(height[l], height[r]). Index 1 (h=8) aur Index 8 (h=7): width = 7, min = 7, area = 49. |
| Brute force | Har possible pair (i, j) check karo → O(n2). |
| Click moment | Sabse wide container tab banta hai jab l = 0, r = n-1. Pointers paas aayenge to width kam hogi, to area badhane ka ek hi rasta hai: min height badhe. Bottleneck chhoti line hai — lambi line hilane se area kabhi nahi badh sakta. Isliye hamesha chhoti wali line ka pointer aage badhao. |
| Tool | Two Pointers (greedy pointer movement). |
Dry run trace:
| l | r | h[l] | h[r] | width | area | Action |
|---|---|---|---|---|---|---|
| 0 | 8 | 1 | 7 | 8 | 8 | h[l] < h[r] → l++ |
| 1 | 8 | 8 | 7 | 7 | 49 | h[r] < h[l] → r-- |
| 1 | 7 | 8 | 3 | 6 | 18 | h[r] < h[l] → r-- |
| 1 | 6 | 8 | 8 | 5 | 40 | Equal → koi bhi move |
public int maxArea(int[] h) {
int l = 0, r = h.length - 1, best = 0;
while (l < r) {
int currentArea = (r - l) * Math.min(h[l], h[r]);
best = Math.max(best, currentArea);
// hamesha chhoti height wali line ko move karo
if (h[l] < h[r]) {
l++;
} else {
r--;
}
}
return best;
}
13.4 Merge Intervals
Problem: Overlapping intervals ki list ko merge karke non-overlapping intervals banao.
Test case: [[1,3],[2,6],[8,10],[15,18]] → [[1,6],[8,10],[15,18]]
| Thinking Ladder | Is problem me |
|---|---|
| Observe + Manual | [1,3] aur [2,6]: 2 ≤ 3 hai, overlap! Merge: start = 1, end = max(3,6) = 6 → [1,6]. [1,6] aur [8,10]: 8 > 6, overlap nahi. [8,10] aur [15,18]: 15 > 10, overlap nahi. Maine hamesha pichhla merged interval yaad rakha. |
| Waste analysis | Agar input random unsorted aaye jaise [[8,10],[1,3],[2,6]], to "pichhla-naya" rule toot jayega! |
| Tool | Intervals ko start time se sort karo. Sorting ke baad overlap sirf previous interval ke saath hi possible hai. |
public int[][] merge(int[][] intervals) {
// 1. Start point ke hisaab se sort karo
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> res = new ArrayList<>();
res.add(intervals[0]);
for (int i = 1; i < intervals.length; i++) {
int[] last = res.get(res.size() - 1);
// current interval pichhle se overlap karta hai?
if (intervals[i][0] <= last[1]) {
last[1] = Math.max(last[1], intervals[i][1]); // merge end
} else {
res.add(intervals[i]); // naya interval
}
}
return res.toArray(new int[res.size()][]);
}
13.5 Koko Eating Bananas
Problem: Piles me bananas hain. Koko 1 ghante me kisi pile se k bananas kha sakti hai. h ghante ke andar sab khatam karne ke liye minimum speed k kya ho?
Test case: piles = [3,6,7,11], h = 8 → 4
| Thinking Ladder | Is problem me |
|---|---|
| Observe + Manual | Speed 4: ceil(3/4)+ceil(6/4)+ceil(7/4)+ceil(11/4) = 1+2+2+3 = 8 ghante OK. Speed 3: 1+2+3+4 = 10 ghante (limit 8 se zyada) FAIL. |
| Brute force | Speed k = 1, 2, 3, ... linear try karo. Max banana 109 ho sakta hai → TLE. |
| Click moment | Speed badhegi to hours ghategi (monotonic). Validation pattern: FAIL FAIL FAIL PASS PASS PASS PASS. Pehla PASS dhoondna = Binary Search on answer space [1, max(piles)]. |
| Tool | Binary Search on Answer. |
Dry run trace:
| lo | hi | mid (speed) | Hours taken | Check h = 8 | Action |
|---|---|---|---|---|---|
| 1 | 11 | 6 | 1+1+2+2 = 6 | 6 ≤ 8 OK | hi = mid = 6 |
| 1 | 6 | 3 | 1+2+3+4 = 10 | 10 > 8 FAIL | lo = mid + 1 = 4 |
| 4 | 6 | 5 | 1+2+2+3 = 8 | 8 ≤ 8 OK | hi = mid = 5 |
| 4 | 5 | 4 | 1+2+2+3 = 8 | 8 ≤ 8 OK | hi = mid = 4 |
| 4 | 4 | stop | — | — | Answer = 4 |
public int minEatingSpeed(int[] piles, int h) {
int lo = 1, hi = 0;
for (int p : piles) hi = Math.max(hi, p);
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (hours(piles, mid) <= h) {
hi = mid; // mid feasible hai, aur chhota try karo
} else {
lo = mid + 1; // mid too slow hai, speed badhao
}
}
return lo;
}
private long hours(int[] piles, int k) {
long total = 0;
for (int p : piles) {
total += (p + k - 1) / k; // integer math for ceil(p / k)
}
return total;
}
13.6 Coin Change (DP kaise banta hai)
Problem: Coins ke denominations diye hain. Given amount banane ke liye minimum kitne coins lagenge?
Test case: coins = [1,2,5], amount = 11 → 3 (5 + 5 + 1)
| Thinking Ladder | Is problem me |
|---|---|
| Observe + Manual | Greedy kyun fail hota hai: coins = [1,3,4], amount = 6. Greedy bada coin lega: 4+1+1 = 3 coins. Par optimal 3+3 = 2 coins! Matlab saare combinations explore karne padenge. |
| Brute force | Recursion: solve(amount) = 1 + min(solve(amount - c)) har coin c ke liye. solve(11) = 1 + min(solve(10), solve(9), solve(6)). Exponential O(coinsamount). |
| Waste analysis | solve(9) ya solve(6) baar-baar recalculate hota hai → same subproblems. |
| Click moment | DP ke 4 steps: State dp[a] = amount a ke liye min coins. Transition dp[a] = 1 + min(dp[a - c]) jahan a - c ≥ 0. Base dp[0] = 0. Final dp[amount] (unreached ho to -1). |
| Tool | Dynamic Programming (memoization / tabulation). |
Dry run trace:
| a | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| dp[a] | 0 | 1 | 1 | 2 | 2 | 1 | 2 | 2 | 3 | 3 | 2 | 3 |
public int coinChange(int[] coins, int amount) {
int INF = amount + 1;
int[] dp = new int[amount + 1];
Arrays.fill(dp, INF);
dp[0] = 0; // base: 0 amount needs 0 coins
for (int a = 1; a <= amount; a++) {
for (int c : coins) {
if (a - c >= 0) {
dp[a] = Math.min(dp[a], dp[a - c] + 1);
}
}
}
return dp[amount] == INF ? -1 : dp[amount];
}
13.7 Number of Islands (Grid + DFS)
Problem: 2D grid me '1' = zameen, '0' = paani. Connected zameen (horizontal / vertical) milkar ek island banati hai. Total islands count karo.
Test case: Grid: 1100 / 1100 / 0010 / 0001 → 3 islands
| Thinking Ladder | Is problem me |
|---|---|
| Observe + Manual | Top-left ka 2x2 block = Island 1. Beech ka akela (2,2) = Island 2. Bottom-right ka akela (3,3) = Island 3. Har naye 1 pe maine count badhaya aur us se jude saare 1s ko visit karke sink / mita diya, taaki dobara count na ho. |
| Tool | DFS traversal + in-place visited mutation (1 → 0). |
public int numIslands(char[][] grid) {
int count = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == '1') {
count++;
dfs(grid, r, c); // poore island ko '0' bana do
}
}
}
return count;
}
private void dfs(char[][] g, int r, int c) {
// Boundary check + water check
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != '1') {
return;
}
g[r][c] = '0'; // mark visited
dfs(g, r + 1, c); // down
dfs(g, r - 1, c); // up
dfs(g, r, c + 1); // right
dfs(g, r, c - 1); // left
}
r < 0 || c < 0 || r ≥ R || c ≥ C) hamesha recursive function ki sabse pehli line me likho.13.8 Subsets (Backtracking)
Problem: Array ke saare possible unique subsets (power set) return karo.
Test case: [1,2,3] → [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] (total 8)
| Thinking Ladder | Is problem me |
|---|---|
| Observe + Manual | Har element ke paas exactly 2 choices: include ya exclude. 3 elements → 23 = 8 subsets. Har state khud ek valid subset hai. Har node se aage sirf bade index wale elements jodte hain, taaki [2,1] duplicate na bane. |
| Tool | Backtracking (Choose → Explore → Undo). |
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
go(nums, 0, new ArrayList<>(), res);
return res;
}
private void go(int[] nums, int start, List<Integer> path, List<List<Integer>> res) {
res.add(new ArrayList<>(path)); // har intermediate node ek valid subset
for (int i = start; i < nums.length; i++) {
path.add(nums[i]); // 1. Choose
go(nums, i + 1, path, res); // 2. Explore
path.remove(path.size() - 1); // 3. Undo (backtrack)
}
}
Practice Plan
Sahi tareeka (high retention)
- Pattern-wise practice karo, random kabhi nahi. Ek week me ek pattern pakdo aur uske 8–10 diverse problems solve karo.
- Har problem ke baad reflection likho: pattern kya tha aur test case me use kaise pehchana.
- Solution dekhne ke baad: tab close karke khud bina dekhe code type karo.
- Spaced revision: purani solved problems 7 din baad dubara open karke logic trace karo.
- Quality over quantity: 100 problems ratta maarne se 40 foundational problems ki deep understanding 100x behtar hai.
Recommended problems (Thinking Ladder apply karo)
| # | Problem | Level | Core pattern hint (pehle mat dekho!) |
|---|---|---|---|
| 1 | Two Sum II | Easy | Sorted input + target pair → Two Pointers |
| 2 | Best Time to Buy and Sell Stock | Easy | Running minimum price track karo → single pass Greedy |
| 3 | Longest Substring Without Repeating Characters | Medium | Dynamic unique window → Sliding Window + Set |
| 4 | 3Sum | Medium | Sort + ek fix karo + baaki pe Two Pointers (duplicates skip) |
| 5 | Daily Temperatures | Medium | Next greater element → Monotonic Decreasing Stack |
| 6 | Search in Rotated Sorted Array | Medium | Modified Binary Search (kaunsa half strictly sorted hai) |
| 7 | Top K Frequent Elements | Medium | Frequency count + Min-Heap of size K |
| 8 | House Robber | Medium | Adjacent pick disallowed → DP (include / exclude) |
| 9 | Course Schedule | Medium | Prerequisite graph → Topological Sort / cycle detection |
| 10 | Permutations | Medium | All orderings → Backtracking with visited tracking |
(1) Is problem ka core pattern kya tha?
(2) Kis observation ya keyword se pattern click hua?
(3) Brute force me waste kya tha aur kis tool ne use remove kiya?
One Page Quick Revision
Har problem pe ye 10 sawal poochho:
5 core mantras
| # | Mantra | Matlab |
|---|---|---|
| 1 | "Pehle haath se paper pe, phir keyboard se IDE me." | Jab tak paper pe logic clear na ho, keyboard mat chhuo. |
| 2 | "Brute force → Bottleneck → Optimize." | Pehle working baseline, phir waste dhoond ke tool lagao. |
| 3 | "Constraints batate hain technique." | Input size n pehle hi target complexity fix kar deta hai. |
| 4 | "Search slow? HashMap. Sorted? Binary Search / Two Pointers." | Bottleneck match karke tool uthao. |
| 5 | "Chhote input se pattern hamesha saaf dikhta hai." | 2–3 elements pe dry run karne se rule turant unlock hota hai. |
Ek nazar me: n → complexity
| n ≤ 10 | n ≤ 20 | n ≤ 500 | n ≤ 5,000 | n ≤ 10⁵ | n ≤ 10⁶ | n ≥ 10⁹ |
|---|---|---|---|---|---|---|
| O(n!) | O(2n) | O(n3) | O(n2) | O(n log n) | O(n) | O(log n) / O(1) |
Problem Solving Worksheet (photocopy karo)
A4 printout ya notebook me solve karne ke liye template. Is worksheet ko print karke har tough problem pe manually bharo.
Step 1-2: Samjho
Input: ____________________________________ Output: ____________________________________ n: ____________
Sorted? [ ] Duplicates? [ ] Negatives? [ ] Empty allowed? [ ] Target complexity: ______________
Step 3: Test case ko haath se solve karo (trace yahan likho)
Fill-in-the-blank (7 sentences)
- Input ____________________ hai aur output ____________________ chahiye.
- Maine ____________________ kaam baar-baar kiya aur ____________________ yaad rakha.
- Brute force ____________________ hai, complexity ____________________, constraints ____________________ ⇒ TLE / chalega.
- Waste: __________________________________________________ baar-baar repeat ho raha hai.
- Tool / data structure: __________________________________________________
- Ye 100% kaam karega kyunki __________________________________________________
- Edge cases: __________________ , __________________ , __________________
Step 7: Dry run table
Reflection (solve hone ke baad)
Core pattern: ____________________________________________________________________
Kis keyword / observation se click hua: ____________________________________________
Waste kya tha aur kis tool ne hataya: ___________________________________________
Revise on (7 din baad): ____________________________