Skip to content
← Back to Blog

How to Solve Any LeetCode Problem: A 5-Step Framework

10 min read

You have solved 200 LeetCode problems, but when a new one appears you still stare at the screen. The issue is not effort — it is the absence of a repeatable process. Top candidates do not freestyle every problem. They follow a framework that converts any problem statement into working code in under 30 minutes.

This guide gives you that framework: five concrete steps you can apply to every single problem, whether it is an easy array question or a hard graph problem. We will also give you a pattern-matching cheat-sheet so you can jump from "I have no idea" to "I know exactly which technique to use" in seconds.

Step 1: Understand the Problem

Most wrong answers start with a misunderstood problem. Before you think about algorithms, make sure you know exactly what is being asked.

1A — Restate the inputs and outputs

Say it out loud (or write it down): "I receive an array of integers and a target integer. I must return the indices of two numbers that sum to target." If you cannot restate the problem clearly, you do not understand it yet.

1B — Clarify the constraints

Constraints tell you which algorithms are even feasible. They are the single strongest signal for choosing a pattern.

  • n ≤ 20 — brute force, backtracking, bitmask DP are all fine
  • n ≤ 10⁴ — O(n²) is acceptable; two pointers, sliding window
  • n ≤ 10⁵ — O(n log n) or O(n); sorting, binary search, hash map
  • n ≤ 10⁷+ — must be O(n) or O(log n); math, prefix sum, binary search

1C — Walk through examples and edge cases

Work through the provided examples by hand. Then invent your own edge cases:

  • Empty input (n = 0)
  • Single element
  • All duplicates
  • Already sorted / reverse sorted
  • Negative numbers, zeros
  • Maximum constraint value

If your approach handles these, it will almost certainly handle everything in between. This step typically takes 2–3 minutes but saves 10+ minutes of debugging.

Step 2: Identify the Pattern

This is the step where most people get stuck, and where this framework saves the most time. Instead of guessing, use two signals: the input data structure and what the problem asks you to do.

Pattern Identification Cheat-Sheet

When you see a certain signal in the problem, try the corresponding pattern:

If you see…Try this pattern
Sorted array, find pair/targetTwo Pointers
Contiguous subarray/substring, window conditionSliding Window
Subarray sum with negatives, range sum queriesPrefix Sum
Linked list cycle, middle element, palindromeFast & Slow Pointers
Overlapping intervals, merge/insertMerge Intervals
Sorted array, minimize/maximize, search spaceBinary Search
Tree traversal, path problems, subtree queriesDFS
Shortest path (unweighted), level-order traversalBFS
Top/bottom K elements, running medianTop K / Heap
Counting frequencies, pair with complementHash Map Counting
Max/min subarray, contiguous sumKadane's Algorithm
Next greater/smaller element, histogram areasMonotonic Stack
All combinations/permutations, constraint satisfactionBacktracking
Optimal substructure, overlapping sub-problemsDynamic Programming
Dependency ordering, course scheduleTopological Sort
Connected components, "are X and Y connected?"Union Find
Prefix matching, autocomplete, word search in dictionaryTrie

Not sure which row fits? Use the AlgoArk Decision Tree — it asks you yes/no questions and narrows down to the correct pattern automatically.

What if multiple patterns seem to fit?

This is normal. Many problems combine patterns ( Binary Search + Greedy, BFS + Hash Map). When two patterns seem plausible, pick the one whose time complexity matches the constraint best. For a deeper look at combination patterns, read our Pattern Combinations Guide.

Step 3: Write Pseudocode First

Never jump straight to code. Pseudocode lets you validate your logic without worrying about syntax. It is also what interviewers want to see — they can follow along, give feedback, and spot issues before you spend five minutes coding a wrong approach.

Example: Two Sum

Problem: given an array and a target, return indices of two numbers that add up to target.

# Pattern: Hash Map (complement lookup)

function twoSum(nums, target):
    create empty hash map: complement -> index

    for i from 0 to len(nums) - 1:
        complement = target - nums[i]

        if complement exists in map:
            return [map[complement], i]

        map[nums[i]] = i

    return []  # no solution found

