Week 1 · Day 4 of 42
Two Pointer: In-place Array Modification and Fixed Separation
"Remove/modify in-place with O(1) space" → use a slow (write) pointer and a fast (read) pointer. Fast scans everything; slow only advances when we keep an element. "Nth from the end" → advance one pointer N steps ahead first, then walk both together. When the leader hits null, the follower is at the target.
Sign in to tick off tasks and keep your progress on every device
Two Pointers - In-place Array Modification
Tick the box when you have studied this pattern
How to recall this pattern
"Remove/modify in-place with O(1) space" → use a slow (write) pointer and a fast (read) pointer. Fast scans everything; slow only advances when we keep an element.
- Use a slow pointer (write position) and a fast pointer (read position).
- Fast pointer scans every element; slow pointer only advances when we keep an element.
- Overwrites in-place without extra space. Common for removing duplicates or specific values.
- Time: O(n), Space: O(1). Order of remaining elements is preserved.
Two Pointers - Fixed Separation (Nth Node from End)
Tick the box when you have studied this pattern
How to recall this pattern
"Nth from the end" → advance one pointer N steps ahead first, then walk both together. When the leader hits null, the follower is at the target.
- Advance the first pointer by N steps, then move both pointers together.
- When the first pointer hits the end, the second pointer is N nodes from the end.
- Use a dummy node before head to handle edge cases (e.g., removing the head node).
- Time: O(n) single pass, Space: O(1).
Solve these
Try each one before reading a solution. Name the pattern out loud first.
Extra practice · 2 more problems
Spotted a mistake on this page?
Wrong formula, broken animation or confusing wording. Tell us and we will fix it.