LogIn
I don't have account.

How to Approach Any DSA Interview Problem : A Complete Step-by-Step Guide

Jon Chu
232 Views

I have sat on the other side of the table for more than 2,000 coding interviews. Not two hundred. Two thousand. And here is the thing that still surprises new interviewers when I tell them: most people who fail these interviews know the algorithm. They just don't know how to use it in a room with someone watching them think.

I have watched a candidate who had 500+ LeetCode problems solved freeze on an easy array question because the interviewer asked one follow-up he wasn't expecting. I have also watched a candidate who barely knew what a heap was walk through a hard problem step by step, out loud and get hired anyway , because he showed me exactly how his brain worked and his brain worked well.

That is the whole secret of this article. Solving a problem on LeetCode at 11 PM with no one watching is one skill. Solving the same problem in front of a stranger, on a timer, while explaining your thinking, is a completely different skill. Nobody teaches you the second one. This article does.

A quick note before we start: this is not a DSA tutorial. I am not going to teach you what a binary search tree is. I am going to teach you what to do the moment your interviewer finishes reading the question out loud , because that moment is where most interviews are won or lost, long before anyone writes a single line of code.

What Interviewers Are Really Evaluating

Here is something most candidates don't know, the code is maybe 30% of what I'm scoring. The rest is everything happening around the code. When I write feedback after an interview, I'm not writing "solved the problem, yes/no." I'm answering questions like these:

  • Can this person break down a vague problem into something solvable?
  • Do they think out loud or do I have to guess what's going on in their head?
  • When I push back or ask "what if," do they think it through or do they panic?
  • Do they just pick the first idea or do they consider trade-offs?
  • When their code is wrong, do they find the bug calmly or do they start randomly changing things?
  • Is the code something I'd feel okay reviewing in a real pull request?
  • Did they check their own solution against tricky inputs or did they just say "I think this works"?
  • If I gave them a hint, did they use it well or did they get defensive?
  • Were they pleasant to work with for 45 minutes or exhausting?

One mistake I see almost every week, a candidate solves the problem correctly, gets the optimal time complexity and still gets rejected. Why? Because for 40 minutes, I had no idea what they were thinking. They typed in silence, deleted things, typed again and finally showed me a correct answer , but I have no way to know if they'll do that on a real project with a teammate depending on them or if they just got lucky pattern-matching this one problem.

Compare that to a candidate I interviewed last year for an SDE-2 role. She didn't get the most optimal solution. She got a good one, not the best one. But every single decision she made, she said out loud first , "I'm going to use a hash map here because I need O(1) lookups," "let me check what happens with duplicates before I move on." I could follow her entire brain from start to finish. I hired her. The other candidate, the one who solved it perfectly in silence, I did not.

The Complete Interview Timeline

Most 45–60 minute interviews follow a rough shape. Knowing this shape in advance removes a huge amount of anxiety, because you stop wondering "am I taking too long?" every two minutes.

Time What Should Be Happening
0–2 min Quick greeting, small talk, interviewer sets expectations
2–7 min Interviewer reads the problem, you read it again yourself
7–12 min You ask clarifying questions, confirm inputs/outputs/constraints
12–20 min You think out loud, work through examples, discuss brute force
20–30 min You look for a better approach, discuss trade-offs
30–45 min You write the actual code
45–55 min You test your code, fix bugs, discuss complexity
55–60 min You ask the interviewer questions, wrap up

This is a guide, not a stopwatch you should stare at. Some interviewers spend 15 minutes just on clarification for a tricky problem. Some skip brute force entirely if you jump straight to a good idea. The point of knowing this timeline isn't to follow it exactly , it's so that if you're still stuck on "understanding the problem" at minute 25, a small alarm goes off in your head telling you to move forward, ask for a hint or simplify your approach.

Step 1 , Don't Start Coding

This is, without exaggeration, the single biggest mistake I see. Many candidates hear the problem and start typing within 30 seconds. It feels productive. It is usually the opposite.

Here's why this happens so often: silence feels uncomfortable, especially on a video call with someone watching you. Typing feels like progress. But typing before you understand the problem is like starting to build a house before you've seen the plot of land , you might build something, but there's a good chance you'll have to tear it down halfway through.

I've rejected excellent programmers because they never once explained what they were building before they built it. One candidate, clearly skilled, started coding a solution within a minute of hearing the question. Three minutes in, he stopped, deleted everything and started over , because his first assumption about the input was wrong. He did this two more times. By minute 25, he had a working solution, but I had watched him waste 20 minutes on false starts that ten seconds of clarification would have prevented.

The strongest candidates usually do the opposite: they sit with the problem for a minute, sometimes in silence, sometimes thinking out loud, before touching the keyboard. That pause is not wasted time. It's the most valuable 60 seconds in the entire interview.

Understanding the Problem

Once the interviewer finishes reading the question, don't rush to respond. Read it again yourself, slowly, in your head or even out loud. Then work through it like this:

  • What exactly is the input? Is it an array, a string, a tree, a graph? What are its possible sizes , could it be empty? Could it have one element?
  • What exactly is the output? A single number? A list? True or false? A modified version of the input?
  • What are the constraints? If the array can have up to 10^5 elements, that alone tells you an O(n²) solution probably won't pass. If it can have up to 20 elements, that's a strong hint that the intended answer might involve trying all combinations.
  • What assumptions am I making that I haven't said out loud? This is the one people skip most.

Here's an example of a weak clarification versus a strong one, using a classic problem: "find two numbers in an array that add up to a target."

Weak clarification: "So I just need to find two numbers that sum to the target, right?"

This question tells the interviewer nothing about how you think. It just confirms what was already said.

Strong clarification: "Can the array contain duplicate values? Can the same element be used twice or do I need two different indices? Is there guaranteed to be exactly one valid answer or could there be zero or multiple? Are the numbers only positive or can they be negative?"

Notice what happened there , each of those questions could genuinely change the code you write. That's the test of a good clarifying question: if the answer wouldn't change your approach at all, it's probably not worth asking. If it would completely change how you solve it, ask it early, before you've built half a solution on a wrong assumption.

How to Talk to the Interviewer

A coding interview is closer to a conversation than an exam, even though it doesn't always feel that way. The interviewer wants to hear your thoughts, not just see your final code.

  • Thinking aloud means narrating your reasoning as it happens, not after. Instead of going quiet and then announcing "I'll use a hash map," say something like: "I need to check if I've seen this value before and I need that check to be fast , a hash map gives me O(1) lookups, so let me try that." That single sentence tells me you understand why, not just what.

  • Handling silence is something almost nobody prepares for. If you go quiet for 30 seconds while thinking, that's completely fine , just say "give me a second to think this through" so the interviewer knows you're working, not stuck. Silence without any signal makes an interviewer nervous and a nervous interviewer starts wondering if they need to jump in and rescue you.

  • Handling hints is a skill in itself. When an interviewer says something like "what if there were duplicates in the array?", that is almost never a random question , it's usually a hint that your current approach breaks under that condition. The worst response is to brush it off with "oh yeah, I think it still works," without actually checking. The best response is to pause, genuinely think about it and say "actually, let me check that against an example" and then do it.

  • Admitting uncertainty is far better than fake confidence. If you don't know whether a language's built-in sort is stable or you forget the exact syntax for something, just say so: "I don't remember if this method exists exactly like this, but conceptually here's what I want it to do." Interviewers have seen thousands of candidates , we can tell the difference between real confidence and a bluff and the bluff never lands well.

Working Through Examples

Before jumping to an algorithm, walk through a small example by hand. This does two things: it makes sure you actually understood the problem correctly and it often reveals the pattern before you've consciously thought about it.

Say the problem is: given a string, find the length of the longest substring without repeating characters. Take a small example , "abcabcbb" and manually trace through it: a, then ab, then abc, then you hit another a, so you shrink from the left and so on. Doing this by hand, slowly, out loud, often makes you notice something like "oh, I'm sliding a window and shrinking it when I see a duplicate" and that noticing, that's the sliding window pattern showing itself to you naturally, instead of you trying to remember it from a list of patterns.

Always test at least one normal case and one edge case by hand before coding , an empty input, a single-element input or the smallest and largest values allowed by the constraints. Interviewers genuinely love watching candidates do this, because it's exactly what a careful engineer does before writing any real code, not just interview code.

Identifying the Pattern