Example: Maximum Subarray (Kadane's)

# Pattern: Kadane's Algorithm

function maxSubarray(nums):
    currentSum = nums[0]
    maxSum     = nums[0]

    for i from 1 to len(nums) - 1:
        # Either extend the current subarray or start fresh
        currentSum = max(nums[i], currentSum + nums[i])
        maxSum     = max(maxSum, currentSum)

    return maxSum

Example: Sliding Window — Longest Substring Without Repeating

# Pattern: Sliding Window

function lengthOfLongestSubstring(s):
    create empty set: charSet
    left = 0
    maxLen = 0

    for right from 0 to len(s) - 1:
        while s[right] in charSet:
            remove s[left] from charSet
            left += 1

        add s[right] to charSet
        maxLen = max(maxLen, right - left + 1)

    return maxLen

Notice how each pseudocode block starts with a comment naming the pattern. This anchors your thinking and communicates intent to the interviewer. After writing pseudocode, trace through your example from Step 1 to verify correctness before moving on.

Step 4: Implement and Test

Now translate your pseudocode to real code. Because the logic is already validated, this step is mostly mechanical.

Implementation checklist

  • Use descriptive variable names: left, right, windowSum — not i, j, s
  • Handle edge cases first (empty array, single element, null input) with early returns
  • Get the brute force working before optimizing — a correct O(n²) beats a buggy O(n)
  • Use helper functions if a block of logic is complex

Testing strategy

After writing code, test with at least three cases:

1. Happy path: the normal case from the problem statement.

2. Edge case: empty input, single element, all identical values.

3. Stress case: large input to mentally verify your complexity claim.

Walk through the code line by line with your happy-path example. Track variables in your head (or on paper). If any variable has an unexpected value, you have found a bug. Fix it before submitting.

Step 5: Optimize

Once your solution is correct, ask yourself: can I do better? Interviewers often follow up with "Can you improve the time or space complexity?"

Common optimization moves

  • Hash map for O(1) lookup: replace nested loops with a hash map to turn O(n²) into O(n).
  • Sort + two pointers: for pair/triplet problems, sorting unlocks two pointers at O(n log n).
  • Binary search on answer: if you can frame the problem as "is X possible?" with a monotonic check function, binary search on the answer space works.
  • Sliding window instead of prefix sum: when the window condition is monotonic (all positive values), sliding window avoids a hash map entirely.
  • DP space reduction: if your DP only depends on the previous row, reduce from O(n²) space to O(n).
  • Heap for streaming top-K: instead of sorting the entire array, maintain a min-heap of size K with Top K.

State your complexity explicitly

Always tell the interviewer: "This runs in O(n) time and O(n) space because we iterate once and store at most n entries in the hash map." Naming the complexity shows mastery and prevents follow-up questions.

Putting It All Together: A Full Walkthrough

Let us apply the framework to a real problem: "Given an array of integers and an integer k, find the maximum sum of a contiguous subarray of size k."

Step 1 — Understand:

Input: array of integers, integer k. Output: single integer (the max sum). Constraints: 1 ≤ k ≤ n ≤ 10⁵. Edge case: k = n means the answer is the sum of the entire array.

Step 2 — Pattern:

Contiguous subarray of fixed size → Sliding Window. The window size is fixed at k.

Step 3 — Pseudocode:

windowSum = sum(nums[0..k-1])
maxSum = windowSum

for i from k to len(nums) - 1:
    windowSum += nums[i] - nums[i - k]
    maxSum = max(maxSum, windowSum)

return maxSum

Step 4 — Test:

nums = [2, 1, 5, 1, 3, 2], k = 3. Initial window: 2+1+5 = 8. Slide: 1+5+1 = 7, 5+1+3 = 9, 1+3+2 = 6. Max = 9. Correct.

Step 5 — Optimize:

Already O(n) time and O(1) space. No further optimization needed.

Frequently Asked Questions

"What if I cannot identify any pattern?"

Start with brute force. Write the O(n²) or O(2ⁿ) solution first. Then look at what is causing the inefficiency — repeated computation? That hints at DP. Scanning an array for each element? That hints at a hash map. The brute force often reveals the pattern.

"How many problems should I practice?"

Quality beats quantity. Doing 100 problems with deliberate pattern practice is better than grinding 500 random ones. Aim for 3–5 problems per pattern. Use our Top 50 LeetCode by Pattern list as a starting point.

"Should I memorize solutions?"

No. Memorize patterns, not solutions. If you know that "contiguous subarray with a condition" maps to Sliding Window, you can solve dozens of variations without memorizing any of them. That is the entire philosophy behind AlgoArk.

"How do I get faster at coding interviews?"

Speed comes from two things: pattern recognition (so you skip the "what algorithm do I use?" phase) and code fluency (so the implementation is automatic). Practice both separately. Use the AlgoArk Quiz for pattern recognition drills, and time yourself on implementation.

The 5-Step Framework at a Glance

1. Understand — restate inputs/outputs, read constraints, list edge cases

2. Identify the pattern — match input type + ask type to the table above

3. Pseudocode — write human-readable logic, trace with an example

4. Implement & test — translate to code, run 3 test cases

5. Optimize — reduce time/space, state complexity explicitly

Related reads:

Stop guessing patterns — start recognizing them

The fastest way to master Step 2 is deliberate practice. Use the decision tree to drill pattern identification, or take the quiz to test yourself under pressure.