DSA Logic Building Playbook

📖 Master Diagnostic Edition

Code nahi, logic banana seekho — Test case se optimal code tak

Test case se optimized code tak: 7-step framework, Thinking Ladder, constraint & keyword cheat-tables, 11 pattern templates, 8 fully worked examples (Java) aur ek blank worksheet.
Source: github.com/Kali-Prem/dsa-logic-building-playbook (MIT License) Official Logic Playbook
01

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.

RuleKya matlab hai
01 Code se pehle logicKeyboard tab chhuo jab paper pe pata ho ki exact kya likhna hai.
02 Seedha optimal nahi aataPehle working brute force banao, phir bottleneck dekh ke improve karo.
03 Test case sabse bada hint haiInput se output kaise bana, haath se pen-paper pe trace karke dekho.
04 Constraints batate hain techniqueProblem ka n kitna bada hai, wahi bata deta hai kaunsa algorithm chalega.
05 Problem naya nahi hota, pattern purana hota haiDSA me ginke sirf 15–20 fundamental patterns hote hain.
02

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.

1 Rephrase 1 min
2 I/O + Bounds 1 min
3 Trace on paper 3 min
4 Brute force 2 min
5 TLE check 1 min
6 Fix waste 3 min
7 Edge + Code 5 min
StepKya karna haiTimeKey focus
1Problem dobara apne words me bolo1 minMisunderstandings clear karo
2Input, Output, Constraints likho1 minBounds aur data types check karo
3Test case ko haath se solve karo3 minMental steps observe karo
4Brute force socho aur complexity nikalo2 minBase working solution
5Constraints dekh ke target complexity decide karo1 minO(n), O(n log n) target fix
6Pattern pehchano, brute force ko optimize karo3 minWaste hatao using right tool
7Edge cases check karo, phir code likho5 minOff-by-one, empty input safety
💡
Flow Rule: Step 5 pe agar brute force constraints me pass ho raha hai to seedha Step 7 pe jao. Agar TLE aayega to Step 6 (waste hatana) zaroori hai.
03

Problem Ko Samjho

Problem padhte hi apne aap se ye 5 basic sawal poochho:

  1. Input kya hai? Array, string, number, tree, graph ya matrix?
  2. Output kya chahiye? Single number, boolean true/false, index, array, count, min/max value?
  3. Kya input sorted hai? Agar sorted ho to Binary Search ya Two Pointers ke 90% chances hote hain.
  4. Duplicates, negatives, empty input allowed hain?
  5. 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 typeAksar kaunsi technique lagti hai
Sirf true / falseHashing, Two Pointers, Dynamic Programming, Graph Traversal
Count of waysDP (combinations), Combinatorics, Backtracking
Min / Max valueDynamic Programming, Greedy, Binary Search on Answer
Saare subsets / permutations / combinationsBacktracking, Recursion (decision tree)
Index ya specific pairHashMap, Two Pointers, Binary Search
Shortest path / min stepsBFS (unweighted), Dijkstra (weighted)
Top K / K-th elementHeap (PriorityQueue), Quickselect, Sorting
04

Test Case Se Logic Kaise Nikale

⚠️
Ye wo critical step hai jo 90% log jaldbazi me skip karte hain, aur isi wajah se unka logic kabhi nahi banta.

Method: Insaan ki tarah solve karo (bina computer, bina code)

  1. Sample input kagaz pe likho.
  2. Output tak kaise pahunche, step by step likho — dimag me nahi, paper pe.
  3. Poochho: "Maine kaunsa kaam baar baar kiya?" → wahi tumhara loop hai.
  4. Poochho: "Pichhle step ka kya yaad rakha?" → wahi tumhara variable / data structure hai.
  5. 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.
🎯
Pattern nikla: Agar pichhla running sum negative ho jaye to use chhod do, warna aage jodte jao. Yahi Kadane's Algorithm hai — tumne bina ratte khud derive kar liya!
Java
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.

05

Test Case Padhne Ki 6 Techniques

