DEV Community

Timevolt
Timevolt

Posted on

How to Approach Any LeetCode Problem in 5 Steps – A 'Matrix' Mindset

The Quest Begins (The "Why")

I still remember the first time I opened LeetCode after a brutal interview. I stared at the prompt “Given an array of integers, return indices of the two numbers that add up to a specific target.” My brain felt like it was stuck in a loading screen—endless loops, off‑by‑one errors, and that sinking feeling that I’d never crack it. I’d spent hours scribbling brute‑force O(n²) solutions, only to watch the test cases time out. Honestly, I wondered if I was missing some secret cheat code that the top coders seemed to have built‑in.

That frustration sparked a question: What if there was a repeatable mental framework, like a combo move in a fighting game, that could turn any vague problem into a clear path forward? I started watching how seasoned engineers talk through problems, and I noticed a pattern. They didn’t jump straight to code; they followed a short, deliberate checklist. I decided to test it on a real problem, and the breakthrough felt like Neo finally seeing the code of the Matrix—everything snapped into focus.

The Revelation (The Insight)

The framework I distilled into five steps is simple, but each step forces you to confront a different layer of the problem. Think of it as a quest log:

  1. Restate the problem in your own words – Strip away the jargon. What are we really being asked to do?
  2. Draw a concrete example – Walk through a tiny case with pen and paper (or a comment block).
  3. Identify the naïve approach and its cost – Usually a brute‑force loop; note why it fails under constraints.
  4. Look for a pattern or invariant – Is there a sorted property? A frequency count? A sliding window?
  5. Map the pattern to a data structure/algorithm – Choose the tool that makes the invariant O(1) or O(log n) per step.

The “aha!” moment for me came on step 4. I realized that most LeetCode problems hide a state that can be updated incrementally as you scan the input. Once you spot that state, the solution often collapses into a single pass.

Let’s see this in action with a classic problem: Two Sum (LeetCode #1).

Wielding the Power (Code & Examples)

Step 1 – Restate

“Given an array nums and an integer target, find two distinct indices i and j such that nums[i] + nums[j] == target. Return them as a list.”

Step 2 – Draw an example

nums = [2, 7, 11, 15]
target = 9
Enter fullscreen mode Exit fullscreen mode

We scan:

  • At index 0, value 2 → we need 7 (9‑2).
  • At index 1, value 7 → we need 2 (9‑7).

Step 3 – Naïve approach

Brute force: check every pair → O(n²) time, O(1) space. For n = 10⁵ this times out.

Step 4 – Find the pattern

While iterating, we need to know if we’ve already seen the complement (target − current). That’s a classic “look‑up” problem → we need a hash map that stores value → index.

Step 5 – Implement

Before (the struggle)

def two_sum_bruteforce(nums, target):
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []
Enter fullscreen mode Exit fullscreen mode

Trap: Forgetting to start the inner loop at i+1 leads to using the same element twice or doing redundant work.

After (the victory)

def two_sum(nums, target):
    """
    Returns indices of the two numbers that add up to target.
    Uses a hash map for O(n) time and O(n) space.
    """
    seen = {}                     # value -> index
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:    # aha! we already saw the needed partner
            return [seen[complement], i]
        seen[num] = i             # store current number for future look‑ups
    return []                     # if no solution exists (per problem guarantee, this line rarely runs)
Enter fullscreen mode Exit fullscreen mode

Trap: Overwriting seen[num] before checking the complement would cause us to miss a pair where the two numbers are identical (e.g., [3,3] target 6). The order above—check first, then store—avoids that pitfall.

When I first wrote the hash‑map version, I felt like I’d just unlocked a new ability in an RPG. The runtime dropped from seconds to milliseconds, and the test suite passed on the first try.

Why This New Power Matters

Adopting this five‑step checklist does more than solve a single problem—it rewires your intuition.

  • Confidence: You stop staring at a blank editor and start asking, “What state am I tracking?”
  • Speed: Most medium‑level problems become a single pass with a hash map, set, or two‑pointer technique.
  • Resilience: When a problem throws a curveball (like needing a monotonic stack or a binary search), you already have the habit of looking for the invariant before jumping to code.

It’s the difference between wandering a dungeon without a map and having a clear quest log that tells you exactly which lever to pull next.

Your Turn

Pick any LeetCode problem you’ve been avoiding—maybe “Longest Substring Without Repeating Characters” or “Maximum Product Subarray.” Run it through the five steps, write out the example, spot the invariant, and watch the solution emerge.

Challenge: Comment below with the problem you tackled and the “aha!” insight you discovered. Let’s turn those frustrating debugging sessions into victory streaks together!

Happy coding, and may your algorithms be ever in your favor. 🚀

Top comments (0)