Pattern recognition isn't about memorizing "this is a sliding window problem" from a list. It's about noticing certain signals in the problem that push you toward certain tools. Here's how experienced engineers actually think through it, not just a list to memorize:

  • Two Pointers: Signal , sorted array or you need to compare elements from both ends or find pairs/triplets.
  • Sliding Window: Signal , contiguous subarray or substring and you're looking for something like "longest," "shortest," or "count of" a window that satisfies a condition.
  • Binary Search: Signal , sorted data or the answer itself is a number you can guess and check ("can I finish this in X days?").
  • DFS / Backtracking: Signal , you need to explore all possible combinations, paths or arrangements, especially with words like "all possible," "count the ways," or "find if a path exists."
  • BFS: Signal , shortest path in an unweighted graph or "level by level" exploration.
  • Dynamic Programming: Signal , the problem asks for a maximum, minimum or count of ways and smaller versions of the same problem clearly feed into the bigger one.
  • Greedy: Signal , at each step, picking the locally best option seems to lead to the globally best result, often involving sorting first.
  • Heap: Signal , you repeatedly need the smallest or largest element, like "top K" problems.
  • Trie: Signal , lots of string prefix matching or autocomplete-style lookups.
  • Graph / Topological Sort: Signal , dependencies between tasks, "must happen before," or scheduling problems.
  • Monotonic Stack: Signal , "next greater element," or comparing each element to the nearest bigger/smaller one.
  • Prefix Sum: Signal , repeated queries about the sum of a range in an array.
  • Hash Map: Signal , you need fast lookups, counting frequencies or checking "have I seen this before."
  • Intervals: Signal , problems about merging, overlapping or scheduling ranges of time.
  • Bit Manipulation: Signal , constraints mention powers of two or the problem talks about XOR, unique elements or binary representations.
  • Union Find: Signal , grouping things into connected sets or repeatedly asking "are these two things connected?"

You will not always spot the pattern in ten seconds and that's fine. Talking through the signals out loud , "this feels like it needs fast lookups, so maybe a hash map, let me check" , shows the interviewer your reasoning process even before you've locked in the final approach.

Start With Brute Force

A lot of candidates are scared to say the brute force out loud because it feels like admitting they don't know the "real" answer yet. This fear costs people interviews all the time.

Saying the brute force first does three things for you. It proves to the interviewer you actually understood the problem, since even a slow solution requires correct understanding. It gives you a working baseline you can fall back on if you run out of time. And it often naturally reveals what's slow, which points you straight toward the optimization.

Here's how to say it well: "The simplest way I can think of is checking every possible pair, which would be O(n²). I know that's not ideal, so let me think about what's making it slow before I try to improve it." That single sentence does a lot of work , it shows you know it's not the final answer and it sets up the transition to Section 9 naturally instead of you awkwardly announcing "now let me optimize."

One candidate I interviewed skipped brute force completely and jumped straight to a clever O(n) solution using a hash map. It worked. But when I asked "why did you pick this approach over anything simpler?" , he couldn't explain the journey, only the destination. It made me wonder if he'd simply memorized this exact problem rather than derived the solution live. Walking through brute force first removes that doubt entirely.

Optimization Thinking

Once brute force is on the table, look for the actual bottleneck , the specific part of your solution doing repeated, unnecessary work. This is a skill you build by asking yourself a few honest questions:

  • What am I recalculating that I already know? If you're looping through the array again inside another loop just to check something, that repeated work is often removable with a hash map or a precomputed array.
  • Would sorting help? A lot of two-pointer and greedy problems become dramatically simpler the moment the data is sorted, even though sorting itself costs O(n log n).
  • Can I trade memory for speed? Storing extra information (like a hash map of counts or a prefix sum array) often turns an O(n²) solution into O(n), at the cost of some extra space. Say this trade-off out loud , "I can use O(n) extra space to bring this down from O(n²) to O(n) time" , because naming the trade-off explicitly is exactly what a senior engineer does on a real project too.
  • Am I solving the same subproblem more than once? If yes, that's dynamic programming knocking on the door , either memoize the recursive calls or build the solution bottom-up.

Optimization rarely happens in one big leap. It usually happens in small, explainable steps , "this part is O(n²) because of this nested loop, if I precompute this value once, I remove the inner loop entirely." Walking through it this way, out loud, step by step, is far more convincing to an interviewer than silently rewriting your solution and revealing a faster one out of nowhere.

