Space
Open
From Fieldwork
Scales
Archive
Used for: Longest Substring Without Repeating Characters, Min Size Subarray Sum.
Visual Logic: An inchworm. The head (right) moves forward to eat. If the inchworm gets too full (invalid state), the tail (left) moves forward to digest/shrink.
def sliding_window(s):
left = 0
window_state = {} # Or set(), or integer sum
best_len = 0
# 1. Expand (Right pointer moves)
for right in range(len(s)):
char = s[right]
window_state[char] = window_state.get(char, 0) + 1
# 2. Shrink (While invalid)
# Example: If we have duplicates
while window_state[char] > 1:
left_char = s[left]
window_state[left_char] -= 1
left += 1
# 3. Update Result (After fixing the window)
best_len = max(best_len, right - left + 1)
return best_lenPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode