Tensorum
YouTubeশেখা শুরু করুন
১-দিনের revision

প্রতিটি প্রবলেম, revise করার জন্য এক পাতায়

310টি প্রবলেম, প্রতিটির মূল idea, complexity আর এড়ানোর মতো ভুল। ইন্টারভিউয়ের আগের দিন পড়ুন, তারপর পুরো revision card দেখতে যেকোনো প্রবলেম খুলুন।

সমাধানের বিবরণ ইংরেজিতে।

Array

Hashing / Anagram

1. Two SumসহজO(n) · O(n)

Store seen values in a map; look up target − num before inserting num.

⚠ Check the map before inserting the current number, so an element is never paired with itself.

217. Contains DuplicateসহজO(n) · O(n)

A set turns 'have I seen this before?' into O(1).

⚠ Sorting mutates the input — fine here, but worth noting.

242. Valid AnagramসহজO(n) · O(1) — 26 counters

One frequency table: +1 for s, −1 for t, all zeros at the end.

⚠ Unicode input would need a dict instead of a fixed 26-slot array.

350. Intersection of Two Arrays IIসহজO(n + m) · O(min(n, m))

Count the smaller array; consume counts while scanning the other.

⚠ Decrement the count so a value isn't used more times than it appears in both.

268. Missing NumberসহজO(n) · O(1)

missing = n(n+1)/2 − sum(nums).

⚠ The range is 0..n inclusive (n+1 values), not 1..n.

136. Single NumberসহজO(n) · O(n) for the set

2·sum(set(nums)) − sum(nums) = the single value (XOR also works).

⚠ XOR of all values gives O(1) extra space: pairs cancel to 0.

49. Group AnagramsমাঝারিO(n · k) with counts (O(n · k log k) with sorting) · O(n · k)

Key = sorted word (or letter-count tuple); group by key.

⚠ Lists aren't hashable — convert the count array to a tuple.

128. Longest Consecutive SequenceমাঝারিO(n) · O(n)

Only expand from run starts (num − 1 not in set).

⚠ Without the 'is it a start?' check the algorithm degrades to O(n²).

Prefix Sum

238. Product of Array Except SelfমাঝারিO(n) · O(1) extra (output excluded)

answer[i] = prefix_product[i] × suffix_product[i].

⚠ Dividing the total product breaks on zeros.

560. Subarray Sum Equals KমাঝারিO(n) · O(n)

count += seen[prefix − k], then record prefix.

⚠ Sliding window doesn't work — values can be negative.

523. Continuous Subarray SumমাঝারিO(n) · O(min(n, k))

Same prefix remainder twice, ≥ 2 apart ⇒ a good subarray.

⚠ Store only the first index of each remainder — overwriting shortens the gap.

Two Pointers

202. Happy NumberসহজO(log n) per step · O(1)

Floyd's cycle detection on the digit-square sequence.

⚠ A set of seen values also works, at O(k) memory.

88. Merge Sorted ArrayসহজO(m + n) · O(1)

Three pointers, filling nums1 from the end.

⚠ Filling from the front would overwrite elements of nums1 you haven't placed yet.

283. Move ZeroesসহজO(n) · O(1)

Two pointers: swap the next non-zero into the first zero slot.

⚠ Order of the non-zero elements must be preserved — swapping keeps it.

27. Remove ElementসহজO(n) · O(1)

Keep-if-not-val with a write index.

⚠ Order beyond the first k elements is irrelevant.

125. Valid PalindromeসহজO(n) · O(1)

Two pointers that skip non-alphanumerics.

⚠ Keep the left < right guard inside the skip loops so they can't cross.

15. 3SumমাঝারিO(n²) · O(n)

Fix one, two-sum the rest with a hash set; dedupe via sorted tuples.

⚠ Without deduplication the same triplet appears many times.

16. 3Sum ClosestমাঝারিO(n²) · O(1)

Sort + two pointers, tracking the smallest |target − sum|.

⚠ Return the sum, not the difference.

18. 4SumমাঝারিO(n³) · O(1) extra

Two fixed loops + two pointers, skipping duplicates at each level.

⚠ Skip duplicates for i, j, left and right — missing any produces repeated answers.

11. Container With Most WaterমাঝারিO(n) · O(1)

Move the shorter line inward.

⚠ Moving the taller side can never help — that's the proof of correctness.

31. Next PermutationমাঝারিO(n log n) here (O(n) if the tail is reversed instead of sorted) · O(1)

Find the pivot, swap with the next-larger tail value, sort the tail.

⚠ The tail is descending, so reversing it is enough — sorting works but is slower.

80. Remove Duplicates from Sorted Array IIমাঝারিO(n) · O(1)

Keep nums[i] unless it equals nums[insert_index − 2].

⚠ Compare against the write area, not the read area — that's what limits copies to two.

189. Rotate ArrayমাঝারিO(n) · O(1)

Reverse all, reverse first k, reverse the rest.

⚠ k can exceed n — take k % n first.

75. Sort ColorsমাঝারিO(n) · O(1)

low / mid / high pointers partition into 0s, 1s, 2s in one pass.

⚠ Don't increment mid after swapping with high.

42. Trapping Rain WaterকঠিনO(n) · O(1) with two pointers

water[i] = min(maxLeft, maxRight) − height[i].

⚠ The pointer on the lower side is safe to resolve; the other side's max can only be higher.

Kadane

53. Maximum SubarrayমাঝারিO(n) · O(1)

A negative prefix never helps a future subarray — reset it to 0.

⚠ Update max_sum before resetting, otherwise an all-negative array returns 0 instead of its largest element.

Matrix

48. Rotate ImageমাঝারিO(n²) · O(1)

Transpose, then mirror each row.

⚠ Start the transpose inner loop at j = i, or every pair is swapped twice (back to the original).

73. Set Matrix ZeroesমাঝারিO(m·n) · O(1) in the final version