Jab logic bilkul na soojh raha ho, sample test case ko in 6 nazron se dekho:

#NazariyaKya dekhna haiKaunse problems me kaam aata hai
1Haath se trace karoTumhari aankhein aur dimag pen-paper pe kya steps follow kar rahe hain?Greedy, Two Pointers, Simulation
2Kya badla, kya sameKaunse elements apni jagah pe hain aur kaunse shift hue?Array partition, in-place sorting, rotation
3Chhota bana ke dekhon = 1, 2, 3, 4 ke answers paper pe manually likhoRecurrence relation, DP base cases, math sequences
4Ulta chaloFinal output se input ki taraf reverse calculate karoBinary Search on Answer, Prefix Sum + Map lookups
5Extreme casesSab identical, already sorted, negatives, extreme boundsGreedy assumptions test karna, edge bug discovery
6Counter-example banaoKhud aisa input design karo jo tumhari trick ko break kareGreedy confirm ya reject karne ke liye
💡
Technique 3 in action: Maan lo tumne dekha: n=1 → 1, n=2 → 2, n=3 → 3, n=4 → 5, n=5 → 8. Sequence: 1, 2, 3, 5, 8 — har number pichhle do ka sum hai! Bina formula soche Fibonacci recurrence mil gayi.

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.

  1. "Input ____________ hai aur output ____________ chahiye."
  2. "Haath se paper pe karte waqt maine ____________ kaam baar-baar kiya, aur ____________ yaad rakha."
  3. "Brute force solution ____________ hai (complexity ____________), par constraints ____________ hain, isliye ye TLE dega / chalega."
  4. "Brute force me ____________ computation baar-baar repeat ho raha hai (waste)."
  5. "Is waste ko hatane ke liye main ____________ (tool / data structure) use kar sakta hoon."
  6. "Ye tool 100% kaam karega kyunki ____________."
  7. "Edge cases jo handle karne hain: ____________, ____________, ____________."
06

Brute Force Hamesha Pehle

Brute force ek safety net hai. Ye prove karta hai ki tumhe problem 100% samajh aa chuki hai.

Problem ka shabdBrute force kaisa hogaComplexity
"Saari possibilities try karo"Nested loops ya recursiondepends
"Har pair check karo"Do nested loopsO(n2)
"Har subarray check karo"Start, end loops (+ sum loop)O(n2) ya O(n3)
"Har subset check karo"Include / exclude recursionO(2n)
⚠️
Brute force ke baad ek hi sawal: Is brute force me kaunsa kaam baar baar ho raha hai ya bina wajah repeat ho raha hai? Wahi tumhara bottleneck hai, aur har optimal solution usi waste ko hatane se nikalta hai!
07

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 sizeAllowed complexitySpeedKaunsi techniques lag sakti hain
n ≤ 10O(n!)Extremely slowPermutations, Backtracking
n ≤ 20O(2n)ExponentialSubsets generation, Bitmask DP, Backtracking
n ≤ 500O(n3)Cubic3 nested loops, Floyd-Warshall, 3D DP
n ≤ 5,000O(n2)Quadratic2 nested loops, 2D DP
n ≤ 105O(n log n)Linearithmic (optimal)Sorting, Heap, Binary Search, Divide & Conquer
n ≤ 106O(n)Linear (fast)Hashing, Two Pointers, Sliding Window, Prefix Sum
n ≥ 109O(log n) ya O(1)Lightning fastBinary Search, math formula, bit manipulation
⏱️
Thumb rule: Competitive programming aur online judges (LeetCode) pe 1 second me lagbhag 108 operations allow hote hain.

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.
08

Keyword Se Technique Pehchano

Problem statement ke words me hi solution ka hint chhupa hota hai.

Master pattern decision tree

InputDecision
Array / StringSorted? → Two Pointers / Binary Search
Array / StringUnsorted + contiguous subarray, no negatives → Sliding Window
Array / StringUnsorted + contiguous, sum = K ya negatives → Prefix Sum + Map
Array / StringPairs / lookup → HashMap / HashSet
Array / StringNext greater / Top K → Monotonic Stack / Heap
OptimizationOverlapping subproblems → Dynamic Programming
OptimizationLocally best choice → Greedy (sort first)
OptimizationMonotonic feasibility → Binary Search on Answer
Tree / GraphShortest path / level order → BFS (Queue)
Tree / GraphPath / island sink → DFS (Recursion)
Tree / GraphPrerequisites → Topological Sort
All subsets / pathsBacktracking tree

Direct keyword to pattern table

Problem me ye keyword / requirement dikheYe technique dimag me lao
Sorted array, pair ya triplet dhoondnaTwo Pointers, Binary Search
Subarray / substring, contiguous, max/min lengthSliding Window
Subarray sum, range sum query multiple timesPrefix Sum
Duplicate, frequency count, "pehle dekha hai?", pair sumHashMap / HashSet
Sorted + search, "minimum X jo condition satisfy kare"Binary Search (on answer pattern)
Brackets matching, next greater element, undo, nestedStack, Monotonic Stack
Top K largest / smallest, running median, merge K listsHeap / PriorityQueue
Linked list me cycle, middle node dhoondnaFast & Slow Pointers (Floyd's Cycle)
Tree traversal, height, max path sumDFS, BFS, Tree Recursion
Shortest path, level-order, min stepsBFS
Connected components, islands, clustersDFS, BFS, Union-Find (DSU)
Dependencies, prerequisite ordering (course schedule)Topological Sort (Kahn's / DFS)
Saare subsets, permutations, combinationsBacktracking
Har step pe locally best choice, intervals, schedulingGreedy (aksar sorting ke baad)
Count ways, min cost, max profit, overlapping subproblemsDynamic Programming
Prefix match, dictionary words, autocompleteTrie (Prefix Tree)
Bit operations, single non-duplicate, power of 2Bit Manipulation
Intervals merge ya overlap checkSort by start time, phir merge loop
09

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.
Java
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)).
Java
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.
Java
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]
💡
Pro trick: "Subarray sum = K" dhoondne ke liye Prefix Sum ko HashMap ke saath pair kiya jata hai.

9.4 HashMap

  • Core idea: Expensive O(n) linear search ko O(1) lookup me badal do. "Pehle kaunsa element dekha tha" yaad rakho.
Java
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.
Java
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;
🎯
Binary Search on Answer: "Minimum X jo condition satisfy kare" → X ki range [minPossible, maxPossible] pe binary search lagao aur ek alag helper boolean check(X) likho. Feasible mila to ans = mid; hi = mid - 1, warna lo = mid + 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.
Java
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.
Java
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 stepsSawal
1. Statedp[i] ka exact matlab kya hai? Pehle plain words me likho.
2. Transitiondp[i] ko pichhle calculated subproblems se kaise compute karein?
3. Base caseSabse chhota / trivial answer kya hai (dp[0])?
4. Final answerAnswer table me kahan milega (dp[n] ya max(dp))?
1. Brute force recursion → 2. Memoization (top-down) → 3. Tabulation (bottom-up) → 4. Space optimization
⚠️
Overlapping subproblems nahi hain to ye DP nahi, Divide & Conquer hai (MergeSort, Binary Search).

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.
Java
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.
Java
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
10

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

StepSawalActionTrap
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 Constraintsn kitna bada hai? Corner cases kya hain?Negatives, empty, duplicates note karo. Target complexity fix.Constraints ignore karna → TLE.

Phase 2 — Manual observation

StepSawalActionTrap
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

StepSawalActionTrap
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

StepSawalActionTrap
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

⚡
Ye is poori playbook ka sabse powerful shortcut hai. Brute force ka bottleneck pehchano aur seedha right tool uthao.
#Brute force me waste / bottleneckExact ilaaj (tool)Complexity dropExample problems
1Baar-baar linear search: "ye element pehle dekha tha?"HashMap / HashSetO(n) → O(1)Two Sum, Subarray Sum Equals K
2Har query pe range sum / product baar-baar calculatePrefix Sum / Suffix arrayO(n) → O(1)Range Sum Query, Product Except Self
3Har pair check, jabki array sorted hai ya sort ho sakta haiSort + Two PointersO(n2) → O(n)3Sum, Container With Most Water
4Window ka common part har step pe recalculateSliding WindowO(n2) → O(n)Longest Substring Without Repeating
5Monotonic sequence me ek-ek step aage badhnaBinary Search (on answer)O(n) → O(log n)Koko Bananas, Search Rotated Array
6Same subproblem recursion tree me baar-baar solveDynamic ProgrammingO(2n) → O(n)Coin Change, Climbing Stairs
7Pichhle elements ka order yaad rakhna ya matching pairs (LIFO)Monotonic StackO(n2) → O(n)Daily Temperatures, Valid Parentheses
8Har step pe continuous dynamic min / max dhoondnaHeap / PriorityQueueO(n) → O(log n)Top K Frequent, Merge K Sorted Lists
9Random unordered intervals me overlap checkSort by start timeO(n2) → O(n log n)Merge Intervals, Meeting Rooms
11

Edge Cases Checklist

Final code submit karne se pehle ye 9 checks zaroor verify karo (tick lagao):

12

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
HaanNahi—Saare combinations / possibilities ka loop socho
HaanHaanNahiSeedha submit (pehle edge cases dekh lo)
HaanHaanHaan — search slowHashMap / HashSet
HaanHaanHaan — range slowPrefix Sum
HaanHaanHaan — overlappingDynamic Programming
HaanHaanHaan — monotonicBinary Search on Answer
HaanHaanHaan — sorted pairTwo Pointers

Situation-wise action plan

SituationImmediate action plan
Kuch samajh nahi aa rahaSabse 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 rahaSection 8 ka keyword-technique cheat-sheet dekho.
Do approaches me confusionDono 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 rahiPehle brute recursion likho; jo function parameters change ho rahe hain, wahi DP state hai.
15–20 min se stuck hoSolution dekh lo! Samjho kyun aur kaise kaam karta hai, phir 2 din baad bina dekhe scratch se likho.
13

Worked Examples — Step by Step

Har example me wahi Thinking Ladder laga hai: test case observation se shuru, clean Java code pe khatam.

#ProblemCore patternTimeSpace
13.1Product of Array Except SelfPrefix & Suffix ProductO(n)O(1)
13.2Subarray Sum Equals KPrefix Sum + HashMapO(n)O(n)
13.3Container With Most WaterTwo Pointers (greedy choice)O(n)O(1)
13.4Merge IntervalsSort by start + GreedyO(n log n)O(n)
13.5Koko Eating BananasBinary Search on AnswerO(n log max)O(1)
13.6Coin ChangeBottom-up DPO(amount × coins)O(amount)
13.7Number of Islands2D Grid DFS (in-place sink)O(R × C)O(R × C)
13.8SubsetsBacktracking (decision tree)O(n × 2n)O(n)

13.1 Product of Array Except Self

Tags: Arrays, Prefix/Suffix Product  |  Target: O(n) time, O(1) extra space

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 LadderIs problem me
Observe + ManualIndex 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 forceHar index ke liye doosra loop chala kar baaki array multiply karo → O(n2).
Waste analysisLeft 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!
ToolPrefix Product (left pass) aur Suffix Product (right pass).

Dry run trace:

inums[i]left (prefix)right (suffix)answer[i]
0112×3×4 = 2424
1213×4 = 1212
231×2 = 248
341×2×3 = 616
Java
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;
}
💡
Key lesson: Jab bhi "baaki sab elements" ya "current ko chhodke" pucha jaye, problem ko hamesha Left aur Right do hisson me split kar lo.

13.2 Subarray Sum Equals K

