DEV Community

Timevolt
Timevolt

Posted on

How to Approach Any LeetCode Problem in 5 Steps: A Jedi's Guide

The Quest Begins (The "Why")

I still remember the first time I opened LeetCode after a brutal interview‑prep marathon. I stared at a problem titled “Maximum Subarray” and felt like a Padawan handed a lightsaber without any training. My brain kept looping: Do I sort? Do I use two pointers? Do I just brute‑force? After 45 minutes of fruitless tinkering I gave up, convinced I lacked the “coding gene.”

That frustration sparked a question: What do the top solvers actually do before they type a single line? I started watching their streams, reading their write‑ups, and noticed a pattern—not a secret algorithm, but a repeatable mental checklist. Once I internalized those five steps, my solve‑time dropped from hours to minutes, and the confidence that followed felt like finally mastering the Force.

If you’ve ever felt stuck in a loop of “I don’t know where to start,” this is for you. Let’s turn that confusion into clarity, step by step.

The Revelation (The Insight)

The breakthrough insight is simple: solve the problem on paper before you touch the keyboard. Top coders treat each LeetCode question like a mini‑research project. They ask themselves five questions, in this order:

  1. What is the input, and what does the output look like?
  2. What constraints matter most? (e.g., O(n) vs O(n²), space limits)
  3. Can I rephrase the problem in my own words? (often reveals a hidden pattern)
  4. What is the simplest brute‑force solution, and why is it too slow?
  5. Which classic technique (sliding window, two‑pointer, DP, BFS/DFS, etc.) bridges the gap between brute force and optimal?

Answering these questions forces you to externalize the problem, spot the “aha!” pattern, and pick the right tool—no guesswork, just deliberate reasoning.

I’ll walk through a real example to show how the checklist turns a bewildering prompt into a crystal‑clear plan.

Wielding the Power (Code & Examples)

Problem: Maximum Subarray (LeetCode 53)

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Step‑by‑step checklist in action

Step My thought process Outcome
1. Input/Output Input: list of ints (could be negative). Output: a single int (max sum). Clear contract.
2. Constraints 1 ≤ nums.length ≤ 10⁵, values ∈ [‑10⁴, 10⁴]. Need O(n) time, O(1) space. Rules out O(n²) DP tables.
3. Rephrase “Find the biggest sum you can get by adding a consecutive chunk of numbers.” Sounds like we might keep a running total and drop it when it hurts.
4. Brute force Try every start index, extend to every end index, keep max → O(n²). Too slow for 10⁵. Need smarter.
5. Technique This is the classic Kadane’s algorithm: maintain current_sum (best sum ending at i) and global_max. If current_sum drops below 0, reset it to 0 because a negative prefix can’t help future sums. O(n) time, O(1) space.

The “before” – a frantic attempt

# Before: naive O(n^2) – times out on large cases
def maxSubArray(nums):
    best = float('-inf')
    for i in range(len(nums)):
        cur = 0
        for j in range(i, len(nums)):
            cur += nums[j]
            best = max(best, cur)
    return best
Enter fullscreen mode Exit fullscreen mode

Running this on the maximal test set feels like watching a slow‑motion boss fight in Contra—you know you’ll lose if you don’t power‑up.

The “after” – applying the checklist

# After: Kadane’s algorithm – O(n) time, O(1) space
def maxSubArray(nums):
    # Step 5 insight: reset when running sum becomes negative
    current_sum = global_max = nums[0]   # handle all‑negative case
    for x in nums[1:]:
        # Either extend the previous subarray or start fresh at x
        current_sum = max(x, current_sum + x)
        global_max = max(global_max, current_sum)
    return global_max
Enter fullscreen mode Exit fullscreen mode

Why it works:

  • At each index we decide whether the best subarray ending here is just the current element (x) or the previous best subarray extended by x.
  • If extending makes the sum smaller than starting fresh, we drop the past—exactly the “reset when negative” rule.
  • global_max tracks the best we’ve seen anywhere.

The moment the current_sum = max(x, current_sum + x) line clicked, I felt like Neo seeing the Matrix code—whoa, the problem reduced to a single, elegant update rule.

Common traps to avoid

Trap What happens How to dodge it
Resetting to zero when all numbers are negative Returns 0 (incorrect) because the empty subarray isn’t allowed. Initialize both trackers with nums[0] and use max(x, current_sum + x).
Forgetting to update global_max inside the loop Returns the sum of the last processed element only. Update global_max after each current_sum calculation.
Using extra arrays for DP O(n) space, passes but misses the optimal O(1) space insight. Remember the constraint: O(1) space is enough; keep only two variables.

Why This New Power Matters

Internalizing those five steps turned LeetCode from a guessing game into a repeatable craft. I now approach any problem—whether it’s graph traversal, dynamic programming, or a tricky string manipulation—with the same mental scaffolding. The payoff?

  • Faster solves: What used to take 30+ minutes now often finishes under 5.
  • Less anxiety: Knowing I have a checklist eliminates the dread of “blank page syndrome.”
  • Deeper learning: By forcing myself to articulate constraints and rephrase the problem, I start recognizing patterns across unrelated questions, which is the real skill interviewers test.

Think of it as leveling up from a button‑masher to a combo‑master in a fighting game—you still need to practice the moves, but now you know which move to throw in each situation.


Your Turn: Grab Your Lightsaber

Pick a LeetCode problem you’ve avoided because it looked intimidating. Apply the five‑step checklist on paper (or a note‑taking app) before you write a single line of code. When the “aha!” moment hits, notice how the solution almost writes itself.

Drop a comment below with the problem you tackled and which step gave you the breakthrough—let’s celebrate each other’s victories! May the Force be with your algorithms. 🚀

Top comments (0)