Use row 0 / column 0 as markers, plus a col0 flag.

⚠ Process row 0 and column 0 last, or the markers get destroyed.

54. Spiral MatrixমাঝারিO(m·n) · O(1) extra

Four shrinking boundaries; guard the bottom and left passes.

⚠ Without the top ≤ bottom and left ≤ right checks, a single remaining row or column is read twice.

36. Valid SudokuমাঝারিO(81) · O(81)

One set of descriptive keys for rows, columns and boxes.

⚠ Only check filled cells — the board doesn't need to be solvable.

289. Game of LifeমাঝারিO(m·n) · O(1)

In-place state encoding: −1 (dies) and 2 (born).

⚠ board.copy() is shallow — it doesn't protect the rows; the encoding is what makes it correct.

Sorting

56. Merge IntervalsমাঝারিO(n log n) · O(n)

Sort by start; extend or append.

⚠ Touching intervals like [1,4] and [4,5] count as overlapping.

Cyclic Sort / Index Marking

287. Find the Duplicate NumberমাঝারিO(n) · O(1)

Floyd's cycle detection on index → value pointers.

⚠ The 'do … while' first step matters: both start at nums[0].

41. First Missing PositiveকঠিনO(n) · O(1) in the final version

Use indices as a presence map (sign marks presence).

⚠ Use abs() when reading values — they may already be negated.

Counting Sort

274. H-IndexমাঝারিO(n log n) · O(1)

Sorted descending, h = first i where citations[i] ≤ i.

⚠ A counting-sort version gives O(n).

Moore Voting

169. Majority ElementসহজO(n) · O(1)

Vote: same → +1, different → −1, zero → new candidate.

⚠ This relies on a majority being guaranteed — otherwise verify with a second pass.

229. Majority Element IIমাঝারিO(n) · O(n)

Count and keep values with count > n // 3.

⚠ Extended Boyer–Moore (two candidates) does it in O(1) space.

Linear Scan

485. Max Consecutive OnesসহজO(n) · O(1)

Running streak, reset on non-1.

⚠ Update the maximum on every step, not only on resets.

Design

380. Insert Delete GetRandom O(1)মাঝারিO(1) average per operation · O(n)

List + index map; delete by swapping with the last element.

⚠ Update the moved element's index before deleting the removed key (order matters when removing the last element).

String

Two Pointers

344. Reverse StringসহজO(n) · O(1)

Swap s[i] with s[n−1−i] for i < n/2.

⚠ Stop at n // 2 or you'll swap everything back.

680. Valid Palindrome IIসহজO(n) · O(1)

On the first mismatch, try both deletions once.

⚠ Only one deletion is allowed — don't recurse with another deletion budget.

392. Is SubsequenceসহজO(|t|) · O(1)

Greedy two-pointer match.

⚠ An empty s is always a subsequence.

151. Reverse Words in a StringমাঝারিO(n) · O(n) for the character list

Trim → reverse everything → reverse each word.

⚠ Collapse repeated spaces between words to a single one.

Palindrome / Expand Around Center

5. Longest Palindromic SubstringমাঝারিO(n²) · O(1)

Expand around centre: odd (i, i) and even (i, i+1).

⚠ Forgetting the even centre misses answers like 'bb'.

String Matching (KMP / Rabin-Karp)

686. Repeated String MatchমাঝারিO(n + m) expected · O(n)

Only ceil(|B|/|A|) or one more repeat can work.

⚠ The additive hash collides often — the character check after a hash match is essential.

Hashing / Frequency

205. Isomorphic StringsসহজO(n) · O(1) — bounded alphabet

Compare 'last seen index' of s[i] and t[i].

⚠ Checking only one direction misses cases like 'ab' → 'aa'.

290. Word PatternসহজO(n) · O(n)

Last-seen index per letter and per word must agree.

⚠ Length mismatch is an immediate False.

Parsing / Conversion

13. Roman to IntegerসহজO(n) · O(1)

If cur < next, add next − cur and skip both.

⚠ Guard i + 1 < len(s) when peeking.

8. String to Integer (atoi)মাঝারিO(n) · O(1)

Strip → sign → digits → clamp.

⚠ Stop at the first non-digit — 'words 987' is 0.

6. Zigzag ConversionমাঝারিO(n) · O(n)

Row index bounces 0 → numRows−1 → 0.

⚠ numRows = 1 must return s unchanged (no bouncing).

38. Count and SayমাঝারিO(total length) · O(total length)

Term n = run-length encoding of term n−1.

⚠ Build the result with a list in Python; repeated string concatenation is slower.

Math

50. Pow(x, n)মাঝারিO(log n) · O(1)

Square the base and halve the exponent; peel off one factor when odd.

⚠ Looping n times is too slow for n ≈ 2³¹.

7. Reverse IntegerমাঝারিO(log x) · O(1)

num = num·10 + x % 10, then range-check.

⚠ Overflow check is required: 1534236469 reversed overflows.

Prefix / Misc

14. Longest Common PrefixসহজO(S) — total characters · O(1)

Shrink a candidate prefix until every word starts with it.

⚠ Return early when the prefix becomes empty.

Sliding Window

76. Minimum Window SubstringকঠিনO(|s| + |t|) · O(Σ)

Expand to valid, shrink to minimal; 'formed' counts satisfied characters.

⚠ formed should change only when a count crosses the requirement exactly.

Sliding Window

Fixed Window

219. Contains Duplicate IIসহজO(n) · O(n)

Last-seen index map; compare distance.

⚠ Always update to the latest index — older ones are farther away.

438. Find All Anagrams in a StringমাঝারিO(n · 26) · O(26)

Fixed window of len(p); compare frequency counts.

⚠ Remove zero entries from a Counter, or the equality check fails.

567. Permutation in StringমাঝারিO(n) · O(Σ)

Fixed-size window with matching counts.

