AlgoMaster Logo

Chapter 3: Problem-Solving Framework

20 min readUpdated January 17, 2026
Listen to this chapter
Unlock Audio

Chapter 3: Problem-Solving Framework

Here is a scenario that plays out in thousands of coding interviews every day: a candidate sees a problem, immediately starts typing, gets halfway through, realizes their approach does not work, panics, tries to salvage it, runs out of time, and leaves defeated.

The frustrating part? They probably knew enough to solve the problem. What they lacked was not knowledge but a systematic approach.

This chapter gives you that approach. A framework you can apply to any problem, whether you are practicing on LeetCode, interviewing at Google, or debugging production code at 2 AM. The techniques here will not just help you solve more problems. They will help you solve them faster, with fewer bugs, and with the confidence that comes from knowing exactly what to do next.

Why You Need a Framework

When you face a new problem, your brain has two modes it can operate in. The first is pattern matching: you recognize the problem as similar to something you have solved before, and the solution flows naturally. This is the goal of learning DSA patterns, and it works beautifully when it works.

But what happens when you do not recognize the pattern? What happens when the problem is genuinely new, or when interview pressure makes your mind go blank? This is where most people fail. Without a systematic approach, they either freeze or start coding randomly, hoping something will work.

A framework gives you a fallback. It turns "I have no idea what to do" into "Let me work through my process." Even when you are stuck, you know the next step. This alone reduces anxiety and improves performance.

The framework we will learn has five phases: Understand, Match, Plan, Implement, and Verify. Let us go through each one in detail.

Phase 1: Understand the Problem

The biggest mistake candidates make is starting to code before they fully understand what they are solving. This seems obvious, but under time pressure, the urge to "get started" is powerful. Resist it.

Read Carefully, Then Read Again

Problem statements are carefully written. Every word matters. Read the entire problem at least twice before doing anything else. Pay attention to:

  • Input format: What exactly are you given? An array? A string? A tree? What are the types?
  • Output format: What exactly should you return? A number? A list? A boolean?
  • Constraints: What are the size limits? This tells you what time complexity you need.
  • Edge cases mentioned: The problem often hints at tricky cases.

Ask Clarifying Questions

In an interview, you are expected to ask questions. Interviewers intentionally leave some details ambiguous to see if you will clarify. Here are questions you should always consider:

CategoryExample Questions
InputCan the array be empty? Can it contain negative numbers? Are there duplicates?
OutputIf there are multiple valid answers, can I return any of them? What should I return if no solution exists?
ConstraintsWhat is the maximum size of the input? Do I need to handle very large numbers?
FormatIs the input sorted? Is the tree a BST or any binary tree? Is the graph directed or undirected?

Even on LeetCode, mentally ask these questions. The constraints section usually answers them, but developing this habit prepares you for interviews.

Work Through Examples

Before thinking about solutions, make sure you understand the problem by tracing through the given examples manually. Then create your own examples, especially:

  • Small cases: The simplest possible input
  • Edge cases: Empty input, single element, all same elements
  • Large cases: To verify your understanding scales

Let us apply this to a real problem.

Problem: Two Sum

Understanding checklist:

  • Input: Array of integers, one integer target
  • Output: Two indices (as an array)
  • Constraints: Exactly one solution exists, cannot use same element twice
  • Questions I would ask: Can the array have negative numbers? (Yes, by the examples.) Is the array sorted? (Not specified, so assume no.)

Tracing examples:

Now I truly understand what the problem is asking.

Phase 2: Match to Known Patterns

Once you understand the problem, the next step is to see if it matches any patterns you know. This is where your study of DSA patterns pays off. You are not starting from scratch. You are searching your mental library for similar problems.

Pattern Recognition Questions

Ask yourself these questions to identify potential approaches:

QuestionSuggests
Am I looking for a pair/triplet that satisfies a condition?Two pointers, hash map
Am I looking for a contiguous subarray?Sliding window, prefix sum
Is the input sorted, or would sorting help?Binary search, two pointers
Do I need to explore all possibilities?Backtracking, BFS/DFS
Does the problem have optimal substructure?Dynamic programming, greedy
Am I working with a tree or graph?BFS, DFS, tree traversal
Do I need O(1) lookup?Hash map, hash set
Do I need to track frequency/count?Hash map
Am I looking for top K or Kth element?Heap, quickselect
Does the problem involve intervals?Sorting + greedy, merge intervals

Building a Pattern Library

Over time, you will build a mental map connecting problem characteristics to approaches:

What If Nothing Matches?

Sometimes you genuinely do not recognize the pattern. That is okay. Fall back to first principles:

  1. Start with brute force: What is the simplest solution that would work, ignoring efficiency?
  2. Identify the bottleneck: What makes the brute force slow?
  3. Look for wasted work: Are you recalculating something? Can you cache it?
  4. Consider the constraints: What time complexity do you need? Work backward from there.

