Back to Roadmap
Track 03 of 10
AlgorithmsIntermediate Level~25 Mins
3. Array Patterns: Two Pointers & Sliding Window
Reduce O(N²) brute-force nested loops into clean O(N) single-pass algorithm patterns.
The "WHY" Core Principle
Two Pointers and Sliding Window leverage array structure (like sorted order or window sum maintenance) to skip millions of invalid combinations in a single pass.
Interactive Visualizer
Code-Aware Array Algorithm Master Engine
In-Place Deduplication clean(names) O(N) Same-Direction Pointers
CORE PRINCIPLE: In-Place Deduplication: 'left' tracks unique write boundary while 'right' scans forward. If names[right] == names[left], skip duplicate; otherwise increment left and write.
Python Source CodeActive Execution Line
1
def clean(names):
2
left = 0
3
for right in range(1, len(names)):
4
if names[right] != names[left]:
5
left += 1
6
names[left] = names[right]
7
return left + 1 # Return new length
8
9
names = ['Alice', 'Bob', 'Bob', 'Charlie', 'Charlie', 'David']
10
new_length = clean(names)
11
print(names[:new_length]) # ['Alice', 'Bob', 'Charlie', 'David']
Step 1/7: Initialize write pointer 'left' at index 0 ('Alice')
UNIQUE WRITE ACTION: Writing unique item 'Alice' at index names[0].
RAM Memory Array: namesUnique Length = 1
WRITE (left)
Alicei=0
Bobi=1
Bobi=2
Charliei=3
Charliei=4
Davidi=5
Cleaned Result Sub-Array: names[:new_length]O(N) In-Place Memory
'Alice'
Interactive Code Snippets (1 Lessons)
Lesson 01
Two Pointers — Pair Sum in Sorted Array
O(N)O(1)
Find two numbers in a sorted array that add up to a target in O(N) time and O(1) space.
WHY Under The Hood:
If `arr[left] + arr[right] < target`, the sum is too small. Increasing `left` increases the sum. If too large, decreasing `right` decreases the sum.
CPython C Struct Detail: Uses pure index variables `left` and `right` without allocating extra data structures.
Two Pointers — Pair Sum in Sorted Array
Pyodide WASM EngineType, edit code, and click 'Run & Profile' to see live runtime ms and operation count!
Python 3.12 Code (Editable)
Expected:Time: O(N)Space: O(1)