⚠ Delete zero counts so dict comparison is accurate.

Variable Window – Longest

1004. Max Consecutive Ones IIIমাঝারিO(n) · O(1)

Longest window with ≤ k zeros.

⚠ The window never shrinks, only slides — that's fine because we only need the max length.

Variable Window – Shortest / Minimum

209. Minimum Size Subarray SumমাঝারিO(n) · O(1)

Positive numbers ⇒ expand then shrink.

⚠ Sliding window relies on positivity — with negatives use prefix sums.

Counting Subarrays (Exactly K = AtMost K − AtMost K−1)

1248. Count Number of Nice SubarraysমাঝারিO(n) · O(1)

Odd → 1, then exactly(k) = atMost(k) − atMost(k − 1).

⚠ Same atMost trick — only the value mapping changes.

Window + Hashing (Multi-word)

Monotonic Queue

239. Sliding Window MaximumকঠিনO(n) · O(k)

Monotonic decreasing deque; front = window max.

⚠ Store indices, not values — you need them to expire elements.

Prefix / Circular Window

Linked List

Basics

Fast & Slow Pointers

141. Linked List CycleসহজO(n) · O(1)

Floyd: fast meets slow ⇔ cycle.

⚠ Compare nodes (identity), not values.

142. Linked List Cycle IIমাঝারিO(n) · O(1)

Meet, reset one to head, step together → cycle start.

⚠ Return null when phase 1 ends without meeting.

Reversal

206. Reverse Linked ListসহজO(n) · O(1)

prev ← temp ← front, one arrow at a time.

⚠ Save temp.next before overwriting it.

92. Reverse Linked List IIমাঝারিO(n) · O(1)

Detach [left, right], reverse, reconnect both ends.

⚠ left = 1 has no previous node — the head changes.

61. Rotate ListমাঝারিO(n) · O(1)

Ring, then cut after length − k % length nodes.

⚠ Empty list returns immediately.

25. Reverse Nodes in k-GroupকঠিনO(n) · O(1)

Find kth node → detach → reverse → reconnect.

⚠ Track prev_node across groups so they stay connected.

Merge

23. Merge k Sorted ListsকঠিনO(N log k) · O(k) for the round list

Pairwise merging rounds — O(N log k).

⚠ Merging one by one into a growing list is O(N·k).

Palindrome

234. Palindrome Linked ListসহজO(n) · O(1)

Middle → reverse second half → compare.

⚠ Restoring the list is good practice — callers may reuse it.

Reordering / Partition

86. Partition ListমাঝারিO(n) · O(1)

Two dummy chains, then concatenate.

⚠ Set temp2.next = None or the list may loop.

Intersection

Deep Copy / Multilevel

Design

146. LRU CacheমাঝারিO(1) per operation · O(capacity)

Hash map + doubly linked list with sentinels.

⚠ Sentinel head and tail remove all null checks.

460. LFU CacheকঠিনO(1) per operation · O(capacity)

freq → OrderedDict buckets + min_freq.

⚠ Ties at the same frequency are broken by recency — hence the ordered buckets.

Sorting

148. Sort ListমাঝারিO(n log n) · O(log n) recursion

Split at the middle, sort halves, merge.

⚠ Cut the list at the middle (midPrev.next = None) or the recursion never ends.

Arithmetic

2. Add Two NumbersমাঝারিO(max(m, n)) · O(max(m, n)) output

Grade-school addition with a carry.

⚠ Keep looping for a final carry (999 + 1).

Stack & Queue

Parentheses / Bracket Matching

20. Valid ParenthesesসহজO(n) · O(n)

Push openers; each closer must match the top.

⚠ Leftover openers like '((' make it invalid.

1249. Minimum Remove to Make Valid ParenthesesমাঝারিO(n) with a set (O(n²) with indexOf) · O(n)

Stack of '(' indices; collect unmatched indices; rebuild.

⚠ Checking membership with indexOf on an array is O(n) per character — a set is better.

678. Valid Parenthesis StringমাঝারিO(n) · O(1)

Two counters: optimistic opens forward, optimistic closes backward.

⚠ A '*' before a '(' can't close it — the stack version checks index order.

Stack Simulation / String Processing

71. Simplify PathমাঝারিO(n) · O(n)

Stack of directory names.

⚠ '...' is a valid directory name, not a parent reference.

Expression Evaluation

224. Basic CalculatorকঠিনO(n) · O(n)

Stack saves (answer, sign) at each '('.

⚠ Step back one index after reading a multi-digit number.

Stack / Queue Design

225. Implement Stack using QueuesসহজO(n) push, O(1) pop/top · O(n)

Rotate after each push so the newest is at the front.

⚠ One queue is enough; the two-queue version is commented out in the code.

232. Implement Queue using StacksসহজO(n) push, O(1) pop/peek · O(n)

Make push expensive so the oldest item stays on top.

⚠ The amortised two-stack version makes pop O(1) amortised instead.

155. Min StackমাঝারিO(1) per operation · O(n)

Push (value, min so far) pairs.

⚠ A single 'current min' variable can't recover the old min after a pop.

Iterator (Stack-based)

173. Binary Search Tree IteratorমাঝারিO(1) amortised next · O(h)

Controlled in-order traversal with a stack of left spines.

⚠ Flattening the whole tree up front uses O(n) memory instead of O(h).

Queue Simulation

Monotonic Stack – Next / Previous Greater or Smaller

496. Next Greater Element IসহজO(n + m) · O(n)

Monotonic decreasing stack over nums2 + hash map.

⚠ Values are unique, so mapping by value is safe.

503. Next Greater Element IIমাঝারিO(n) · O(n)

Loop 2n−1 → 0 with i % n; monotonic stack.

⚠ Pop on equal values too — 'greater' is strict.

Monotonic Stack – Greedy Removal

402. Remove K DigitsমাঝারিO(n) · O(n)

