Double Pointers
5. Longest Palindromic Substring
Approach: There are two cases for the center of a palindrome:
- The palindrome has odd length, i.e., the center is a single character.
- The palindrome has even length, i.e., the center is two identical characters.
For each character in the string, we treat it as the center and expand outwards on both sides to find the longest palindrome centered at it and update the answer.
Example:
Input: s = “babad”
Output: “bab”
Explanation: “aba” is also a valid answer.
Solution:
26. Remove Duplicates from Sorted Array
Example:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Approach: Use a fast pointer j
to iterate through the array, and a slow pointer i
to keep track of update progress.
If the current iterated element is equal to the previous one, skip it.
Otherwise, update the slow pointer with the current element and move to the next position.
Solution:
80. Remove Duplicates from Sorted Array II
Example:
Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Approach: Use a fast pointer j
to iterate through the array, and a slow pointer i
to keep track of the position to place the next unique element.
Similar approach to the previous problem but beware of the wrong solution below, which yields wrong answer [1,1,2,3,_,_]
for the example above.
That is because in this problem we need to keep at most two of the duplicates and nums[j-2]
is possible to have been updated already (when j-2<=i
).
Solution: