Authored by Tony Feng
Created on March 30th, 2022
Last Modified on March 30th, 2022
Understanding Two-pointer Algorithm
Intro
- The approach optimizes the runtime by utilizing some order (not necessarily sorting) of the data.
- It is generally applied on lists (arrays) and linked lists.
- Here, pointers represent either index or an iteration attribute like node’s Next.
Main Steps of the Algorithm
- Pointer Initialization
- Pointer Movement
- Stop Condition
Categories
- Old & New State Pointers
- Slow & Fast Pointers
- Left & Right Pointers
- Pointers from Two Sequences
- Sliding Window
Old & New State Pointers
Template
|
|
Examples
Leetcode 509 Fibonacci Number
|
|
Leetcode 198 House Robber
|
|
Slow & Fast Pointers
Template
|
|
Examples
Leetcode 141 Linked List Cycle
|
|
Leetcode 881 Boats to Save People
|
|
Leetcode 26 Remove Duplicates from Sorted Array
|
|
Left & Right Pointers
Template
|
|
Examples
Leetcode 167 Two Sum II - Input Array Is Sorted
|
|
Pointers from Two Sequences
Template
|
|
Examples
Leetcode 244 Shortest Word Distance II
|
|
Sliding Window
There are two types of window
The fixed size window can be used for problem where you want to determine whether given string contain a specific substring.
The dynamic one can be used to find the longest or shortest substring of the given string.
Template
|
|
Examples
Leetcode 209 Minimum Size Subarray Sum
|
|
Leetcode 1456 Maximum Number of Vowels in a Substring of Given Length
|
|
Reference
- 手把手带你刷Leetcode力扣 - 双指针 Two Pointers
- 手把手带你刷Leetcode力扣 - 力扣141
- 手把手带你刷Leetcode力扣 - 力扣881
- 手把手带你刷Leetcode力扣 - 滑动窗口 Sliding Window
- 手把手带你刷Leetcode力扣 - 力扣209
- 手把手带你刷Leetcode力扣 - 力扣1456
- Two Pointers Approach — Python Code
- Algorithm Templates: Two Pointers - Part 1
- Algorithm Templates: Two Pointers - Part 2
- Algorithm Templates: Two Pointers - Part 3
- Effective LeetCode: Understanding the Sliding Window Pattern