Two Pointers
Two pointers is a technique where you use two pointers that either move towards each other or move in the same direction. The technique is often used to search for a pair of indices satisfying some constraint in linear time.
When:
- String or array questions
- Satisfy a constraint
- "Find a set of elements that satisfy some constraint"
- Substring/subarray questions
Cases:
- Two pointers one starting at the beginning and one at the end moving towards each other
- One pointer moving in the same direction, one slow and one fast.
Valid Palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105- s consists only of printable ASCII characters.
Solution
Try it yourselfconst isPalindrome = function(s) { // turn string to lowercase and use regex to remove non-alphanumeric s = s.replace(/[^p{L}p{N}]/giu, ''); s = s.toLowerCase() let a = 0, b = s.length - 1 while(a < b){ if(s[a] !== s[b]) return false a++ b-- } return true };
Explanation:
- Get rid of non alphanumeric values and turn string to lowercase
- Pointer 'a' points at the beginning of the string and pointer 'b' points at the end of the string
- While 'a' is less than 'b', if the values at 'a' and 'b' are not equal, return false
- If the values at 'a' and 'b' are equal, increment 'a' and decrement 'b'
- If the loop finishes, return true
Remove Duplicates from Sorted Array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
Consider the number of unique elements in nums to be k. After removing duplicates, return the number of unique elements k.
The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,,,,,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 104-100 <= nums[i] <= 100- nums is sorted in non-decreasing order.
Solution
Try it yourselffunction removeDuplicates(nums) { if (nums.length === 0) return 0; let k = 1; let lastUniquePointer = 0; for (let i = 1; i < nums.length; i++) { if (nums[i] !== nums[lastUniquePointer]) { lastUniquePointer += 1; nums[lastUniquePointer] = nums[i]; k++; } } return k; }
Explanation:
- Empty array edge case: return 0.
- Two pointers: lastUniquePointer tracks the last unique value's index; k counts unique elements (starts at 1 since first element is always unique).
- Loop from index 1: when nums[i] differs from nums[lastUniquePointer], advance lastUniquePointer, copy nums[i] there, and increment k.
- Return k (number of unique elements). The first k elements of nums hold the unique values in order.
Remove Duplicates from Sorted Array II
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,,]
Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 104-104 <= nums[i] <= 104- nums is sorted in non-decreasing order.
Solution
Try it yourselffunction removeDuplicates(nums) { let k = 2; for (let i = 2; i < nums.length; i++) { if (nums[i] !== nums[k - 2]) { nums[k] = nums[i]; k++; } } return k; }
Explanation:
- First two elements are always valid (at most 2 allowed per value), so k starts at 2.
- From index 2: compare nums[i] with nums[k - 2]. If different, we're not exceeding 2 of the same value in the result, so write nums[i] at k and increment k.
- If nums[i] === nums[k - 2], we would have 3 of that value; skip (do not write, do not increment k).
- Return k. First k elements hold the result with each value appearing at most twice.