Loading
Loading
Two indices moving under a rule that never lets them backtrack.
Keep two positions in a sequence and advance them according to what you observe, so that each element is visited a bounded number of times. The pointers may start at opposite ends and close in, or start together and move in the same direction. Either way the win is the same: a decision that would need a nested scan becomes a single pass, because every move permanently rules out a region you will never need to revisit.
Each step must eliminate at least one candidate permanently. When the pointers close in, ask: given what I just observed, which side can I rule out entirely? If you cannot answer that, two pointers is the wrong tool.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
def opposite_ends(nums, target): """Pointers start apart and close in. Requires sorted input.""" left, right = 0, len(nums) - 1 while left < right: total = nums[left] + nums[right] if total == target: return [left, right] if total < target: # Everything left of 'left' is even smaller, so it can never # reach the target with any partner. Discard it. left += 1 else: right -= 1 return [] def same_direction(nums): """Slow marks where the next kept item goes; fast scans ahead.""" slow = 0 for fast in range(len(nums)): if keep(nums[fast]): nums[slow] = nums[fast] slow += 1 return slow # length of the compacted prefix| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Compact the Queue#3 | Easy | Primary | |
| Rotate the Roster#4 | Medium | Primary | |
| Normalise and Compare#9 | Easy | Primary | |
| Longest Mirrored Core#10 | Medium | Primary | |
| Compress Run Lengths#11 | Easy | Primary | |
| Reverse Words in a Log Line#12 | Easy | Primary | |
| Sorted Pair Target#22 | Easy | Primary | |
| Dedupe a Sorted Log#23 | Easy | Primary | |
| Widest Water Span#24 | Medium | Primary | |
| Sorted Squares of a Signed Series#25 | Easy | Primary | |
| Balanced Triples#26 | Hard | Primary | |
| Reverse the Chain#37 | Easy | Primary | |
| Merge Two Sorted Chains#39 | Easy | Primary | |
| Portions for Appetites#72 | Easy | Related | |
| Shared Free Windows#80 | Medium | Primary | |
| Ferrying Hikers Across the Lake#86 | Medium | Related | |
| Spiral Readout#92 | Easy | Primary | |
| Sorted Ledger Lookup#96 | Easy | Primary |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in