doubts, cleared
Every doubt, answered simply
Every doubt you were too shy to ask, answered in a few short lines. Search it, or open a group. Tension mat lo: if you have this doubt, many others have it too.
114 doubts
Starting out
Fears and questions before (and right after) you begin.
I'm bad at maths. Can I still learn DSA?
Yes. Interview DSA needs school-level maths: counting, adding, a little multiplication.
The one new word is log₂ n. It only means "how many times can I halve n until 1 is left?" For 10 lakh, that's about 20.
The rest is logic: "if this, then that". You already do that every time you debug.
When a chapter needs a maths idea, it explains it right there.
How many hours a day should I study?
Steady beats long. 60–90 focused minutes a day works; the course just takes longer at that pace.
The 10-week roadmap is the full-time pace (a few hours a day). Start here turns your own hours into a dated plan.
Daily beats a weekend marathon. Practice spread out over days is remembered better than the same amount crammed into one sitting.
Phone away. One section or one problem at a time.
Should I learn C++ instead of Java?
No need. Coding rounds usually let you pick a mainstream language, and Java is one of them.
C++ is popular in competitive programming for raw speed. Interviews judge your algorithm, not microseconds.
Switching language now costs weeks. Use the one you already write daily.
If a job post asks for a specific language, follow the post.
Is it too late for me? I'm older / I have years of work experience / I'm still in college.
No. DSA is a skill, like driving. It depends on practice, not age.
Working developers have an edge: you already read code, debug and think about edge cases in production.
Freshers have an edge too: more time, and basics still fresh.
Start where you are. The course starts from Java memory basics.
I'm a complete beginner. Where do I start?
Start at chapter 1 and go in order. Each chapter only uses what came before it.
A chapter opens one section at a time, so there is only one idea in front of you. Read it, then press next →.
Already strong in Java? Skim the Java stage, take each chapter's quiz, and move on when you score well.
Then follow the roadmap, one week at a time.
I forget everything after a week. Is something wrong with my brain?
No. Forgetting is how memory works for everyone. Ebbinghaus measured how fast it happens back in 1885, by testing himself.
Reading again helps less than you think. Recalling helps more: in experiments, people who answered from memory remembered more a week later than people who re-read.
Recall spread over days also beats recall crammed into one sitting. Recall cards do this for you, with gaps of 1, 3, 7, 16 and 35 days.
For problems: re-solve must-dos from a blank editor a few days later.
Do I need to finish every chapter before I apply for jobs?
How many problems should I solve to be ready?
There is no magic number, and no study behind any exact count.
A common rule of thumb is roughly 150–250 problems across all patterns, each one re-solved later.
100 problems you can re-solve cold beat 500 you solved once and forgot.
Start with the must-dos.
I don't have a CS degree. Am I at a disadvantage?
The DSA round tests what you can do in the room, not your degree certificate.
Everything a CS course teaches for this round is here, from how memory works up to graphs and DP.
Your job: go chapter by chapter and practise. Simple hai.
Should I study here or on LeetCode?
Both, for different jobs.
Here: understand the idea, watch it in 3D, try with hints, and run Java against tests.
LeetCode: the big practice ground. Every problem here links to its LeetCode page.
Learn a pattern here first, then practise more of it there.
I never use DSA at my job. Why learn it?
You use it every day without seeing it: HashMap lookups, database indexes, Git history, the browser's back button.
Knowing it lets you pick the right tool when data grows from 100 rows to 10 lakh.
And interviews test it. Both reasons are explained, with sources, on the Why DSA page.
AI can write code now. Is DSA still worth it?
Yes. Someone still has to judge whether the AI's code is correct and fast enough for real data. That someone is you.
You can only judge what you understand.
Our full take, with sources, is on the Why DSA page.
I start with full energy and stop after three days.
Others have solved 500 problems. I feel so far behind.
Compare yourself with you from last month, not with someone's LinkedIn post.
A count of problems is not the skill. The skill is solving one unseen problem calmly, out loud.
That is what this course trains, one pattern at a time.
Should I make notes?
Short ones only. Per problem: the pattern, the one-line insight, and the bug you made.
Every chapter already has a one-screen summary and recall cards, so don't copy the chapter.
A "mistakes log" is the best thing to read the night before an interview.
My English is not great. Will that hurt me in interviews?
Interviewers want clear, not fancy. Short sentences work best.
Keep a few ready phrases: "Let me restate the problem." "Brute force is O(n²) because…" "Can I assume the input fits in an int?"
Practise saying them out loud while you solve. In a week they'll feel natural.
How to study with this site
What every part of a chapter is for, and how the tools work.
A chapter has so many sections. What is each one for?
Why it exists, plain English, remember: the meaning first, before any code.
See it in 3D, time & space, Java: watch it work, count its cost, read real Java.
Spot the pattern, traps & tricks, why & how (the shy questions), practice: recognise it and use it on interview problems.
Summary, recall cards, check yourself (a quiz): revise in minutes, days or weeks later.
A chapter opens one section at a time: finish it, then press next →. The contents list (on a phone, the bar at the top) jumps to any section, and full page shows the whole chapter on one long page.
What are the concept cards at the top of a chapter?
One card per data structure or algorithm the chapter teaches.
Each says who invented it and why, what it does in real software today, how much load it carries (with computed numbers), and what breaks without it.
Read them once. They answer "why should I care?" before "how does it work?".
How do I control the 3D simulation?
Space play / pause. → / ← next / previous step. Home / End first / last step. R restart. + / − speed.
Drag empty space to move around. Right-drag to rotate.
To zoom, first click inside the scene, then scroll or pinch. This way the page scroll is never hijacked.
P turns on predict mode: you guess each step before it plays.
Press ? anytime to see every key.
I dragged a box in the simulation and it jumped back. Is that a bug?
No. Array, stack, queue and grid cells spring back, because their position means something (the index).
Graph, tree, trie and bucket nodes stay where you drop them, so you can untangle a messy graph.
Backspace puts the selected element back. Shift + 0 puts everything back. 0 resets the camera.
The 3D view confuses me. Can I see it flat?
Yes. Press C to switch between flat 2D and 3D.
1 gives a front view and 2 a top view. 0 fits everything back in view.
Too busy? L hides extra labels and G hides the grid.
Can I try my own input in the simulation?
Yes. Edit the input fields above the scene and press run ↵.
If an input isn't allowed, a message tells you why.
Some simulations have shuffle ⤮ for a random input. Try the weird cases: empty, one element, all the same.
What is the Java code next to the simulation, with one line lit up?
It's the real Java being "run". The lit line is the one doing the current step.
The sentence shown on the scene explains that step in plain English.
Chalo, dry-run karte hain: step with → and read the line, the sentence and the variables together.
How do the hints work?
Every problem has 3 hints: a nudge, the direction, and almost the answer.
Open one at a time. After each hint, try again for a few minutes before the next.
Using a hint is not cheating. It is what a good teacher would do.
What are recall cards?
Small question cards at the end of each chapter. Read the question, answer in your head, then flip.
Rate yourself honestly: forgot, hard, got it or easy (keys 1–4).
Answering from memory is what builds memory. Re-reading feels productive, but a week later people remember less from it than from recalling.
How does the 1 / 3 / 7 / 16 / 35-day schedule work?
A card you rate comes back after a gap. Each got it moves it to the next gap: 1 → 3 → 7 → 16 → 35 days.
Easy jumps two steps. Hard keeps the same gap. Forgot sends it back to 1 day.
The first time you rate a card it starts at 1 day, even on "got it": one right answer isn't learned yet. "Easy" on first sight starts at 3 days.
Spacing is the point: recall spread over days is remembered longer than recall crammed together. The exact gaps are our own simple choice, not a magic formula.
How does the Java editor on problem pages work?
It's real Java 17, running inside your browser. Your code is compiled and tested on your device and is never sent to a server.
Run (Ctrl + Enter; ⌘ + Enter on Mac) checks the examples. Submit (Ctrl + Shift + Enter) adds the hidden tests.
Your code is saved as a draft in this browser. Reset to starter brings back the starting code (Ctrl + Z undoes that).
Inside the editor, Tab types an indent. Press Esc, then Tab, to leave it.
The editor is very slow the first time. Is it broken?
No. The first time, your browser downloads a Java runtime and the compiler. That takes about 10–20 seconds.
After that, a run takes about a second.
If Java can't start in your browser, the page offers two ways out: solve it on LeetCode, or copy the files and run them with your own JDK.
Why Java 17? Can I use var, records and switch expressions?
The in-browser runtime supports Java up to 17, so we compile everything with Java 17.
Everything up to 17 works: var (Java 10), switch expressions (14), text blocks (15), records (16).
Features added in Java 18 or later won't compile here.
Where is my progress saved? Do I need an account?
No account. Progress, recall cards and code drafts live only in this browser's localStorage.
Another browser, another device, or a private/incognito window starts empty.
Clearing this site's data (or all browser data) deletes it. Use one browser for studying.
Switching device? Export your progress as a file on my progress and import it in the other browser.
What does the confidence meter measure?
A simple, honest score: 40% chapters finished, 40% problems solved, 20% quiz accuracy.
It measures effort you control. It is not a prediction of any interview result.
How do I read the time & space table in a chapter?
Each row is an operation or an approach. Each cell is its Big-O. The last column says why.
Colours show how it grows: green for O(1) and O(log n), teal for O(n), yellow for O(n log n), pink for O(n²) and O(n·m), red for exponential.
Always read the "why" column. Interviewers ask for the reason, not just the letters.
What does "must-do" mean on a problem?
The few problems per chapter that teach its pattern best. The roadmap is built around them.
Short on time? Do the must-dos first, and re-solve them a few days later.
On the problems page, tick must-do only.
How do I find a topic or problem quickly?
Press Ctrl + K (⌘ + K on Mac) anywhere to search every chapter, problem, pattern and company.
On this page, the search box above filters these doubts as you type.
What is the "learn more" section at the end of a chapter?
A second teacher: a video or book that explains the same topic in a different voice.
If our explanation didn't click, a different one often does. Use it, then come back for practice.
Problem solving
Getting unstuck, using solutions well, and finding the right pattern.
I understand the solution when I read it, but I can't solve problems myself.
Very common. Reading a solution and writing one are different skills, like watching cricket and batting.
Fix: after reading, close it. Next day, solve it from a blank editor.
Then solve one similar problem without help. Every problem lists similar ones for exactly this.
How long should I try before I look at hints or the solution?
About 20 minutes of real trying (the 20-minute rule from the mindset chapter): writing examples, a brute force, a dry run. Not staring at the screen.
Still stuck? Open hint 1 and try 5–10 more minutes. Then hint 2, then hint 3.
After the solution, write it yourself without looking. That's where the learning happens.
Should I memorise solutions?
Memorise templates: binary search, BFS, sliding window, backtracking. They're like formulas.
Don't memorise whole problems. Interviews change one detail and memory breaks.
Test yourself: can you say why each line is there? Then you've learned it, not memorised it.
How do I know which pattern to use?
Look for signals in the problem statement.
"Sorted array" → binary search or two pointers. "Subarray / substring with a condition" → sliding window. "Top k" → heap.
"Fewest steps in a grid" → BFS. "All combinations" → backtracking. "Count the ways / min cost with choices" → DP.
Every chapter has a "spot the pattern" table, and the patterns page collects them all.
Brute force feels stupid. Should I skip it?
No. Brute force proves you understood the problem, and it is your safety net.
The optimal solution is usually brute force with the wasted work removed. You can only see the waste after writing brute force.
In interviews: say it out loud with its Big-O, then improve it.
What does "Time Limit Exceeded" mean?
Your answer may be correct, but it's too slow for the input size.
Rule of thumb: Java does roughly 10⁸ simple steps per second. n ≤ 10⁵ needs O(n log n) or better; n ≤ 20 allows O(2ⁿ).
The cheatsheet has the full "constraints → complexity" table.
I look at a new problem and my mind goes blank. How do I even start?
Use the same steps every time, so you don't need inspiration.
1. Restate the problem in your words. 2. Solve 2 small examples by hand. 3. Write brute force. 4. Find the repeated work and remove it.
Solving an example by hand very often shows you the algorithm.
The mindset chapter teaches these steps (UMPIRE) with practice.
Even "Easy" problems feel hard to me. Am I just not smart enough?
No. "Easy" means easy after you know the pattern. Before that, everything feels hard.
Learn the pattern, and its easy problems become easy. That is what the chapters are for.
Feeling stuck is part of learning, not a sign you can't.
Should I re-solve problems I've already solved?
Yes, that's the best practice there is. Re-solve from a blank editor after a few days, then after a week or two.
Solved in under 20 minutes? Great, gap it longer. Couldn't? Review the insight and try again in a few days.
What is a "dry run", and why does everyone say to do it?
Running your code by hand on a small input, writing down every variable after every line.
It finds bugs before you press Run. In interviews, it's how you test without a computer.
The 3D simulation is a dry run you can watch. Then do one on paper yourself.
I can never think of the optimal solution on my own.
Nobody does at first. Optimal ideas come from having seen the patterns many times.
Ask two questions. "What work am I repeating?" Store it: hash map, prefix sum, memo.
"What am I searching for again and again?" Sort it, or keep it in a heap or a set.
Which edge cases should I always check?
Empty input. One element. Two elements.
All values the same. Duplicates. Negatives and zero.
Already sorted, and reverse sorted.
Very large values (does it fit in int?) and the largest n allowed (is it fast enough?).
My code gives the wrong answer and I can't find the bug.
Take the smallest input that fails. Print the variables inside the loop. Compare with your hand dry-run.
The first line where they differ is your bug.
Usual suspects: off-by-one (< vs <=), a variable not reset, wrong loop bound, int overflow, changing a list while looping over it.
My solution is different from yours. Is mine wrong?
Not if it passes all the tests and has the same time and space complexity.
Interviewers care about correct, efficient, and clear. There is rarely only one right answer.
Do read our approach too. It might teach you a pattern you'll need later.
Java doubts
The Java questions that trip up DSA learners, answered from the official Java 17 docs.
int vs Integer: what's the difference?
int is a plain number (a primitive). Integer is an object that wraps one int.
Collections only hold objects, so it's List<Integer>, never List<int>. Java converts for you (autoboxing).
Integer can be null. Unboxing a null throws NullPointerException, e.g. int c = map.get(key); when the key is missing.
In hot loops, prefer int and int[]: no boxing, less memory.
== vs .equals(): why does == sometimes fail?
For objects, == asks "same object in memory?". .equals() asks "same value?".
Strings: always a.equals(b).
Trap: with Integer a = 127, b = 127;, a == b is true. With 128 it is usually false, because Java only promises to cache −128 to 127.
Bas itna yaad rakho: == for int, long, char, boolean; .equals() for String, Integer and every other object.
When should I use an ArrayList, and when a plain array?
Size known up front (you're given n) → int[]. Fast and no boxing.
Size grows as you go (collecting answers) → ArrayList.
ArrayList.add is amortized O(1): adding n elements takes O(n) time in total, even though it sometimes copies into a bigger array.
Need an int[] at the end? A simple loop, or list.stream().mapToInt(Integer::intValue).toArray().
HashMap vs TreeMap: which one should I use?
HashMap: get/put in O(1) on average. No order at all.
TreeMap: get/put in O(log n), guaranteed. Keys stay sorted, and you get floorKey, ceilingKey, firstKey, lastKey.
Need sorted keys, or "the closest key below x"? TreeMap. Otherwise HashMap.
Need insertion order (or an LRU cache)? LinkedHashMap.
Why do you use ArrayDeque and not Stack?
Stack is an old class built on Vector, which is synchronized: a locking cost you don't need in a single-threaded solution.
The Java docs themselves say to prefer Deque: Deque<Integer> stack = new ArrayDeque<>();
As a stack: push, pop, peek. As a queue: offer, poll, peek.
One catch: ArrayDeque doesn't allow null elements.
What is StackOverflowError, and how do I fix it?
Every method call takes a frame on the call stack. Recurse too deep and the stack runs out.
Most common cause: a missing or wrong base case, so the recursion never stops.
If the base case is right but the input is huge (a list of 10⁵ nodes), the depth itself is the problem. Use a loop or your own ArrayDeque stack.
Our hidden tests keep recursion depth small enough for the browser, so a correct recursive solution won't fail here because of depth.
Why did my sum suddenly become negative?
int can hold at most 2,147,483,647 (about 2.1 × 10⁹). Go past it and it silently wraps around to a negative number. No error.
Use long when values can add or multiply big: e.g. the sum of 10⁵ numbers up to 10⁹ can reach 10¹⁴.
Careful: long x = a * b; with int a, b still overflows, because the multiply happens in int. Write (long) a * b.
Binary search middle: lo + (hi - lo) / 2, not (lo + hi) / 2. Even the JDK once had this bug.
String vs StringBuilder: why does += in a loop slow me down?
A String can never change. s += c builds a brand-new string and copies everything, every time.
In a loop over n characters that copying adds up to O(n²).
StringBuilder grows in place: sb.append(c) is amortized O(1). Finish with sb.toString().
Rule: building a string in a loop → StringBuilder.
What does c - 'a' mean?
A char is a number underneath: its Unicode value. 'a' is 97, 'b' is 98, and so on.
So c - 'a' is 0 for 'a', 1 for 'b' … 25 for 'z'. A perfect index into int[26].
Going back: (char) ('a' + i).
I printed my PriorityQueue and it's not sorted. Is it broken?
No. It's a heap: only the top, peek(), is guaranteed to be the smallest.
Printing it or looping over it shows the internal order, which the docs say has no particular order.
For sorted order, poll() again and again. Each poll is O(log n).
Max-heap: new PriorityQueue<>(Collections.reverseOrder()). Avoid (a, b) -> b - a: with very large or negative values the subtraction can overflow. Use Integer.compare(b, a).
Which sort does Arrays.sort use? Is it always O(n log n)?
For primitive arrays like int[]: Dual-Pivot Quicksort. The Java 17 docs say O(n log n) on all data sets.
For objects (Integer[], String[], and Collections.sort): TimSort. O(n log n), and stable.
Stable means equal items keep their original order. Useful when you sort by one field after another.
Why is -7 % 3 equal to -1 in Java, not 2?
Java's integer division rounds toward zero: -7 / 3 is -2. So the remainder is -7 - (-2 × 3) = -1.
In short: % keeps the sign of the left number.
Need a result from 0 to m − 1 (circular arrays, hashing)? Use Math.floorMod(-7, 3), which gives 2.
Why do I get ConcurrentModificationException when I remove items in a loop?
Changing a list or map while a for-each loop walks over it confuses its iterator, so Java usually stops you with this exception.
Fix: list.removeIf(x -> x < 0), or use an Iterator and call it.remove().
Or build a new list with only the items you want to keep.
What's the cleanest way to count things with a HashMap?
map.merge(x, 1, Integer::sum); adds 1, starting from 1 if x is new.
Same thing, more readable for some: map.put(x, map.getOrDefault(x, 0) + 1);
Grouping: map.computeIfAbsent(key, k -> new ArrayList<>()).add(x);
Only lowercase letters? A plain int[26] is simpler and faster.
Why does printing my array show something like [I@1b6d3586?
Arrays don't have their own toString(). You see the type name ([I means "int array") and a hash code.
Use Arrays.toString(arr), and Arrays.deepToString(grid) for 2D arrays.
Same trap with comparing: a.equals(b) on arrays compares references. Use Arrays.equals(a, b).
Do I need streams and lambdas for DSA?
Streams: not really. Plain loops are clearer to explain and usually faster in hot paths.
Lambdas: yes, for comparators. Sort intervals by start: Arrays.sort(iv, (x, y) -> Integer.compare(x[0], y[0]));
Or the same thing, more readable: Arrays.sort(iv, Comparator.comparingInt(x -> x[0]));
Do I need BufferedReader and fast input for interviews?
For LeetCode-style rounds, no. You write a method, and the platform passes the input.
Some online tests make you read input yourself. For large input, BufferedReader is much faster than Scanner, as community benchmarks show.
The Java I/O chapter shows the exact template.
Big-O doubts
Complexity, without the fear.
Why do we drop constants? Isn't 2n slower than n?
It is, a little. But Big-O asks a different question: how does the time grow when n grows?
Double n: both 2n and n double. But n² becomes 4 times bigger.
That growth shape decides whether code survives 10 lakh users. Constants matter when tuning, just not in the Big-O label.
Is O(n log n) always slower than O(n)?
Not always. For small n, constants can win: a tight O(n log n) sort may beat an O(n) method that does heavy work per step.
Big-O is about large n. For n = 10 lakh, log₂ n ≈ 20, so n log n is about 20 × n.
In interviews, compare by Big-O unless you're asked about real speed.
What does "amortized" mean?
The average cost per operation over a long run, even if a few operations are expensive.
ArrayList.add usually just drops the item in. Sometimes the array is full and everything is copied to a bigger one.
Spread over all adds, each one is O(1). The Java docs put it as: adding n elements takes O(n) time.
Not the same as "average case": amortized is a guarantee over the whole sequence. No luck involved.
How do I find the complexity of a recursive function?
Time = (number of calls) × (work in one call, not counting the calls it makes).
Draw the recursion tree. Plain fib(n) makes 2 calls each time, so it's O(2ⁿ). With memo, each n is computed once: O(n).
Space = the deepest chain of calls (stack depth) + any extra memory. For fib(n), depth is n, so O(n).
Halving the input each call (like binary search) gives depth log n.
What does log n really mean?
How many times you can halve n until 1 is left.
16 → 8 → 4 → 2 → 1 is 4 halvings, so log₂ 16 = 4.
10 lakh needs about 20 halvings, 100 crore about 30. That's why binary search feels instant.
Does the input count in space complexity?
Usually we count extra space: what you create beyond the input. Say which one you mean.
"O(1) extra space" means a few variables, no array or map that grows with n.
The recursion stack counts as extra space. A recursion of depth n is O(n) space.
Worst case or average case: which one do I say in an interview?
Say the worst case by default.
When they differ, say both: "Quicksort is O(n log n) on average, O(n²) in the worst case."
For a HashMap, the honest phrase is "O(1) on average".
Two nested loops: is that always O(n²)?
No. Count the total work, not the number of loops.
In a sliding window, the inner while only moves left forward. Across the whole run it moves at most n times, so it's O(n).
Same with a monotonic stack: each element is pushed once and popped at most once. O(n).
Why do graphs say O(V + E) instead of O(n)?
When the input has two sizes, keep both. A graph has V nodes and E edges.
BFS and DFS visit each node once and look at each edge once (twice if undirected), so O(V + E).
Grids work the same way: O(rows × cols).
Can I guess the needed complexity from the constraints?
Yes, roughly. Assume about 10⁸ simple steps per second.
n ≤ 10 → O(n!) is fine. n ≤ 20 → O(2ⁿ). n ≤ 500 → O(n³). n ≤ ~5,000 → O(n²) (10⁴ is borderline).
n up to 10⁶ → O(n log n). Up to 10⁸ → O(n). Bigger → O(log n) or a formula.
It's a rule of thumb, not a law. The cheatsheet has the full table.
Is HashMap really O(1)?
On average, yes, if the keys spread well across buckets. The Java docs say exactly that.
Hashing a key has its own cost: a String key of length k takes O(k) to hash.
Since Java 8, a bucket with too many collisions turns into a balanced tree. For keys like Integer and String, even a bad bucket then costs O(log n), not O(n).
Topic confusions
The classic "which one, and why?" mix-ups, each with its chapter.
Binary search: lo < hi or lo <= hi? I always mix them up.
Both are correct. Mixing their pieces is what breaks.
Find exactly: hi = n - 1, while (lo <= hi), moves lo = mid + 1 / hi = mid - 1. Return from inside the loop.
Find a boundary (first true, insert position): hi = n, while (lo < hi), moves lo = mid + 1 / hi = mid. When it stops, lo is the answer.
Pick one template per problem and keep all three parts matching.
BFS or DFS: how do I choose?
BFS goes level by level with a queue. Use it for "fewest steps" in an unweighted graph or grid, like the shortest route in a game map.
DFS goes deep first, with recursion or a stack. Use it to explore everything: islands, connected parts, cycles, all paths.
Both are O(V + E). When both work, pick the one you can write without bugs.
When should I use a heap?
When you keep needing the smallest (or largest) item while items keep changing. Like a CPU scheduler picking the next task.
Signals: "top k", "k-th largest", "merge k sorted lists", "always process the cheapest next".
peek is O(1); offer and poll are O(log n).
Just need everything sorted once? Simply sort.
Recursion: what is the "leap of faith"? I get lost tracing the calls.
Don't trace every call in your head. Assume the call on the smaller input already returns the right answer.
Your only jobs: the base case, and building your answer from the smaller answer.
Example: height(node) = 1 + max(height(left), height(right)), and an empty tree has height 0.
Trace only a tiny input (2–3 levels) to check yourself.
DP: top-down or bottom-up?
Top-down: write the recursion, then store each result in an array or map (memo) so it's computed once.
Bottom-up: fill a table from the smallest subproblems upward with loops, like filling an Excel sheet row by row.
Same complexity, usually. Start top-down: it comes straight from the recursion.
Switch to bottom-up when the recursion gets too deep, or when you want to keep only the last row and save space.
Greedy or DP: how do I know?
Greedy takes the best-looking choice now and never looks back. DP tries every choice for each subproblem and remembers the results.
Greedy is right only when you can show the local best choice is always safe.
Test with a small counter-example. Coins {1, 3, 4}, amount 6: greedy picks 4 + 1 + 1 (3 coins), but 3 + 3 needs only 2. So that problem needs DP.
What's the difference between a tree and a graph?
A tree is a special graph: connected, no cycles, n nodes and exactly n − 1 edges. Like folders in File Explorer.
A general graph can have cycles, so you need a visited set or you'll loop forever.
In a rooted tree like TreeNode, walking down from the root never revisits a node, so no visited set is needed. (Tree given as undirected edges? Just don't walk back to the parent.)
Why does sorting first help so often?
Sorted data has order you can use: two pointers from both ends, binary search, duplicates side by side, intervals merged in one pass.
Sorting costs O(n log n) once. That's a great deal if brute force was O(n²).
Catch: sorting loses original positions. If the answer needs indices, sort pairs of (value, index).
Sliding window vs two pointers: aren't they the same?
Sliding window is a kind of two pointers. Both pointers move the same way, and you care about everything between them.
Classic two pointers start at both ends and move inward, usually on sorted data, looking at pairs.
Signals: "longest / shortest subarray or substring with…" → window. "Sorted, find a pair / triplet with sum…" → two pointers.
Subarray sum problem: sliding window or prefix sum?
A window works when all numbers are positive: growing the window always raises the sum, and shrinking it always lowers it.
With negative numbers, the window can't tell when to shrink. Use prefix sums + a HashMap of sums seen so far.
Classic example: "count subarrays with sum exactly k", negatives allowed → prefix sum.
Backtracking vs recursion: what's the difference?
Recursion is the tool: a function calling itself.
Backtracking is a strategy that uses it: choose → explore → un-choose, to try every option.
Every backtracking solution is recursive. Not every recursion is backtracking: factorial never un-chooses anything.
Stack vs queue: I keep confusing them.
Stack: last in, first out. Ctrl + Z undoes your latest change first, and browser back goes to the latest page.
Queue: first in, first out. The print queue prints the first document sent.
In Java both are ArrayDeque: stack uses push / pop, queue uses offer / poll.
Why do linked list solutions use a "dummy" node?
So the head isn't a special case. Without it, removing or inserting at the head needs separate code.
Put a fake node before the head, work normally, and return dummy.next at the end.
When do I need a trie instead of a HashSet of words?
When the question is about prefixes: "any word starting with 'pri'?", autocomplete, contacts search.
A HashSet answers "is this exact word there?" well, but finding every word with a prefix means checking them all.
A trie answers a prefix question in O(length of the prefix).
When do I use union-find instead of BFS/DFS?
When edges arrive one by one and you keep asking "are these two connected now?".
BFS/DFS would redo the search after every edge. Union-find (with path compression and union by rank) answers each question in nearly O(1), amortized.
For a fixed graph you explore once, BFS/DFS is simpler.
Interviews and fear
Honest, practical answers for the scary part. No guarantees, just what helps.
I blank out in interviews, even on problems I know.
This happens to many people, including strong engineers. It's not a sign you don't know DSA.
Have a fixed routine, so you never depend on inspiration: restate the problem → work an example by hand → say brute force → find the waste.
Type your thoughts in the editor as comments as you go. They hold your thinking when your head can't.
Practise that routine in timed mocks until it runs on autopilot.
What if I can't solve the problem in the interview?
Don't go silent. A correct, clearly explained brute force is much better than half of a clever idea.
Say exactly where you're stuck: "I have O(n²). I'm looking for a way to avoid the inner loop." That invites help.
One bad round doesn't decide your future. Write down what tripped you and add it to your practice.
Is it okay to ask the interviewer for a hint?
Yes. Ask after showing your thinking: "Here's what I tried and where I'm stuck. Am I on the right track?"
A hint used well is far better than ten minutes of silence.
Listen closely when the interviewer speaks. A community guide puts it simply: usually they are trying to give you a hint or steer you.
What if I make a bug in the interview?
Everyone makes bugs. Finding and fixing your own bug calmly is a good sign, not a bad one.
Before you say "done", dry-run your code on a small example and one edge case. Community guides give the same advice.
Found one? Say it plainly: "I see a bug, this should be <=", and fix it. Koi baat nahi.
I'm an introvert. How do I "think aloud"?
You don't have to be chatty. Just narrate, like a cricket commentator: what you're doing, and why.
Use ready phrases: "First, let me restate the problem…" "Brute force would be…, that's O(n²) because…" "I'll keep a HashMap of values I've seen."
Quiet thinking is allowed. Say "Can I take a minute to think?", then share what you found.
Practise alone: solve one problem a day out loud, or record yourself. Awkward at first, normal within a week or two.
Should I tell them I've already seen the problem?
Yes, be honest: "I've seen a similar problem before."
They may give you a different one, or ask you to explain it deeply. Both are fine.
Pretending, and getting caught, does far more damage than a new problem.
Rejections are making me feel useless.
A rejection means "not this round, not this day". It doesn't measure your worth, or decide your future.
Many strong engineers have been rejected many times before an offer. Ek round se life decide nahi hoti.
After each one, write 3 lines: what went well, what broke, one thing to practise next. That turns hurt into a plan.
Talk to someone you trust. If the low feeling stays for weeks, or ever feels too heavy, please talk to a counsellor or doctor, or call Tele-MANAS on 14416: India's free government mental-health helpline, open 24x7.
How should I spend the 45 minutes of a coding round?
Rough plan: about 5 minutes to understand and do examples, about 7 to agree on brute force and a better plan.
About 18 to code, narrating as you go.
The last 15: dry-run, edge cases, then final time and space complexity.
The mindset chapter has this budget as a table; the 45-minute plan splits it into seven phases, with what to say in each.
The interviewer stays silent and I feel judged.
Silence is normal. Many interviewers are listening or taking notes.
Check in now and then: "Does this approach sound reasonable before I code it?"
Their answer tells you whether you're on track, and breaks the silence.
What should I ask before I start coding?
How big can the input get? Can it be empty? Negatives? Duplicates? Is it sorted?
Return indices or values? One answer or all of them? What if there's no answer?
Community interview guides suggest asking at least 2–3. It also stops you solving the wrong problem.
What if they ask the complexity and I'm not sure?
Reason out loud instead of guessing: "The loop runs n times, and each map lookup is O(1) on average, so O(n)."
A reason with a small slip is better than a confident wrong guess.
I code fine alone, but freeze when someone watches.
That's a skill to practise, not a personality flaw.
Make practice feel like the real thing: a 45-minute timer, an unseen problem, talking out loud.
Then add a person: a friend, a colleague, or record yourself. The fear shrinks each time.
How do I practise interviews when I'm alone?
Pick an unseen must-do problem and set a 45-minute timer.
Speak the whole time. No hints for the first 20 minutes.
Afterwards, note one thing that went well and one thing to fix.
What should I do right after an interview?
The same day, write down the questions and exactly where you got stuck.
Then solve them fully at home, with this site's matching chapter.
Pass or fail, that hour of notes is some of the best practice you'll ever get.
What is a "machine coding" round?
Some companies, often Indian product companies (community-reported), have a round where you build a small working program in a fixed time.
Think a parking lot system or a splitwise-style expense sharer: clean classes, working code, and a bit of design.
It's a different skill from DSA rounds, with its own practice.