Before Writing Code

Once you have an approach you're fairly confident about, don't jump straight into typing real code. Take thirty seconds to say it back in plain words, almost like pseudocode: "So I'll use Two Pointers:, one at the start and one at the end. I'll compare their sum to the target. If it's too small, move the left pointer forward. If it's too big, move the right pointer back. I'll repeat until they meet."

This step matters for two reasons. First, saying it out loud often catches a logical gap before you've written a single line , you might realize mid-sentence that you haven't handled what happens when the pointers meet. Second, it gives the interviewer a chance to stop you before you write ten minutes of code based on a wrong idea, rather than after.

Most interviewers will simply nod and say "sounds good, go ahead" and that small nod is worth a lot, because now you're coding with confidence instead of hoping you're on the right track.

Writing Clean Code

Interview code doesn't need to be perfect production code, but it should look like something a teammate could read without asking you ten questions.

  • Use real variable names , leftPointer and rightPointer, not l and r if the problem has several pointers moving around; wordCount instead of wc or x.
  • Break out small helper functions if a chunk of logic is doing its own separate job , like a function that checks if a string is a palindrome, called from inside your main function.
  • Don't over-engineer it either , this isn't the place for excessive abstraction, design patterns or building a generic framework for a problem that only needs twenty lines.
  • Keep your code visually organized , consistent spacing and indentation make a real difference in how easy your code is to review on the spot.

I've seen candidates lose points not because their logic was wrong, but because their code was so cramped and unreadable that I had to ask them to explain every single line. That's time neither of you gets back.

Thinking Aloud Effectively

Here's what good communication actually sounds like in practice, not just in theory. Below is a realistic snippet of dialogue from an interview on the classic "group anagrams" problem.

Candidate: "I'm considering a hash map here, where the key is some kind of signature for the word and the value is a list of all words that share that signature."

Interviewer: "What would you use as the signature?"

Candidate: "My first thought is sorting each word's letters , 'eat' and 'tea' both sort to 'aet'. That would work as a key."

Interviewer: "What about performance if the words are really long?"

Candidate: "Good point , sorting each word costs O(k log k) where k is the word length. If I have a lot of long words, that adds up. I could instead count letter frequencies as the key, which would be O(k) instead. Let me go with that if the words could be long."

Interviewer: "Sounds reasonable, go ahead."

Notice what happened here , the candidate didn't get defensive when questioned. She treated the interviewer's question as useful information, thought about it honestly and adjusted. That back-and-forth is not a test you're failing , it's the interview working exactly as it's supposed to.

When You Get Stuck

Everyone gets stuck. What separates a good interview from a bad one is what you do in that stuck moment, not whether it happens at all.

  • Go back to your example. Re-run your current approach on the example by hand and watch exactly where it breaks. This is often faster than trying to think your way out abstractly.
  • Simplify the problem. Ask yourself, "what if the array only had 3 elements , how would I solve it then?" Sometimes solving a tiny version reveals the general pattern.
  • Say what you're thinking, even if it's not a full idea. "I feel like there should be a way to avoid this second loop, but I'm not seeing it yet" is a completely valid thing to say. It keeps the interviewer engaged with your thinking instead of watching you sit in silence.
  • Ask for a hint directly. There's no shame in saying "I think I might be missing something , could you nudge me in a direction?" Interviewers expect this at certain problems, especially harder ones and how you use a hint matters more than needing one at all.

One candidate completely changed the interview by doing exactly this. He got stuck for a good two minutes on a hard graph problem, visibly frustrated and then said, calmly, "I know I'm missing something about how to avoid revisiting nodes , can you point me toward what I'm not seeing?" I gave him a small hint. He took it, ran with it and finished the problem well. That moment of asking for help, calmly and specifically, told me more about how he'd behave on a real team than the rest of the interview combined.

Debugging

When your code doesn't work, the goal is to find the bug through reasoning, not by randomly changing lines and hoping something fixes itself.

  • Read the error message properly if you're in an environment that shows one , a NullPointerException or IndexOutOfBoundsException tells you almost exactly where to look.
  • Trace through your own code with the failing example, line by line, tracking variable values as you go, just like you did earlier with the problem itself.
  • Check the usual suspects first , off-by-one errors in loop bounds, integer overflow on large inputs, forgetting to handle an empty input and infinite loops caused by a pointer or index that never actually moves.
  • Say what you're checking out loud , "let me check if my loop is going one index too far" , so the interviewer can see you debugging systematically, not just staring at the screen.

