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

Two-Pointer Technique

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…