Topic: Two Pointers with Sliding Window
Q977 Squares of a Sorted Array
Q189 Rotate Array
Q283 Move Zeroes
Q167 Two Sum
Q344 Reverse String
Q557 Reverse Words in a String III
Q876 Middle of the Linked List
Q19 Remove Nth Node From End of List
Q3 Longest Substring Without Repeating Characters
Q567 Permutation in String
A searching algorithm which finds a pair of element's position in a sequential(sorted) array.
e.g. Given a enumerable array Grid
(maybe sorted in some
order), having finite integers, Two-Pointers method can find if there
exists any pair of elements (Grid[i]
,
Grid[j]
) such that suits some given target.
Note: This pair of elements can also represents a sequence of items of an array, which starts at item No. i and stops at item No. j.
Pre&Post / Sliding Window Method
1 | ## Ensure that pointer H(High) is kinda ahead of the pointer L(Low). |
Left&Right Method
1 | ## Do until the pointers L(Left) and R(Right) meet each other, |
Time Complexities
- Best Case Complexity: O(1)
- Worst Case Complexity: O(n)
- Average Case Complexity: O(n)
Space Complexities
- O(1)
Footnote
In Q977 Squares of a Sorted Array:
Left&Right Method is applied. Take The absolute value for comparison.
In Q189 Rotate Array:
See also in: < Article Not Published Yet >
In Q283 Move Zeroes:
Left&Right Method is applied. One Pointer stands for the current working position, and another stands for the staing point of pushing in / filling with zeros.
In Q167 Two Sum:
Left&Right Method is applied.
Note: The given input array is sorted.
In Q344 Reverse String:
Left&Right Method is applied.
In Q557 Reverse Words in a String III:
Left&Right Method is applied. Just make wise usage of slicers.
In Q876 Middle of the Linked List:
Pre&Post / Sliding Window Method is recommended.
1 | Pre += 1 |
In Q19 Remove Nth Node From End of List:
Left&Right Method is applied.
Repeat the "process" for N times, then remove the node.
In Q3 Longest Substring Without Repeating Characters:
Pre&Post / Sliding Window Method is applied.
In Q567 Permutation in String:
Note: It's much faster to create 2 dictionarys and compare them instead.