Monotonic increasing stack; pop larger previous digits while k > 0.

⚠ Leftover k comes off the end (the stack is increasing there).

Monotonic Stack – Contribution / Area

84. Largest Rectangle in HistogramকঠিনO(n) · O(n)

Monotonic stack; width = i − stack_top − 1 when popping.

⚠ The −1 sentinel gives the correct width at the left edge.

85. Maximal RectangleকঠিনO(m · n) · O(n)

Row-by-row histograms + largest-rectangle-in-histogram.

⚠ The −1 sentinel on the stack makes the width formula work at the left edge.

Tree

Traversals (Recursive / Iterative)

Left → right → node.

⚠ Iterative post-order is the trickiest of the three — reversed (node, right, left) is a neat shortcut.

DFS Basics

226. Invert Binary TreeসহজO(n) · O(h)

Swap children at every node.

⚠ Order doesn't matter — pre-order swapping works too.

100. Same TreeসহজO(n) · O(h)

Compare roots and recurse in lockstep.

⚠ Check the None cases before reading .val.

101. Symmetric TreeসহজO(n) · O(h)

Mirror check: outer with outer, inner with inner.

⚠ Compare cross-wise, not left-with-left.

572. Subtree of Another TreeসহজO(m · n) · O(h)

isSubtree = sameTree(root, sub) or recurse into children.

⚠ Matching values aren't enough — the whole structure below must match (example 2).

110. Balanced Binary TreeসহজO(n) · O(h)

Height DFS that returns −1 on imbalance.

⚠ Computing height separately at every node is O(n²).

Root-to-Leaf Paths

112. Path SumসহজO(n) · O(h)

Reduce the target; check at leaves.

⚠ Only leaf-to-root paths count — an internal node hitting zero isn't enough.

129. Sum Root to Leaf NumbersমাঝারিO(n · h) with strings (O(n) with path·10 + val) · O(h)

Carry the path's digits; add at leaves.

⚠ path·10 + val avoids string building.

BFS / Level Order

199. Binary Tree Right Side ViewমাঝারিO(n) · O(h)

Right-first DFS; record the first node per level.

⚠ A left-only branch deeper than the right side is still visible.

662. Maximum Width of Binary TreeমাঝারিO(n) · O(n)

Heap indices per level, normalised by the level's first index.

⚠ Without normalising, indices overflow in languages with fixed-width ints.

Lowest Common Ancestor / Distance

BST

98. Validate Binary Search TreeমাঝারিO(n) · O(h)

Pass (min, max) bounds down the tree.

⚠ Comparing only with the direct parent misses violations deeper down (example 2).

450. Delete Node in a BSTমাঝারিO(h) · O(h)

Replace with successor/predecessor, then delete that one.

⚠ Reassign root.left / root.right with the recursive result.

Construction / Serialization

Tree DP

543. Diameter of Binary TreeসহজO(n) · O(h)

diameter = max over nodes of (left height + right height).

⚠ The path doesn't have to pass through the root.

337. House Robber IIIমাঝারিO(n) · O(n)

State (node, can_rob); robbing forbids the children.

⚠ Returning a (rob, skip) pair per node avoids the memo dictionary entirely.

124. Binary Tree Maximum Path SumকঠিনO(n) · O(h) recursion

Update the answer with both sides; return only one side to the parent.

⚠ Start the global best at −∞ — an all-negative tree must return its largest value.

Heap

Top K

973. K Closest Points to OriginমাঝারিO(n log k) · O(k)

Max-heap of size k on squared distance.

⚠ Comparing squared distances avoids floating-point roots.

215. Kth Largest Element in an ArrayমাঝারিO(n log k) heap · O(n + range) counting · O(k) · O(range)

Min-heap of size k; top = kth largest.

⚠ Shift by −min so negative values index correctly.

347. Top K Frequent ElementsমাঝারিO(n log k) · O(n)

Counter + size-k min-heap on frequency.

⚠ Bucket sort by frequency gives O(n).

658. Find K Closest ElementsমাঝারিO(log n + k) · O(1) extra

bisect to x, then expand the closer side.

⚠ Ties go to the smaller element (the left side).

Two Heaps

295. Find Median from Data StreamকঠিনO(log n) add, O(1) median · O(n)

Two heaps: max-heap low half, min-heap high half.

⚠ Python only has min-heaps — store negatives for the max-heap.

502. IPOকঠিনO(n log n + k log n) · O(n)

Sort by capital; max-heap of affordable profits.

⚠ Unaffordable projects aren't discarded — they may become affordable later.

K-way Merge

373. Find K Pairs with Smallest SumsমাঝারিO(k log k) · O(k)

Best-first walk over the (i, j) grid with a min-heap.

⚠ Without the seen set, (i+1, j+1) gets pushed twice.

Greedy + Heap / Scheduling

621. Task SchedulerমাঝারিO(T · log 26) · O(26)

Max-heap of counts + cooldown queue.

⚠ The formula (maxCount − 1)·(n + 1) + #maxCount gives the answer in O(T) without simulating.

Recursion & Backtracking

Recursion Basics

1922. Count Good NumbersমাঝারিO(log n) · O(1)

5^ceil(n/2) · 4^floor(n/2) mod 1e9+7.

⚠ n can be 10¹⁵ — exponentiation by squaring is required.

Subsets

78. SubsetsমাঝারিO(n · 2ⁿ) · O(n) recursion

Record at every node; extend with later indices.

⚠ Record a copy (subs[:]) — the list keeps changing.

90. Subsets IIমাঝারিO(n · 2ⁿ) · O(n)

Sort; skip nums[i] == nums[i−1] when i > index.

⚠ The condition is i != index (same level), not i > 0.

Combinations

77. CombinationsমাঝারিO(k · C(n, k)) · O(k)

Backtrack with a start index; stop at size k.

⚠ Pruning when not enough numbers remain (n − i + 1 < k − len) speeds it up.

39. Combination SumমাঝারিO(2^(T/min)) · O(T/min)

Recurse with the same index to allow reuse.

⚠ Starting the loop at start (not 0) prevents permutations of the same combination.

40. Combination Sum IIমাঝারিO(2ⁿ) · O(n)

Sort; skip same-level duplicates; break on overshoot.

⚠ Break, don't continue — every later candidate is even bigger.

216. Combination Sum IIIমাঝারিO(C(9, k)) · O(k)

Backtrack over 1..9 with count and sum checks.

⚠ The duplicate check is harmless here — digits are already unique.

Permutations

46. PermutationsমাঝারিO(n · n!) · O(n)

Fix position start, swap each choice into it.

⚠ `num not in ds` costs O(n) and breaks with duplicate values.

47. Permutations IIমাঝারিO(n · n!) · O(n)

Backtrack over a frequency map, not over indices.

⚠ Iterating the Counter keys means each value is tried once per level.

60. Permutation SequenceকঠিনO(n²) · O(n)

Factorial number system: index = k // fact.

⚠ Convert k to 0-based first.

Generate / Build Strings

22. Generate ParenthesesমাঝারিO(4ⁿ / √n) · O(n)

Add '(' if left < n; add ')' if right < left.

⚠ Never let closes exceed opens.

Partitioning

131. Palindrome PartitioningমাঝারিO(n · 2ⁿ) · O(n²) for the table

Backtracking over palindromic prefixes; a dp table can remember which substrings are palindromes.

⚠ Append a copy (parts[:]) — the list keeps changing.

Constraint Satisfaction

51. N-QueensকঠিনO(n!) · O(n²) board

Column-by-column backtracking with row + diagonal hashes.

⚠ Only check to the left — columns to the right are still empty.

52. N-Queens IIকঠিনO(n!) · O(n)

Backtracking that returns the number of solutions.

⚠ The board array isn't needed for counting — the hashes are enough.

37. Sudoku SolverকঠিনO(9^m) for m empty cells · O(m) recursion

Backtracking over empty cells with a validity check.