Debugging out loud, calmly, is one of the most underrated ways to impress an interviewer. It's a direct preview of how you'll behave the day something breaks in production at 2 AM.

Testing Your Solution

Before saying "I think this is done," actually test it , out loud, on purpose, against more than just the example the interviewer gave you.

  • A normal, everyday case
  • An empty input
  • A single-element input
  • Duplicate values, if the input allows them
  • Negative numbers, if the problem allows them
  • The smallest and largest values allowed by the constraints

Walk through each one briefly and say what you expect versus what your code would actually produce. This step alone , genuinely testing your own code instead of just declaring it finished , is something a surprising number of otherwise strong candidates skip entirely and it's one of the easiest ways to stand out without needing extra cleverness.

Time and Space Complexity

Explaining complexity well is a skill on its own, separate from actually knowing Big-O notation. A weak explanation sounds like "it's O(n) I think." A strong explanation sounds like this: "This is O(n) time because I go through the array exactly once and for each element I only do constant-time work , a hash map lookup and insert. Space is O(n) in the worst case, because if every element is unique, the hash map ends up holding all of them."

Notice the difference , the second version explains why, tying the complexity directly back to a specific part of the code, not just stating a final number. Always mention both time and space, even if space is O(1) , saying "and this uses constant extra space since I'm only using a few variables" shows you're thinking about the full picture, not just the part that's easiest to answer.

If the Interviewer Interrupts You

Getting interrupted mid-thought can feel jarring, but it almost never means you're doing badly. Here's what different interruptions usually actually mean and how to respond to each:

  • "What if the input had duplicates?" , Usually a hint that your current approach has a gap. Pause, genuinely check your logic against that case and adjust if needed.
  • "Can you think of a faster way?" , This does not always mean your current solution is wrong. Sometimes it's simply correct but not optimal and the interviewer wants to see how you push further. Say "sure, let me think about what's slow here" and work through it calmly.
  • "We're a bit short on time, can you wrap up?" , Prioritize getting to a correct, even if not perfectly optimized, solution. Say out loud, "given the time, let me finish this version and mention how I'd improve it if I had more time," and follow through.

The worst reaction to any interruption is treating it as a personal attack on your solution. The best reaction is treating it as new information that helps you build something better , because that's genuinely what it is.

Online Coding Interviews

Different online tools have small quirks worth knowing about before interview day so you're not caught off guard.

  • CoderPad / HackerRank / CodeSignal: These usually run your code for you, which is genuinely helpful , but don't let the "run" button replace your own manual testing and reasoning. Run your code, yes, but also explain what you expect before you see the actual output.
  • Google Docs (used by some smaller companies): No syntax highlighting, no auto-complete, sometimes no code execution at all. Slow down slightly and be extra careful with variable names and brackets, since typos are much easier to make and harder to catch here.
  • VS Code Live Share: Feels closest to your own coding environment, but remember the interviewer is watching your screen in real time , resist the urge to silently Google syntax on a second tab; if you genuinely forget something small, just say so honestly instead.

Across all of these tools, one habit matters more than knowing the platform: think and talk before you type, exactly like the earlier sections of this article describe. The tool changes. The thinking process doesn't.

Whiteboard Interviews

Whiteboard interviews (or their video-call equivalent, sharing a blank digital canvas) test something slightly different , they remove the safety net of running your code to check if it works.

  • Write a bit larger and slower than feels natural , cramped, rushed handwriting becomes genuinely hard to read for both of you.
  • Leave visible gaps between lines of code so you have room to insert something you missed, without cramming it awkwardly between two existing lines.
  • Trace through your logic with actual example values written next to the code, rather than trying to hold everything in your head.
  • It's completely fine to ask, "would you like me to write this in pseudocode or actual syntax?" , this question alone shows awareness of what the interviewer actually wants to see.

Since you can't run the code to prove it works, your manual walkthrough with a real example becomes the main evidence the interviewer has that your solution is correct , so don't rush or skip this part.

How Different Companies Interview

Every company has its own personality when it comes to interviews, shaped by what they actually value day to day.

  • Google tends to favor problems with a genuinely clever or non-obvious insight and interviewers often care deeply about how you arrive at that insight, not just whether you reach it.
  • Amazon blends coding rounds heavily with behavioral questions tied to their leadership principles , expect real emphasis on ownership and on how you've handled ambiguity or conflict in past work.
  • Microsoft rounds often feel more conversational and less about trick questions, with real weight placed on clean code and clear communication throughout.
  • Meta moves fast and expects you to communicate fast too , being comfortable thinking and talking simultaneously, without long silent pauses, matters more here than in most places.
  • Uber and LinkedIn frequently lean toward practical, real-world-flavored problems , things that resemble actual product or systems challenges rather than pure abstract puzzles.
  • Atlassian places noticeable weight on collaboration and communication style throughout the interview, sometimes as much as the final answer itself.
  • Adobe, Oracle and Bloomberg often run slightly more traditional DSA-style rounds, though this varies quite a bit by specific team and role.

None of this means you should prepare differently for each company in isolation , the core skills in this article transfer everywhere. It just means don't be surprised if the flavor of the conversation feels a little different depending on where you're interviewing.

Most Common Mistakes

Here are the mistakes I see over and over, almost every single week, across candidates at every experience level.

Mistake Why It Hurts You
Jumping straight into coding Leads to false starts and wasted time fixing wrong assumptions
Not asking any clarifying questions Risks solving the wrong version of the problem entirely
Ignoring given constraints Missing hints about expected time complexity
Skipping brute force entirely Interviewer can't see your reasoning journey
Never discussing complexity Leaves the interviewer unsure if you actually understand the trade-offs
Not testing the solution Bugs get discovered too late or not at all
Poor variable naming Makes your own code harder to explain and debug
Coding in total silence Interviewer has no idea what you're thinking
Giving up too early when stuck Looks like low resilience under pressure
Ignoring or dismissing hints Suggests you can't take feedback well
Arguing with the interviewer Damages the working relationship, regardless of who's technically right

If you only fix one thing from this entire article, fix "coding in total silence." It is, by a wide margin, the most common reason a technically correct solution still results in a rejection.

What Impresses Interviewers

Some behaviors quietly shift an interviewer's opinion of you far more than people realize, precisely because they're subtle and most candidates never do them.

  • Catching your own mistake before the interviewer points it out and saying so directly: "wait, that's wrong, let me fix it."
  • Naming a trade-off out loud even when nobody asked , "this is faster but uses more memory, which I think is a fair trade-off here."
  • Asking one sharp, specific clarifying question instead of five vague ones.
  • Staying calm and pleasant even when a round clearly isn't going your way.
  • Genuinely listening to a hint and adjusting, instead of just nodding and continuing exactly as before.
  • Saying "I don't know" honestly about something small, instead of guessing and hoping it doesn't come up again.

None of these require you to be a genius. They require you to be honest, calm and thoughtful , which, frankly, is rarer in interviews than raw problem-solving talent.

A Full Mock Interview, Start to Finish

Let's put all of this together on one real problem: given an array of integers, find the length of the longest consecutive sequence (the numbers don't need to be adjacent in the array, just consecutive in value , like 1, 2, 3). Example: [100, 4, 200, 1, 3, 2] → answer is 4, for the sequence 1, 2, 3, 4.

Interviewer: "Here's the problem: given an array of integers, find the length of the longest sequence of consecutive numbers. They don't need to appear next to each other in the array, just be consecutive in value."

Candidate: "Okay, let me make sure I understand , so for [100, 4, 200, 1, 3, 2], since 1, 2, 3, 4 are all present, even though they're scattered around in the array, that counts as a sequence of length 4?"

Interviewer: "Exactly right."

Candidate: "Can there be duplicate numbers in the array? And can the array be empty?"

Interviewer: "Good questions , yes, duplicates are possible and yes, the array could be empty, in which case the answer is 0."

Candidate: "Got it. Let me think through a simple approach first. If I sort the array, consecutive numbers would end up next to each other and I could just scan through once counting how long each run is. Sorting is O(n log n) and the scan afterward is O(n), so overall that's O(n log n)."

Interviewer: "That works. Can you do better?"

Candidate: "Let me think... the sorting is the expensive part. I want to find consecutive numbers without ordering everything first. If I put every number into a hash set, I get O(1) lookups , so for any number, I can instantly check if number - 1 or number + 1 also exists. The tricky part is not re-counting the same sequence multiple times. If I only start counting a sequence from its smallest number , meaning, I only begin counting at x if x - 1 is NOT in the set , then I never restart the same sequence twice and every number only gets visited a small number of times overall."

Interviewer: "Walk me through that on the example."

Candidate: "Sure , set is {100, 4, 200, 1, 3, 2}. Start with 100: is 99 in the set? No. So this could be the start of a sequence. Count forward: 100, then check 101 , not there. So sequence length 1. Next, 4: is 3 in the set? Yes , so 4 is NOT a sequence start, skip it for now. Next, 200: is 199 there? No, so start here, check 201 , not there, length 1. Next, 1: is 0 there? No, so this is a start. Count forward: 1, 2, 3, 4, then check 5 , not there. Length 4. That's our answer."

Interviewer: "Nice, go ahead and code that up."

import java.util.*;

public class LongestConsecutiveSequence {
    public static int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        Set<Integer> numSet = new HashSet<>();
        for (int num : nums) {
            numSet.add(num);
        }

        int longestLength = 0;

        for (int num : numSet) {
            // only start counting if 'num' is the beginning of a sequence
            if (!numSet.contains(num - 1)) {
                int currentNum = num;
                int currentLength = 1;

                while (numSet.contains(currentNum + 1)) {
                    currentNum++;
                    currentLength++;
                }

                longestLength = Math.max(longestLength, currentLength);
            }
        }

        return longestLength;
    }
}

Candidate: "Let me test this. For [100, 4, 200, 1, 3, 2], I'd expect 4 and tracing it through matches what we did by hand earlier. For an empty array, my early return handles that and gives 0. For a single-element array like [5], the set has just {5}, 4 isn't in it, so it starts a sequence of length 1, which is correct. What about duplicates, like [1, 2, 2, 3]? Since I'm using a set, duplicates automatically collapse to one entry, so it still correctly gives length 3."

Interviewer: "What's the time and space complexity?"

Candidate: "Time is O(n). It looks like the while loop could add up, but each number only ever gets counted as part of one sequence's forward scan, across the entire run of the algorithm , so the total work across all iterations still adds up to O(n), not more. Space is O(n) for the hash set."

Interviewer: "Good. That's it for this one."

Notice how much of this transcript is talking, not typing. That ratio , mostly thinking and talking, a smaller chunk of actual code , is exactly what a strong interview looks like in practice, not just in theory.

Checklist Before You Submit

Run through this quickly before you tell the interviewer you're done:

  • Did I restate the problem in my own words before starting?
  • Did I ask at least one meaningful clarifying question?
  • Did I walk through a small example by hand?
  • Did I explain a brute force approach, even briefly?
  • Did I explain my optimization and why it's faster?
  • Did I say my approach out loud before coding it?
  • Are my variable names clear and readable?
  • Did I test normal cases, empty input and edge cases?
  • Did I explain time and space complexity, with reasoning, not just a label?
  • Did I stay calm and polite throughout, even if I got stuck?

Interview Day Tips

A few practical, unglamorous things that genuinely affect performance on the actual day:

  • Sleep matters more than one extra hour of practice the night before. A tired brain thinks noticeably slower under pressure, no matter how much you know.
  • Test your setup in advance , camera, microphone, internet connection and the specific coding platform if you can access it beforehand. A five-minute technical hiccup at the start eats into your time and your calm.
  • Use an editor you're actually comfortable with, if you're given the choice, rather than trying out something unfamiliar for the first time during the interview itself.
  • Slow your speaking pace down slightly , nervousness naturally speeds people up and a rushed explanation is harder for the interviewer to follow, even when the underlying idea is solid.
  • Keep water nearby and don't be afraid of a short pause to collect your thoughts , a three-second silence feels much longer to you than it does to the person listening.
  • Managing nerves is mostly about reminding yourself, honestly, that getting stuck or making a small mistake is normal and expected , it's how you respond to it that's actually being watched, not whether it happens at all.

FAQ

1. What if I can't think of any approach at all, not even brute force?

Start by describing what you know about the problem out loud, even if it's not a full solution,often, talking through it surfaces an idea you didn't realize you had. If you're still stuck after a genuine attempt, ask for a hint directly rather than sitting in silence.

