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:
-
Isolate the core constraint (e.g., what exactly makes a substring "invalid"?).
-
Pick a state-tracking structure (usually a hash map or set for $O(1)$ lookups).
-
Set up two pointers (a left and right boundary).
-
Expand and shrink (move the right pointer to explore, and the left pointer to fix constraint violations).
-
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 in last_index and last_index[ch] >= left:
left = last_index[ch] + 1
last_index[ch] = right
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.