Pattern Overview
Sliding window and two pointers are the two most frequently tested algorithmic patterns in coding interviews. They transform brute-force O(n²) or O(n³) solutions into elegant O(n) approaches by maintaining a dynamic range over the input.
When to Use Each Pattern
| Pattern | Use When | Key Signal in Problem |
|---|---|---|
| Fixed Window | Window size is given or constant | "subarray of size K", "window of length K" |
| Variable Window | Window size depends on a condition | "minimum length subarray", "longest substring with at most..." |
| Two Pointers (same direction) | Remove/partition elements in-place | "remove duplicates", "move zeroes", "partition" |
| Two Pointers (opposite direction) | Search pairs in sorted data | "two sum in sorted array", "container with most water" |
Sliding Window Template
The core idea: maintain a window [left, right] and expand/shrink it based on a condition. Here is the universal template:
def sliding_window(arr, condition):
"""Universal sliding window template.
Works for both fixed and variable window problems.
Adjust the shrink condition based on the problem.
"""
left = 0
result = 0 # or float('inf') for minimization
window_state = {} # track window contents
for right in range(len(arr)):
# 1. Expand: add arr[right] to window state
window_state[arr[right]] = window_state.get(arr[right], 0) + 1
# 2. Shrink: while window is invalid, remove from left
while not condition(window_state):
window_state[arr[left]] -= 1
if window_state[arr[left]] == 0:
del window_state[arr[left]]
left += 1
# 3. Update result
result = max(result, right - left + 1)
return result
Two Pointers Template
Two pointers work on sorted arrays or when you need to compare elements from both ends:
def two_pointers_opposite(arr):
"""Two pointers moving toward each other.
Classic pattern for sorted array pair problems.
"""
left, right = 0, len(arr) - 1
result = 0
while left < right:
current = arr[left] + arr[right]
if current == target:
# Found a valid pair
result += 1
left += 1
right -= 1
elif current < target:
left += 1 # need larger sum
else:
right -= 1 # need smaller sum
return result
def two_pointers_same_direction(arr):
"""Two pointers moving in the same direction.
Classic pattern for in-place array modification.
"""
slow = 0 # write pointer
for fast in range(len(arr)): # read pointer
if arr[fast] != val_to_remove:
arr[slow] = arr[fast]
slow += 1
return slow # new length
ML & Streaming Data Applications
These patterns are not just interview tricks — they power real production systems:
Rolling Feature Extraction
Sliding windows compute rolling mean, variance, and percentiles over time series data for ML feature engineering. Pandas rolling() uses this internally.
Stream Processing
Apache Kafka Streams and Flink use tumbling and sliding windows to aggregate real-time events. Your window template maps directly to these APIs.
Anomaly Detection
Variable-size windows detect anomalous sequences in network traffic, sensor data, and financial transactions by tracking deviation from expected patterns.
Sequence Alignment
Two-pointer techniques align DNA/protein sequences in bioinformatics and match time-warped signals in audio/speech processing pipelines.
Complexity Comparison
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force (nested loops) | O(n²) to O(n³) | O(1) | Never in interviews |
| Sliding Window | O(n) | O(k) or O(1) | Contiguous subarray/substring |
| Two Pointers | O(n) | O(1) | Sorted arrays, in-place ops |
| Hash Map | O(n) | O(n) | Unsorted pair finding |
Lilly Tech Systems