2. Is it okay to ask the interviewer questions during the interview?

Yes,and you should. Clarifying questions early on are expected and welcomed, not seen as a weakness.

3. What if I solve it in a way I know isn't optimal and I'm running low on time?

Say so honestly:

"I know this isn't the most optimal solution, but let me get a working version down given the time and I can talk through how I'd improve it."

A working, explained solution beats an unfinished attempt at the perfect one.

4. Should I write comments in my interview code?

A few short comments on tricky logic are fine, but don't spend valuable time writing detailed documentation,your spoken explanation is doing that job already.

5. What if I completely misunderstand the question at first?

It happens to everyone. The moment you realize it, say so clearly:

"Actually, I think I misunderstood part of this. Let me re-read it."

Then adjust your approach. Catching your own misunderstanding is far better than being told about it.

6. How many clarifying questions is too many?

There's no fixed number, but if your questions start feeling like stalling rather than genuinely narrowing down the problem, it's time to move forward with reasonable assumptions stated out loud.

7. What if the interviewer doesn't say much or give me feedback as I go?

Some interviewers are simply quieter than others,it usually doesn't reflect how you're doing. Keep talking through your own thinking regardless of how much feedback you're getting back.

8. Should I always start with brute force, even for easy problems?

Not necessarily. If the optimal approach is obvious to you immediately, you can mention brute force briefly in a sentence and move on, rather than forcing a lengthy detour.

9. What if I realize my approach is wrong halfway through coding?

Say it out loud immediately:

"Wait, I think this breaks for this case. Let me adjust."

Then fix it. This is a completely normal part of real engineering work, not a red flag.

10. Is it bad if I need a hint to solve the problem?

No. Almost every candidate needs a hint at some point across enough interviews. How you use the hint matters far more than needing one.

11. How important is coding speed?

Less important than correctness and clear thinking. A slower, well-reasoned solution generally scores better than a fast, silent one riddled with untested assumptions.

12. What should I do if I finish early?

Test your solution more thoroughly against additional edge cases and discuss any possible further optimizations, even if you don't implement them.

13. Should I memorize solutions to common problems?

Understanding the reasoning behind common patterns is far more valuable than memorizing exact solutions, since interview questions are rarely identical to what you've seen before.

14. What if I don't know the exact syntax for something in my chosen language?

Say so honestly and write pseudocode or an approximate version, explaining what you intend it to do. Most interviewers care more about logic than perfect syntax.

15. Is it okay to use a language I'm less comfortable with if the company prefers it?

Generally, use whichever language you can think fastest and clearest in, unless a specific language is explicitly required for the role.

16. What if the interviewer seems to disagree with my approach?

Ask them directly what's concerning them about it:

"What makes you feel this might not work?"

Rather than assuming you're wrong or getting defensive.

17. How do I recover if I panic mid-interview?

Pause, take a breath and go back to a small example. Grounding yourself in something concrete is usually the fastest way out of a panic spiral.

18. Do I need to know the exact Big-O notation rules perfectly?

You need a solid working understanding, not textbook-perfect definitions. Being able to explain why something is O(n) in plain language matters more than reciting formal notation.

19. What if two approaches seem equally good?

Say so and explain the trade-off between them honestly. This is often a real, non-obvious engineering decision, not a hidden "right answer" you're supposed to guess.

20. Should I ask about the company or team during the technical round?

Save most of that for the very end if time allows. The technical round is primarily about problem-solving, though a quick, genuine question at the close is completely fine.

Key Takeaways

  • Your job in a coding interview is to make your thinking visible, not just to produce correct output.
  • Understanding the problem fully, before writing any code, prevents the majority of wasted time and false starts.
  • Brute force is not something to hide , it's proof that you understood the problem and a natural stepping stone to a better solution.
  • Every optimization should come with a reason, not just a faster-looking piece of code.
  • Testing your own solution, out loud, against real cases is one of the simplest ways to stand out.
  • Getting stuck is normal. Staying calm, communicating clearly and using hints well is what actually gets evaluated in that moment.
  • The interview is a conversation, not an exam , treat the interviewer as a collaborator, not an obstacle.

Related Articles

Responses (0)

Write a response

CommentHide Comments

No Comments yet.