For Two Sum, the brute force is checking every pair: O(n²). The bottleneck is that for each number, we scan the entire array to find its complement. The insight is that we can use a hash map to check for the complement in O(1), giving us O(n) overall.

Phase 3: Plan Your Approach

Now comes the critical phase that many people skip: planning. Before writing any code, you should have a clear, step-by-step plan that you could explain to someone else.

Write Pseudocode or Steps

Do not write actual code yet. Write out the logic in plain English or pseudocode. This forces you to think through the algorithm without getting distracted by syntax.

Two Sum Plan:

Walk Through Your Plan with an Example

Before coding, trace through your plan with a concrete example. This catches logical errors early.

The plan works. Now you can code with confidence.

Consider Edge Cases in Your Plan

Before implementing, think about edge cases:

  • Empty array? (Problem says exactly one solution exists, so array has at least 2 elements)
  • All elements same? (e.g., [3, 3], target = 6, should return [0, 1])
  • Negative numbers? (Our plan handles them fine)
  • Large numbers? (Hash map handles them fine)

If your plan does not handle an edge case, modify it now rather than debugging later.

Communicate Your Plan (In Interviews)

In an interview, explain your plan before coding. Say something like:

This accomplishes several things:

  • Shows the interviewer you have a plan
  • Gives them a chance to redirect you if you are on the wrong track
  • Demonstrates communication skills
  • Buys you thinking time while you talk

Phase 4: Implement the Solution

Now, finally, you can write code. But even here, there are techniques to write cleaner code faster with fewer bugs.

Start with the Skeleton

Write the function signature and return statement first. This ensures your code compiles and establishes the structure.

Translate Your Plan Line by Line

Your pseudocode becomes your guide. Translate each step into code:

Use Meaningful Variable Names

Your code should read like your plan. Avoid single letters for anything but loop indices:

BadGood
mmap or numToIndex
ccomplement
ttarget
nnums or numbers

In interviews, readability matters. The interviewer is reading your code in real time.

Handle Edge Cases Explicitly

If there are edge cases that need special handling, put them at the top of your function:

Avoid Common Coding Mistakes

MistakePrevention
Off-by-one errorsDouble-check loop bounds: < length vs <= length
Null pointer exceptionsCheck for null before accessing
Integer overflowUse long for intermediate calculations if needed
Modifying while iteratingUse index-based loop or create a copy
Wrong return typeCheck the function signature

Phase 5: Verify Your Solution

You have written the code. Before declaring victory, verify it works.

Test with Given Examples

Run through the provided examples manually or with actual test cases:

Test Edge Cases

Create tests for the edge cases you identified:

Trace Through Manually for Bugs

If something fails, do not just stare at the code. Trace through it step by step with the failing input:

Analyze Time and Space Complexity

Always be ready to state the complexity of your solution:

  • Time: O(n) where n is the length of the array. We iterate once, and hash map operations are O(1) average.
  • Space: O(n) for the hash map, which in the worst case stores all elements.

In interviews, state this proactively:

The Complete Framework Summary

Here is the complete framework in one view:

Time Management in Interviews

A typical coding interview is 45-60 minutes. Here is how to allocate that time:

PhaseTimeActivities
Understand5-7 minRead, ask questions, work examples
Match + Plan5-10 minIdentify approach, write pseudocode, communicate
Implement15-20 minWrite clean, working code
Verify5-10 minTest, debug, analyze complexity
Buffer5-10 minFollow-up questions, optimization discussion

Common time mistakes:

  • Rushing to code: Spending only 2 minutes on Understand/Match/Plan leads to wrong approaches
  • Over-planning: Spending 20 minutes planning a perfect solution leaves no time to code
  • Perfectionist debugging: If code mostly works, discuss the bug verbally rather than spending 15 minutes fixing it

If you are running low on time, communicate:

Applying the Framework: A Complete Example

Let us apply the entire framework to a new problem.

Problem: Valid Parentheses

Phase 1: Understand

Reading carefully:

  • Input: String containing only bracket characters
  • Output: Boolean (valid or not)
  • Three conditions define validity

Clarifying questions:

  • Can the string be empty? (Need to check, probably valid)
  • What about nested brackets like ([{}])? (Valid per the rules)
  • What about ([)]? (Invalid, wrong order)

Working examples:

Phase 2: Match

Pattern recognition:

  • This involves matching pairs
  • Order matters (LIFO: last opened must be first closed)
  • LIFO suggests a stack

Key insight: When I see an open bracket, I push it. When I see a close bracket, I check if the top of the stack is the matching open bracket. If not, invalid. At the end, the stack should be empty.

Phase 3: Plan

Walk through with example:

Phase 4: Implement

Phase 5: Verify

Test given examples:

Test edge cases:

