It works on unsorted arrays just as effectively as sorted ones.
It reduces the time complexity, often from O(n^2) to O(n).
It simplifies the code by reducing the number of loops.
It reduces the space complexity by eliminating the need for auxiliary data structures.
T
left
right
Decrement the right pointer.
Increment both pointers.
Increment the left pointer.
Decrement both pointers.
Finding the longest substring without repeating characters.
Checking if a string is a palindrome.
Removing duplicates from a sorted array.
nums
Both pointers start at the beginning and advance together, swapping elements when a duplicate is found.
A left pointer starts at the beginning and a right pointer at the end, and they swap duplicates to the end of the array.
One pointer finds the start of a duplicate sequence, and the other finds the end.
A 'slow' pointer marks the end of the unique elements, and a 'fast' pointer iterates through the array to find the next unique element.
m
n
O(max(m,n))O(max(m, n))O(max(m,n))
O(log(m+n))O(log(m+n))O(log(m+n))
O(m⋅n)O(m \cdot n)O(m⋅n)
O(m+n)O(m + n)O(m+n)
To increase the width of the container.
The area is limited by the shorter height. Moving this pointer is the only way to potentially find a taller line that could increase the area.
It is an arbitrary choice that simplifies the algorithm.
Moving the taller height's pointer can never result in a larger area.
Sort the array, then iterate through it with one index i, and for each element, use a two-pointer (left/right) approach on the rest of the array to find two numbers that sum to -nums[i].
i
-nums[i]
Use two pointers to find all pairs, and then do a linear scan to find a third element for each pair.
Use three pointers that all start at the beginning of the array.
Finding the middle element of a linked list.
Partitioning an array around a pivot element.
Finding if a sorted array contains a pair that sums to a target value.
Reversing a string.
False
True
left_max
right_max
height[left] < height[right]
Because the right_max is guaranteed to be taller, so the water trapped at left is determined by left_max.
This is an arbitrary rule to ensure the pointers eventually meet.
Because you must always move the pointer with the smaller height value.
Because processing from the smaller side is always faster.
Use left and right pointers. Advance left until it points to a letter, and advance right until it points to a letter. Then swap them and move both pointers inward.
This problem cannot be solved with two pointers.
Iterate with one pointer and use the second pointer to find the last letter in the string to swap with.
Swap characters at left and right pointers, then increment left and decrement right unconditionally.
All done? Get your grade