Tags: Arrays, Prefix Sum, HashMap  |  Target: O(n) time, O(n) space

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 LadderIs problem me
Observe + ManualSaare subarrays: [1]=1, [1,2]=3 OK, [1,2,3]=6, [2]=2, [2,3]=5, [3]=3 OK. Total = 2.
Brute forceHar start i aur end j ke liye sum calculate karo → O(n2).
Waste analysisPrefix sum se range sum O(1) me nikal jata hai, par hum phir bhi saare (i, j) pairs manually check kar rahe hain.
Click momentP[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?"
ToolPrefix Sum + HashMap (prefix value → frequency).

Dry run trace:

xprefixneed = prefix - kseen me need ka counttotalUpdated seen
111 - 3 = -200{0:1, 1:1}
233 - 3 = 011{0:1, 1:1, 3:1}
366 - 3 = 312{0:1, 1:1, 3:1, 6:1}
Java
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;
}
💡
Key lesson: Negative numbers allowed hon to standard Sliding Window fail ho jati hai (monotonicity tootne se). Tab hamesha Prefix Sum + HashMap lagao. Dry run me seen = {0:1} se shuru hota hai.

13.3 Container With Most Water

Tags: Two Pointers, Greedy Choice  |  Target: O(n) time, O(1) space

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 LadderIs problem me
Observe + ManualArea = width × min(height[l], height[r]). Index 1 (h=8) aur Index 8 (h=7): width = 7, min = 7, area = 49.
Brute forceHar possible pair (i, j) check karo → O(n2).
Click momentSabse 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.
ToolTwo Pointers (greedy pointer movement).

Dry run trace:

lrh[l]h[r]widthareaAction
081788h[l] < h[r] → l++
1887749h[r] < h[l] → r--
1783618h[r] < h[l] → r--
1688540Equal → koi bhi move
Java
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;
}
💡
Key lesson: Two Pointers ka core intuition ye prove karna hai: "kaunsa pointer move karne se hum koi bhi possible optimal answer miss nahi kar rahe." Maximum area = 49.

13.4 Merge Intervals

Tags: Intervals, Sorting, Greedy  |  Target: O(n log n) time, O(n) space

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 LadderIs 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 analysisAgar input random unsorted aaye jaise [[8,10],[1,3],[2,6]], to "pichhla-naya" rule toot jayega!
ToolIntervals ko start time se sort karo. Sorting ke baad overlap sirf previous interval ke saath hi possible hai.
Java
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()][]);
}
💡
Key lesson: Intervals ke 95% problems hamesha "Sort by start time" se shuru hote hain.

13.5 Koko Eating Bananas

Tags: Binary Search on Answer, Monotonicity  |  Target: O(n log(max(piles)))

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 LadderIs problem me
Observe + ManualSpeed 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 forceSpeed k = 1, 2, 3, ... linear try karo. Max banana 109 ho sakta hai → TLE.
Click momentSpeed 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)].
ToolBinary Search on Answer.

Dry run trace:

lohimid (speed)Hours takenCheck h = 8Action
11161+1+2+2 = 66 ≤ 8 OKhi = mid = 6
1631+2+3+4 = 1010 > 8 FAILlo = mid + 1 = 4
4651+2+2+3 = 88 ≤ 8 OKhi = mid = 5
4541+2+2+3 = 88 ≤ 8 OKhi = mid = 4
44stop——Answer = 4
Java
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;
}
💡
Key lesson: "Minimum X jo condition satisfy kare" ho to 3 cheezein likho: (1) possible answer ki range [min, max], (2) boolean isValid(X) function, (3) monotonic direction (X valid hai to X+1 bhi valid).

13.6 Coin Change (DP kaise banta hai)

Tags: Dynamic Programming, Bottom-up  |  Target: O(amount × coins.length)

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 LadderIs problem me
Observe + ManualGreedy 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 forceRecursion: 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 analysissolve(9) ya solve(6) baar-baar recalculate hota hai → same subproblems.
Click momentDP 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).
ToolDynamic Programming (memoization / tabulation).

Dry run trace:

a01234567891011
dp[a]011221223323
Java
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];
}
💡
Key lesson: DP hamesha recursion se shuru hota hai. Pehle brute recursive equation likho, overlapping branches pehchano, phir table bana kar store karo.

13.7 Number of Islands (Grid + DFS)

Tags: 2D Grid, Graphs, DFS  |  Target: O(R × C) time, O(R × C) space

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 LadderIs problem me
Observe + ManualTop-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.
ToolDFS traversal + in-place visited mutation (1 → 0).
Java
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
}
💡
Key lesson: Grid problems me boundary condition (r < 0 || c < 0 || r ≥ R || c ≥ C) hamesha recursive function ki sabse pehli line me likho.

13.8 Subsets (Backtracking)

Tags: Backtracking, Recursion, Combinatorics  |  Target: O(n × 2n)

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 LadderIs problem me
Observe + ManualHar 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.
ToolBacktracking (Choose → Explore → Undo).
Java
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)
    }
}
💡
Key lesson: Backtracking ke 3 pillars: Choose, Explore, Undo. Aur dhyan rakho ki answer kab collect karna hai — har intermediate node pe ya sirf leaf base case pe.
14

Practice Plan

Sahi tareeka (high retention)

  1. Pattern-wise practice karo, random kabhi nahi. Ek week me ek pattern pakdo aur uske 8–10 diverse problems solve karo.
  2. Har problem ke baad reflection likho: pattern kya tha aur test case me use kaise pehchana.
  3. Solution dekhne ke baad: tab close karke khud bina dekhe code type karo.
  4. Spaced revision: purani solved problems 7 din baad dubara open karke logic trace karo.
  5. Quality over quantity: 100 problems ratta maarne se 40 foundational problems ki deep understanding 100x behtar hai.

Recommended problems (Thinking Ladder apply karo)

#ProblemLevelCore pattern hint (pehle mat dekho!)
1Two Sum IIEasySorted input + target pair → Two Pointers
2Best Time to Buy and Sell StockEasyRunning minimum price track karo → single pass Greedy
3Longest Substring Without Repeating CharactersMediumDynamic unique window → Sliding Window + Set
43SumMediumSort + ek fix karo + baaki pe Two Pointers (duplicates skip)
5Daily TemperaturesMediumNext greater element → Monotonic Decreasing Stack
6Search in Rotated Sorted ArrayMediumModified Binary Search (kaunsa half strictly sorted hai)
7Top K Frequent ElementsMediumFrequency count + Min-Heap of size K
8House RobberMediumAdjacent pick disallowed → DP (include / exclude)
9Course ScheduleMediumPrerequisite graph → Topological Sort / cycle detection
10PermutationsMediumAll orderings → Backtracking with visited tracking
📝
Har problem ke baad notebook me ye 3 lines likho:
(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?
15

One Page Quick Revision

Har problem pe ye 10 sawal poochho:

5 core mantras

#MantraMatlab
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 &le; 10n &le; 20n &le; 500n &le; 5,000n &le; 10⁵n &le; 10⁶n &ge; 10⁹
O(n!)O(2n)O(n3)O(n2)O(n log n)O(n)O(log n) / O(1)
🌟
Yaad rakho: Logic pe focus karo, code khud-ba-khud ban jayega.
16

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.

Problem Solving • Logic Building Worksheet
Problem
Date
Time spent

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)

[ Pen-paper test case execution area — observe which elements repeat, what variables are stored ]

Fill-in-the-blank (7 sentences)

  1. Input ____________________ hai aur output ____________________ chahiye.
  2. Maine ____________________ kaam baar-baar kiya aur ____________________ yaad rakha.
  3. Brute force ____________________ hai, complexity ____________________, constraints ____________________ ⇒ TLE / chalega.
  4. Waste: __________________________________________________ baar-baar repeat ho raha hai.
  5. Tool / data structure: __________________________________________________
  6. Ye 100% kaam karega kyunki __________________________________________________
  7. Edge cases: __________________ , __________________ , __________________

Step 7: Dry run table

[ Iteration trace grid: Pointer positions / Running state / Intermediate answers ]

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): ____________________________