You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Day 8 | June 4, 2026 | 20 Problems (18 Easy + 2 Medium) — Resumed after exam-week gap
Catch-up session. Took a 2-week break for finals + capstone polish + LinkedIn launch. Resumed with a deliberate "variety + volume" run across multiple patterns to rebuild momentum. Hit 2x the original 10-problem goal across DP, Bit Manipulation, Prefix Sum, Matrix, Enumeration, Simulation, and SQL — and added 2 Mediums.
Day 9 | June 5, 2026 | 10 Problems (7 Easy + 3 Medium) — Strings + Tree DFS
Day 2 of comeback. Focused on two pattern families: strings (5 problems building from adjacent-pair aggregation to two-pass prefix sums) and tree DFS (5 problems covering all four DFS flavors: read, compare, aggregate, mutate, then composing them for the Medium). Hit the 10-problem mark with strong pattern recognition — the string problems built on yesterday's adjacent-pair templates, and the trees ended with a Medium that explicitly composes two earlier patterns.
Bit Manipulation DP:ans[i] = ans[i>>1] + (i & 1) for popcount in O(n)
Memoization vs bottom-up:@lru_cache is plan B; bottom-up shows you understand dependency order
Bit Manipulation Toolkit
XOR + popcount template:popcount(a ^ b) counts differing bits — Hamming distance, min bit flips
OR-shift identity for subset XOR sum: answer = OR(nums) << (n-1) — half of all subsets have any given bit set
Bitmask as set: 26-bit integer = set of lowercase letters; (word_mask & ~allowed_mask) == 0 for subset check
Adjacent-pair operations:[a | b for a, b in zip(nums, nums[1:])] — generalizes to any pairwise op
Brian Kernighan trick:x &= x - 1 clears the lowest set bit; iteration count = popcount
Sorting & Greedy
Greedy pairing (LC 561): sort, take every even index for max sum-of-mins; exchange argument proves optimality
Counting sort: when value range is bounded (1..100), beats comparison sort at O(n + R)
Set intersection vs two-pointer: sets win on clarity, two-pointer wins on already-sorted input
Permutation & Frequency
Permutation frequency trick (LC 2657): when both arrays are permutations, freq[v] ≤ 2 → "v becomes common" = "freq hits 2"
Increment-then-check pattern:counter[key] += 1; if counter[key] == THRESHOLD: action()
Enumeration & Digit
Digit-symmetric trick: 2-digit symmetric numbers are exactly multiples of 11 in [11, 99]
String vs arithmetic digit extraction:str(x)[:half] generalizes; x // 1000 + x % 1000 // 100 is faster but case-specific
Matrix
Diagonals: odd-n center cell is on both diagonals → subtract once. (i,i) and (i, n-1-i) are canonical indices
Prefix Sum
Store-before-update pattern: record running sum BEFORE adding current element to exclude it from "left of i"
Total trick:rightSum = total - leftSum - nums[i] collapses two passes into one
In-place running sum: read previous (already-cumulative) cell to update current; no extra array needed
itertools.accumulate: Python's superpower for any associative reduction (sum, product, min, max, xor)
Simulation & In-Place Tricks
Bit-packing for O(1) space (LC 1920):cell = old + n*new; decode with % n and // n. Lets you store two values in one cell using base-n encoding
"Stateless map → sum" pattern: when each element transforms independently, sum(f(x) for x in items) replaces explicit loops
The "just a return" recognition: if there's no running state between iterations, list comprehension is the answer
SQL Patterns (4 new)
WHERE filter (LC 1821): simplest SQL primitive; watch for "positive" = > 0 vs "non-negative" = >= 0
CROSS JOIN (LC 2339):CROSS JOIN ... WHERE t1.x != t2.x for all ordered pairs; < for unordered
GROUP BY + COUNT DISTINCT (LC 2356): dedupe BEFORE counting; foundational analytics idiom
Anti-join (LC 2084): three idioms — NOT EXISTS, NOT IN, LEFT JOIN ... IS NULL. Window function MIN(x) OVER (PARTITION BY group) is the elegant alternative for "keep best per group"
Day 9: Strings + Tree DFS Toolkit (10 problems)
String / Pairwise Aggregation
Adjacent-pair template (LC 3110):sum(op(a, b) for a, b in zip(seq, seq[1:])) — same skeleton as yesterday's LC 3173, now with abs(ord(a) - ord(b)) as the op. The template handles sum/max/list of any pairwise computation.
Score as "total variation" — sum of absolute differences across consecutive elements; the same metric used in signal processing and time-series analysis.
String / Filtering
Filter pattern (LC 1119):''.join(c for c in s if predicate(c)). Three implementations: generator + join, hash set lookup, or str.translate() for C-level speed on long inputs.
Critical Python habit: NEVER use += in a loop to build a string — it's O(n²) due to string immutability. Always use list.append + ''.join or a generator.
String / Indexed Iteration
enumerate (LC 2942): when you need BOTH index and value, enumerate(items) beats manual range(len(items)). The indexed-filter pattern: [i for i, x in enumerate(items) if predicate(x)] — distinct from a plain filter that returns values.
String / 2D Coordinates
Manhattan distance + position lookup (LC 3846): build a char → (row, col) dict ONCE, then it's O(1) per query. For sequences with implicit starting state, either prepend the start OR maintain explicit running state.
Connection to LC 3110: Manhattan distance is the 2D version of abs(ord(a) - ord(b)). Same adjacent-pair skeleton, two dimensions instead of one.
String / Prefix Sum / Two-Pass Sweep
Two-pass directional sweep (LC 1769): decompose "sum over all pairs" into separate left-side and right-side contributions. The running update trick: cost += balls per step (every existing ball gets +1 distance as cursor moves).
Same skeleton as yesterday's LC 2574 — only the aggregation function changed (absolute differences instead of subtraction).
Tree DFS — The Four Flavors
DFS to produce a list (LC 94 Inorder): traverse Left → Node → Right; for BSTs this gives sorted output. Iterative version uses explicit stack — required for tree iterator implementations (LC 173 BST Iterator).
DFS to compare two trees (LC 100 Same Tree): parallel recursion with three base cases: both None (match), one None (mismatch), both exist (compare + recurse). Skeleton extends to LC 101 Symmetric, LC 572 Subtree.
DFS to aggregate a value (LC 104 Max Depth): divide-and-conquer skeleton 1 + max(L, R). Change the combine function and you solve dozens of tree problems: count nodes (1 + L + R), sum values (val + L + R), path sum, balance check.
DFS to mutate the tree (LC 226 Invert): swap children at every node. When each node's work is independent of others, traversal order is free — any DFS or BFS works. Python's tuple-swap node.left, node.right = node.right, node.left is the safe simultaneous-assignment idiom.
Tree DFS — Composition (Medium)
Two-phase pattern (LC 1382 Balance BST): Phase 1 inorder → sorted array (uses BST property). Phase 2 recursive build picking middle as root (same divide-and-conquer as binary search). This problem = LC 94 + LC 108 composed. Recognizing pattern composition is the Medium-tier insight.
Overflow-safe middle formula:start + (end - start) // 2 instead of (start + end) // 2. Doesn't matter in Python (unbounded ints) but mandatory in C++/Java.
Debugging Lessons (from real session bugs)
Method name consistency: if you misspell the definition (creat_balanced_bst) but call it correctly (create_balanced_bst), Python's "Did you mean?" error suggests the misspelled one. Always check both directions.
Copy-paste typo on root.left vs root.right: common when typing inorder traversal — the third recursion is root.right, NOT a copy of the first line. Watch for this.
Sign flip in math formulas:(end - start) vs (end + start) — accidentally works for start=0 but breaks for non-zero starts, producing out-of-range indices.
📚 Notes
Each problem file includes:
✅ Understanding the Goal
✅ LAYER 1: Line-by-line code explanation (with heavy inline comments)
✅ LAYER 2: Worked examples with traces
✅ LAYER 3: Key insights & complexity
✅ LAYER 4: Interview variations
✅ LAYER 5: Cheat sheet entry
Patterns Cheat Sheet: See notes/patterns.md
Last Updated: June 5, 2026 | 71 Problems Solved ✅
Next: W3 — Sliding Window & Stack (Medium-difficulty pattern drill); plan to add review days for already-solved problems
About
Record daily study log of leetcode study & coding test