2/825
Two-Pointer & Expanding Windows · Page 1 of 1

Two-Pointer Technique

36 min Intermediate

Two-Pointer Sliding Window

The Concept

Use two pointers (left, right) to maintain window boundaries:

Array: [1, 3, 2, 2, 3, 1]
Goal: Longest substring with max k distinct chars

k = 2

[1, 3] ✓ (2 distinct)
[1, 3, 2] ✗ (3 distinct) → shrink left
[3, 2] ✓
[3, 2, 2] ✓
[3, 2, 2, 3] ✗ → shrink
[2, 2, 3] ✓

Expanding vs Shrinking

Expand (right pointer):
- When window is valid
- Add new element

Shrink (left pointer):
- When window violates condition
- Remove old elements

Repeat until entire array processed

Use Cases

Two-pointer works when:
- Need flexible window size
- Condition evaluated incrementally
- Can add/remove from both ends

Examples:
- Longest substring without repeating
- Minimum window substring
- Fruits into baskets
- Max consecutive elements

Pattern

left = 0
for right in range(len(arr)):
    # Expand: add arr[right]
    
    # Shrink if needed
    while condition_violated:
        # remove arr[left]
        left += 1
    
    # Process window [left, right]
main.py
Loading...
OUTPUT
Click "Run Code" to execute…