I stopped brute-forcing LeetCode once I realized the difference

Jamie5 Advanced 1h ago 182 views 0 likes 2 min read

For a long time, I treated coding challenges like a guessing game. I remember hitting a wall with the "Longest Substring Without Repeating Characters" problem. My first instinct was a double-loop brute force—basically checking every single possible substring. It worked for the easy test cases, but the moment I hit the larger ones, the runtime exploded to $O(n^2)$, and my laptop started sounding like a jet engine. The frustration wasn't that I didn't know Python; it was that I didn't have a repeatable mental model to tackle these problems efficiently.

The breakthrough came when I stopped writing code and started describing the problem in plain English: I just needed to find the longest stretch of characters where no letter appeared twice. That's when the sliding window concept clicked. Instead of resetting my search every time I hit a duplicate, I could just slide the left boundary of my "window" forward.

I've since realized that most "hard" array or string problems can be cracked using a consistent five-step AI workflow for problem solving:

1. Isolate the core constraint (e.g., what exactly makes a substring "invalid"?).
2. Pick a state-tracking structure (usually a hash map or set for $O(1)$ lookups).
3. Set up two pointers (a left and right boundary).
4. Expand and shrink (move the right pointer to explore, and the left pointer to fix constraint violations).
5. Track the global optimum (update your maximum or minimum result whenever the window is valid).

To show the difference in performance, here is how the brute force approach fails compared to the optimized version.

The inefficient way (Brute Force $O(n^2)$):

def lengthOfLongestSubstring_brute(s: str) -> int:
    n = len(s)
    best = 0
    for i in range(n):
        seen = set()
        for j in range(i, n):
            if s[j] in seen: # duplicate – stop this start position
                break
            seen.add(s[j])
            best = max(best, j - i + 1)
    return best

The problem here is that the inner loop restarts the seen set for every single index, repeating massive amounts of work. If you're dealing with a string of $10^5$ characters, this will crawl.

The optimized way (Sliding Window $O(n)$):

def lengthOfLongestSubstring(s: str) -> int:
    """
    Sliding window with a hash map storing the most recent index of each character.
    """
    last_index = {} # char -> latest position
    left = 0 # start of the current window
    max_len = 0

    for right, ch in enumerate(s):
        # If ch was seen inside the current window, jump left just past its previous spot
        if ch in last_index and last_index[ch] >= left:
            left = last_index[ch] + 1

        # Update the most recent position of ch
        last_index[ch] = right

        # Window [left, right] is now valid
        max_len = max(max_len, right - left + 1)

    return max_len

This approach is a total victory because last_index allows us to jump the left pointer instantly. We never move backward, which guarantees linear time complexity. One huge gotcha: always remember the last_index[ch] >= left check. If you omit that, you might accidentally move your left pointer backward to a character that's already outside your current window, which breaks the whole logic.

AI ProgrammingAI Codingproblemsolving

All Replies (3)

C
CameronOwl Expert 1h ago
Took me months to realize sliding windows were the key. Game changer for my runtime.
0 Reply
R
Riley2 Advanced 1h ago
Did you find that using a hash map or a frequency array worked better for lookups?
0 Reply
T
TaylorDreamer Intermediate 59m ago
Learning to map the problem to a specific pattern first saves so much time.
0 Reply

Write a Reply

Markdown supported