Complexity analysis:

  • Time: O(n) where n is the length of the string. We process each character once.
  • Space: O(n) in the worst case (all open brackets like ((((().

Common Mistakes and How to Avoid Them

MistakeSymptomPrevention
Not understanding the problemWrong approach entirelySpend more time in Phase 1, ask questions
Jumping to codeGetting stuck halfway, rewritingAlways plan before implementing
Ignoring constraintsTLE (Time Limit Exceeded)Check constraints, know what complexity you need
Not testingWrong answer on edge casesAlways verify with examples and edge cases
Poor communicationInterviewer cannot followExplain your thinking out loud
OvercomplicatingConvoluted code, bugsStart simple, optimize if needed
Giving up too earlyNot solving solvable problemsStick to the framework, stay calm

Building Your Problem-Solving Muscle

The framework becomes second nature with practice. Here is how to train:

Daily Practice Routine

  1. Pick one problem appropriate to your level
  2. Set a timer (30-45 minutes)
  3. Apply the full framework, even if it feels slow at first
  4. Write down what patterns you used or should have recognized
  5. Review the solution if you got stuck, understand why it works
  6. Revisit in a week to test retention

Track Your Progress

Keep a log of problems you solve:

DateProblemPattern UsedSolved Alone?TimeNotes
1/15Two SumHash mapYes12 minComplement lookup pattern
1/15Valid ParenthesesStackYes18 minLIFO for matching pairs
1/163SumTwo pointersHint needed35 minSort first, then two pointers

This helps you identify weak areas and track improvement.

Deliberate Difficulty Progression

  • Weeks 1-2: Easy problems, focus on the framework
  • Weeks 3-4: Easy/Medium problems, focus on pattern recognition
  • Weeks 5-8: Medium problems, optimize for speed
  • Weeks 9+: Medium/Hard problems, simulate interview conditions

Interview Questions

Q1: Why should you spend time understanding and planning before coding?

Spending time on understanding and planning prevents wasted effort and reduces bugs. If you misunderstand the problem, you might solve the wrong thing entirely. If you start coding without a plan, you often get stuck halfway through and have to restart. The few minutes invested in understanding and planning save many more minutes of debugging and rewriting. In interviews, this also demonstrates to the interviewer that you think before you act, which is a valuable engineering trait.

Q2: What should you do if you do not recognize the pattern for a problem?

Start with brute force. Ask yourself: what is the simplest solution that would work if efficiency did not matter? Often this means trying all possibilities, nested loops, or recursion that explores every path. Once you have a brute force solution, identify its bottleneck. What makes it slow? Are you recalculating something repeatedly? Is there redundant work? This analysis often reveals the optimization. Additionally, look at the constraints to understand what time complexity you need, which narrows down possible approaches.

Q3: How should you handle edge cases in your solution?

First, identify edge cases during the Understand phase by asking questions like: Can the input be empty? Can values be negative? Are there duplicates? Then, during the Plan phase, ensure your algorithm handles these cases, either through the main logic or explicit checks. During Implementation, add explicit edge case handling at the top of your function when needed. Finally, during Verify, test your code with edge cases to confirm they work. It is much easier to handle edge cases proactively than to debug them later.

Q4: How should you manage your time in a 45-minute coding interview?

Allocate roughly 5-7 minutes to understand the problem and ask clarifying questions, 5-10 minutes to identify your approach and explain your plan, 15-20 minutes to implement your solution, and 5-10 minutes to test and verify. Keep some buffer for discussion. If you are running low on time, communicate with the interviewer. It is better to have working code for the main cases with a verbal explanation of edge case handling than to have incomplete code that handles everything. Avoid spending too long on any single phase.

Q5: What should you do if your code has a bug during an interview?

Stay calm and systematic. First, identify which test case fails. Then trace through your code line by line with that specific input, writing down variable values at each step. Compare what actually happens to what you expected. The bug is where reality diverges from expectation. Common culprits are off-by-one errors in loop bounds, incorrect conditional logic, or forgetting to handle a specific case. If time is short, explain to the interviewer what you think the bug is and how you would fix it, even if you do not have time to implement the fix.

Summary

This chapter gave you a systematic framework for solving coding problems:

  1. Understand: Read carefully, ask questions, work through examples, identify edge cases
  2. Match: Connect problem characteristics to known patterns, fall back to brute force if needed
  3. Plan: Write pseudocode, walk through with examples, communicate your approach
  4. Implement: Start with skeleton, translate plan to code, use clear names, handle edge cases
  5. Verify: Test with examples and edge cases, trace through bugs, state complexity

The framework feels slow at first, but with practice it becomes automatic. The structure gives you confidence: even when you do not immediately see the answer, you know what to do next.

In the next chapter, we will cover Recursion Fundamentals. Recursion is the foundation for many DSA topics including trees, graphs, backtracking, and dynamic programming. Mastering recursive thinking early will make everything else easier.

References