Coding Pattern:
Two Pointers
This pattern has an earnable cheat sheet.
Pattern concept
Step 1 of 11
Use ← → arrow keys
Code snippets
How to identify
Does the problem involve any of these?
- Searching for pairs or triplets of elements that satisfy certain conditions
- Sum of Three: Find triplets that sum up to a target.
- Best Time to Buy and Sell Stock: Find a pair of elements with max profit.
- Maintaining two pointers to scan a list simultaneously from both ends
- Valid Palindrome: Check whether a string is a valid palindrome.
- Valid Palindrome II: Check whether a string is almost a valid palindrome.
- Trapping Rain Water: Scan the list to calculate the amount of rainwater that can be trapped.
- Maintaining a sliding window or range within the array or list (covered later)
- Manipulating pointers to nodes in a linked list or tree (covered later)
- merging or comparing two sorted lists (covered later)
Note
Most two pointer problems can be solved in O(n) time and O(1) space complexity.