⚠ The box index is 3·(row//3) + i//3, 3·(col//3) + i%3.

282. Expression Add OperatorsকঠিনO(4ⁿ) · O(n)

Track prev_operand to fix up multiplication precedence.

⚠ Numbers like '05' are invalid — skip multi-digit numbers starting with 0.

Grid Search / Backtracking DFS

79. Word SearchমাঝারিO(m · n · 3^L) · O(L)

Grid DFS with a path-visited set.

⚠ Un-mark on the way back so other paths can reuse the cell.

Greedy

Sorting + Simple Greedy

455. Assign CookiesসহজO(n log n + m log m) · O(1)

Sort both; smallest sufficient cookie per child.

⚠ Skip cookies that are too small rather than skipping children.

12. Integer to RomanমাঝারিO(1) · O(1)

Greedy over values including subtractive pairs.

⚠ Without CM, XC, IV, etc. you'd produce 'VIIII'.

Jump / Reachability

55. Jump GameমাঝারিO(n) · O(1)

Move the goal left whenever i + nums[i] ≥ goal.

⚠ A zero only matters if nothing before it can jump past it.

45. Jump Game IIমাঝারিO(n) · O(1)

Implicit BFS over index windows.

⚠ Already at the end (n = 1) means 0 jumps.

134. Gas StationমাঝারিO(n) · O(1)

Reset the start after any negative running tank.

⚠ The total check is what guarantees the found start completes the loop.

122. Best Time to Buy and Sell Stock IIমাঝারিO(n) · O(1)

Sum of all positive deltas = best profit with unlimited trades.

⚠ This greedy only works because transactions are unlimited and free — fees or cooldowns need the DP versions.

Local Choice / Two-pass

135. CandyকঠিনO(n) · O(n) two-pass · O(1) slope

Two passes, take the max.

⚠ Equal ratings don't need more candy.

Intervals

228. Summary RangesসহজO(n) · O(1) extra

Extend consecutive runs.

⚠ Empty input returns [].

57. Insert IntervalমাঝারিO(n) · O(n)

Three phases: before, overlap-merge, after.

⚠ Touching intervals ([1,2] and [2,3]) overlap.

435. Non-overlapping IntervalsমাঝারিO(n log n) · O(1)

Sort by end; count overlaps with the last kept.

⚠ Sorting by start instead needs extra logic to keep the smaller end.

Graph

Graph Fundamentals / BFS

133. Clone GraphমাঝারিO(V + E) · O(V)

original → copy map as both cache and visited set.

⚠ Store the copy before recursing, or cycles loop forever.

200. Number of IslandsমাঝারিO(m · n) · O(m · n)

Count DFS launches from unvisited land.

⚠ Deep recursion on huge grids — BFS or marking the grid in place avoids it.

Graph Fundamentals / DFS

733. Flood FillসহজO(m · n) · O(m · n)

DFS through cells of the starting colour.

⚠ If the new colour equals the old one, a visited set (or early return) prevents infinite loops.

841. Keys and RoomsমাঝারিO(N + K) · O(N)

BFS from room 0 over key edges.

⚠ A key to an already-visited room is ignored.

1020. Number of EnclavesমাঝারিO(m · n) · O(m · n)

Flood from the border, count the rest.

⚠ Think in reverse — find what escapes, not what's trapped.

130. Surrounded RegionsমাঝারিO(m · n) · O(m · n)

Mark border-connected O's, flip the rest.

⚠ Searching from interior O's is much harder — start from the border.

Graph Fundamentals / DFS + DSU

547. Number of ProvincesমাঝারিO(n²) · O(n)

Count connected components with DFS.

⚠ The matrix is symmetric — no need to look at both triangles specially.

Multi-Source BFS

542. 01 MatrixমাঝারিO(m · n) · O(m · n)

Multi-source BFS from every 0.

⚠ A BFS per 1-cell would be O((mn)²).

1765. Map of Highest PeakমাঝারিO(m · n) · O(m · n)

Height = BFS distance from water.

⚠ Water cells must stay 0.

994. Rotting OrangesমাঝারিO(m · n) · O(m · n)

Multi-source BFS from rotten oranges; check none stay fresh.

⚠ No fresh oranges at all → 0 minutes.

State-Space BFS

433. Minimum Genetic MutationমাঝারিO(B · L · 4) · O(B)

BFS over one-letter mutations in the bank.

⚠ Use a set for the bank — list membership is O(B).

909. Snakes and LaddersমাঝারিO(n²) · O(n²)

BFS over squares; zig-zag coordinate conversion.

⚠ Only follow one snake/ladder per move (no chaining).

Bipartite / 2-Coloring

785. Is Graph Bipartite?মাঝারিO(V + E) · O(V)

BFS 2-colouring per component.

⚠ The graph can be disconnected — start a BFS from every uncoloured node.

Topological Sort / DAG

207. Course ScheduleমাঝারিO(V + E) · O(V + E)

Cycle detection with path-visited markers.

⚠ visited alone isn't enough — a node finished in another branch isn't a cycle.

210. Course Schedule IIমাঝারিO(V + E) · O(V + E)

DFS post-order, reversed = topological order.

⚠ Many orders are valid — any topological order is accepted.

802. Find Eventual Safe StatesমাঝারিO(V + E) · O(V)

Three-colour DFS; safe = finished without touching the path.

⚠ Leave unsafe nodes at state 1 — that's what marks them.

State-Space / Transformation BFS

399. Evaluate DivisionমাঝারিO(Q · (V + E)) · O(V + E)

Weighted graph; multiply along a BFS path.

⚠ x / x is 1 only if x appears in some equation.

127. Word LadderকঠিনO(N · L · 26) · O(N)

BFS generating one-letter neighbours; remove words once used.

⚠ Removing words from the set doubles as the visited set.

126. Word Ladder IIকঠিনexponential in the number of paths · O(N · L)

BFS for levels, then DFS backwards along level − 1.

⚠ Searching backwards avoids exploring dead branches.

Shortest Path / Dijkstra

743. Network Delay TimeমাঝারিO(E log V) · O(V + E)

Dijkstra from k; answer = max distance.

⚠ Nodes are 1-indexed; ignore dist[0].

1631. Path With Minimum EffortমাঝারিO(m·n log(m·n)) · O(m · n)

Dijkstra with max() instead of +.

⚠ Binary search on the effort + BFS is an alternative.

Shortest Path / Floyd-Warshall

Minimum Spanning Tree

778. Swim in Rising WaterকঠিনO(n² log n) · O(n²)

Min-heap of max-height-so-far along the path.

⚠ Binary search on time + BFS also works.

Union Find / DSU

721. Accounts MergeমাঝারিO(M log M) · O(M + N)

Union accounts sharing an email.

⚠ Names can repeat across different people — only shared emails merge accounts.

827. Making A Large IslandকঠিনO(n²) · O(n²)

DSU sizes + try flipping each 0.

⚠ Use a set of neighbour roots so the same island isn't counted twice.

684. Redundant ConnectionমাঝারিO(n α(n)) · O(n)

First edge connecting an already-connected pair.

⚠ Returning the first such edge matches 'the last one in input order' since only one edge closes the cycle.

Bridges / Articulation Points

Graph DP

329. Longest Increasing Path in a MatrixকঠিনO(m · n) · O(m · n)

Strictly increasing edges form a DAG ⇒ memoised DFS.

⚠ No visited set is needed — strict increase already prevents cycles.

Shortest Path / BFS-Dijkstra

787. Cheapest Flights Within K StopsমাঝারিO(E · k · log(E · k)) · O(E · k)

Heap on (cost, node, stops); skip when stops > k or stops ≥ fewest stops already seen at that node.

⚠ Standard 'visited' marking breaks this problem — a pricier path with fewer stops may be the only valid one.

Graph Fundamentals / DFS-BFS

417. Pacific Atlantic Water FlowমাঝারিO(m · n) · O(m · n)

Reverse BFS from each ocean; intersect.

⚠ Water flows downhill, so the reverse search climbs uphill.

Dynamic Programming

1D / Fibonacci

70. Climbing StairsসহজO(n) · O(1) in the final version (O(n) for memo / table)

ways(n) = ways(n-1) + ways(n-2), with ways(0) = ways(1) = 1.

⚠ Plain recursion without the memo is exponential.

509. Fibonacci NumberসহজO(n) · O(1)

F(i) only depends on F(i-1) and F(i-2), so two rolling variables are enough.

⚠ The naive recursion is O(2^n) — fine for n ≤ 30 here, but it is the classic reason to memoise.

746. Min Cost Climbing StairsসহজO(n) · O(1)

dp[i] = cost[i] + min(dp[i-1], dp[i-2]); answer = min(dp[n-1], dp[n-2]).

⚠ The answer is not dp[n-1] alone — you can step to the top from n-2 as well.

198. House RobberমাঝারিO(n) · O(n) (reducible to O(1) with two variables)

best(i) = max(nums[i] + best(i-2), best(i-1)).

⚠ A single house must return nums[0] before dp[1] is read.

213. House Robber IIমাঝারিO(n) · O(n)

Circle → max(rob_line(nums[1:]), rob_line(nums[:-1])).

⚠ With one house, slicing both ends would leave nothing — handle len == 1 first.

Kadane / Subarray DP

152. Maximum Product SubarrayমাঝারিO(n) · O(1)

The best product is always a prefix or a suffix of some zero-free segment.

⚠ Initialise the answer to −∞, not 0 — an all-negative single element like [-2] must return -2.

918. Maximum Sum Circular SubarrayমাঝারিO(n) · O(n) for the negated copy (O(1) possible)

answer = max(kadane(nums), total − min_subarray(nums)), unless everything is negative.

⚠ All-negative input: total − min would be 0 (empty subarray), which isn't allowed.

State Machine / Stocks

Effective second buy = price − best first profit.

⚠ Splitting the array at every point and running two separate scans works but is easier to get wrong.

188. Best Time to Buy and Sell Stock IVকঠিনO(n · k) · O(k)

min_buy[i] = min(min_buy[i], price − max_profit[i-1]); max_profit[i] = max(max_profit[i], price − min_buy[i]).

⚠ Note the argument order: k comes before prices.

Grid DP

3418. Maximum Amount of Money Robot Can EarnমাঝারিO(m · n · 3) · O(m · n · 3)

State = (i, j, k neutralisations left); at each cell try 'neutralise' and 'don't'.

⚠ Neutralising a positive cell wastes budget — max(coin, 0) keeps it harmless but the k-1 branch is still explored.

931. Minimum Falling Path SumমাঝারিO(n²) · O(n²) (one previous row would do)

dp[i][j] = matrix[i][j] + min(dp[i-1][j-1], dp[i-1][j], dp[i-1][j+1]).

⚠ The right-edge check uses m-1; it works because the matrix is square (m = n).

64. Minimum Path SumমাঝারিO(m · n) · O(m · n)

dp[i][j] = grid[i][j] + min(dp[i][j-1], dp[i-1][j]).

⚠ Skip (0, 0) inside the loop or you'll add it twice.

62. Unique PathsমাঝারিO(min(m, n)) for the formula · O(m·n) for the DP · O(1) for the formula

paths(i, j) = paths(i-1, j) + paths(i, j-1) — or simply C(m+n-2, n-1).

⚠ In the memo version the i == 0 or j == 0 check must come before the negative check (it does).

63. Unique Paths IIমাঝারিO(m · n) · O(m · n)

Obstacle cell ⇒ dp = 0; otherwise dp = left + up.

⚠ A blocked start or finish must return 0.

Triangle / Pascal

118. Pascal's TriangleসহজO(numRows²) · O(numRows²) for the output

row[c] = prev[c-1] + prev[c], edges are 1.

⚠ prev is only read for inner cells, so row 0 never touches it.

119. Pascal's Triangle IIসহজO(r) · O(r) for the output

C(r, i+1) = C(r, i) · (r − i) / (i + 1).

⚠ Multiply before dividing so the integer division stays exact.

120. TriangleমাঝারিO(n²) · O(n²) (one row would do)

dp[row][col] = triangle[row][col] + min(dp[row+1][col], dp[row+1][col+1]).

⚠ Going bottom-up removes the need to take a min over the last row at the end.

0/1 Knapsack / Subset Sum

416. Partition Equal Subset SumমাঝারিO(n · target) · O(n · target)

Equal partition ⇔ a subset sums to total / 2 (and total must be even).

⚠ Only seed dp[0][nums[0]] when nums[0] ≤ target.

494. Target SumমাঝারিO(n · tar) · O(tar) in the final version

Count subsets with sum (total + target) / 2 — a 0/1 knapsack count.

⚠ Handle nums[0] == 0 in the base case — both [] and [0] reach sum 0.

Unbounded Knapsack

322. Coin ChangeমাঝারিO(n · amount) · O(n · amount)

Unbounded knapsack: include ⇒ 1 + dp[same coin][amount − coin].

⚠ Greedy 'largest coin first' fails (e.g. coins [1,3,4], amount 6).

518. Coin Change IIমাঝারিO(n · amount) · O(n · amount)

ways[i][a] = ways[i-1][a] + ways[i][a − coin].

⚠ Looping amounts outer and coins inner counts permutations, not combinations.

279. Perfect SquaresমাঝারিO(n · √n) · O(n)

dp[x] = 1 + min(dp[x − s]) over squares s ≤ x.

⚠ Break out of the squares loop once a square exceeds x.

String DP / Word Break

91. Decode WaysমাঝারিO(n) · O(n)

ways(i) = ways(i+1) [if s[i] ≠ '0'] + ways(i+2) [if s[i:i+2] ≤ 26].

⚠ '06' is invalid — the zero check comes before taking two digits.

97. Interleaving StringমাঝারিO(m · n) · O(m · n)

State (i, j) — k is always i + j, so only two indices matter.

⚠ Greedy 'take from s1 when it matches' fails when both strings share a character.

139. Word BreakমাঝারিO(n² · L) with substring slicing · O(n)

dp[end] = any(dp[start] and s[start:end] ∈ words).

⚠ Without memo, the recursive version explodes on inputs like 'aaaa…b'.

472. Concatenated WordsকঠিনO(N · L²) roughly · O(N · L) for the cache

Word Break per word, with the prefix limited to a strict prefix so the word can't match itself.

⚠ Using range(1, len(word)+1) would let a word match itself and return every word.

72. Edit DistanceমাঝারিO(m · n) · O(m · n)

dist(i, j) = dist(i-1, j-1) if chars match else 1 + min(insert, delete, replace).

⚠ Using lengths (1-based) as indices keeps the empty-string base cases simple — remember to read word[i-1].

698. Partition to K Equal Sum SubsetsমাঝারিO(k · 2ⁿ) worst case · O(2ⁿ) memo

Once k-1 buckets are full, the remaining numbers must fill the last one.

⚠ Undo the 'taken' mark after each try (backtracking).

44. Wildcard MatchingকঠিনO(m · n) · O(m · n)

'*' ⇒ dp(i, j+1) or dp(i+1, j).

⚠ The 'string empty' base case must allow a run of trailing stars.

140. Word Break IIকঠিনO(2ⁿ) worst case (output can be exponential) · O(n) recursion

Backtracking over prefix words; a full path is one sentence.

⚠ Pop after recursing or later sentences inherit stale words.

LCS

1143. Longest Common SubsequenceমাঝারিO(m · n) · O(n) in the final version

lcs(i, j) = 1 + lcs(i+1, j+1) on a match, else max(lcs(i+1, j), lcs(i, j+1)).

⚠ Subsequence ≠ substring — characters don't have to be contiguous.

516. Longest Palindromic SubsequenceমাঝারিO(n²) · O(n²)

Interval DP: dp[i][j] = 2 + dp[i+1][j-1] if s[i] == s[j] else max(dp[i+1][j], dp[i][j-1]).

⚠ Loop order matters — start must go downward so dp[start+1][…] is already filled.

718. Maximum Length of Repeated SubarrayমাঝারিO(m · n) · O(m · n)

Like LCS, but a mismatch resets to 0 and the answer is the max cell, not the corner.

⚠ Don't take max of neighbours on a mismatch — that would compute a subsequence instead.

115. Distinct SubsequencesকঠিনO(m · n) · O(m · n)

match ⇒ ways(i+1, j+1) + ways(i+1, j); else ways(i+1, j).

⚠ Check 't finished' before 's finished' — an empty t matches in exactly one way.

1092. Shortest Common SupersequenceকঠিনO(m · n) · O(m · n)

LCS table, then reconstruct while emitting skipped characters.

⚠ Characters you'd skip for the LCS must still appear in the supersequence.

LIS

368. Largest Divisible SubsetমাঝারিO(n²) · O(n)

Sorted + 'divides' is transitive ⇒ it's LIS with % instead of <.

⚠ Sorting first is what makes checking only the last element enough.

873. Length of Longest Fibonacci SubsequenceমাঝারিO(n² · log M) (each chain grows like Fibonacci) · O(n)

Two numbers fix the whole sequence — extend each pair with a set lookup.

⚠ Length 2 alone doesn't count — the answer must be at least 3 or 0.

300. Longest Increasing SubsequenceমাঝারিO(n log n) · O(n)

Patience sorting: tails stay sorted, so bisect_left finds where each number belongs.

⚠ Use bisect_left for strictly increasing; bisect_right allows equal values.

354. Russian Doll EnvelopesকঠিনO(n log n) · O(n)

Sort (w ↑, h ↓), then LIS on heights.

⚠ Without height-descending on ties, [3,4] and [3,5] would wrongly nest.

Palindrome / Interval DP

647. Palindromic SubstringsমাঝারিO(n²) · O(1)

Count expansions from 2n-1 centres.

⚠ Count every expansion, not just the longest one.

132. Palindrome Partitioning IIকঠিনO(n²) · O(n²)

dp[end] = min over palindromic s[start..end] of (0 if start == 0 else dp[start-1] + 1).

⚠ Backtracking over all partitions (like Palindrome Partitioning) is exponential — this needs the DP.

DP on Squares / Matrix

221. Maximal SquareমাঝারিO(m · n) · O(m · n)

dp = 1 + min(up, left, diagonal); answer = max side².

⚠ The matrix holds characters '0'/'1', not integers.

Game DP

1025. Divisor GameসহজO(1) final (O(n²) for the table) · O(1)

Win ⇔ n is even.

⚠ n = 1 is a loss: no x with 0 < x < 1 exists.

877. Stone GameমাঝারিO(1) final (O(n²) for minimax) · O(1)

Minimax on (i, j, turn) — and with an even pile count Alice can always win.

⚠ The 'return True' trick depends on an even pile count and an odd total — read the constraints before using it.

DP on Array

403. Frog JumpকঠিনO(n²) · O(n²)

State = (stone index, last jump); a hash map turns 'is there a stone at x?' into O(1).

⚠ The first jump must be exactly 1 — starting with prev_jump = 0 enforces it.

Top Interview 150

Other

222. Count Complete Tree NodesমাঝারিO(n) · O(log n) for a complete tree

count = 1 + count(left) + count(right).

⚠ Comparing left and right heights gives O(log² n) by using completeness.

58. Length of Last WordসহজO(n) · O(1)

Skip trailing spaces, count back to a space.

⚠ Trailing spaces are the trap.

9. Palindrome NumberসহজO(log x) · O(1)

Reverse half the digits and compare.

⚠ Converting to a string works but isn't the intended trick.

66. Plus OneসহজO(n) · O(1) (O(n) when growing)

Carry propagation from the right.

⚠ [9,9,9] becomes [1,0,0,0].

383. Ransom NoteসহজO(m + n) · O(1) — 26 letters

Counter(magazine) ≥ Counter(note) letter by letter.

⚠ Each magazine letter can be used once.

427. Construct Quad TreeমাঝারিO(n² log n) · O(log n)

Uniform square → leaf; else recurse on 4 quadrants.

⚠ Checking uniformity by scanning at every level costs O(n² log n); prefix sums can make it O(n²).

149. Max Points on a LineকঠিনO(n²) · O(n)

Per anchor, group other points by slope.

⚠ Floating-point slopes can collide or differ by rounding; a reduced (dy, dx) pair with gcd is exact.

68. Text JustificationকঠিনO(total characters) · O(maxWidth)

Greedy packing + even/remainder space distribution.

⚠ Left gaps get the remainder, not the right ones.

Tree

Hard 50

Advanced / Mixed

432. All O`one Data StructureকঠিনO(1) inc/dec, O(#buckets) for max/min here · O(n)

count map + count → keys buckets.

⚠ max()/min() over bucket keys isn't O(1) — a doubly linked list of buckets makes every operation O(1).

493. Reverse PairsকঠিনO(n log n) · O(n)

Merge sort; count cross pairs before each merge.

⚠ Count before merging — the halves must still be separate.

Tree

1373. Maximum Sum BST in Binary TreeকঠিনO(n) · O(h)

Post-order returning (sum, min, max) or 'not a BST'.

⚠ The best sum starts at 0 — an all-negative tree returns 0 (empty BST).