Skip to content

Double Pointers

5. Longest Palindromic Substring

Leetcode

Approach: There are two cases for the center of a palindrome:

  1. The palindrome has odd length, i.e., the center is a single character.
  2. 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:

1
class Solution:
2
def longestPalindrome(self, s: str) -> str:
3
ans = ""
4
for i in range(len(s)):
5
# odd length case
6
cur = self.findPalindrome(s, i, i)
7
if len(cur) > len(ans):
8
ans = cur
9
# even length case
10
# if s[i] and s[i+1] are not identical, it will return ""
11
cur = self.findPalindrome(s, i, i+1)
12
if len(cur) > len(ans):
13
ans = cur
14
return ans
15
16
def findPalindrome(self, s: str, left: int, right: int):
17
"""
18
Find the longest palindrome by starting from `left` and `right`
19
and going outwards.
20
"""
21
while left >= 0 and right < len(s) and s[left] == s[right]:
22
left -= 1
23
right += 1
24
return s[left+1: right]

26. Remove Duplicates from Sorted Array

Leetcode

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:

1
class Solution:
2
def removeDuplicates(self, nums: List[int]) -> int:
3
i = 0
4
for j in range(len(nums)):
5
if j > 0 and nums[j] == nums[j-1]:
6
continue
7
nums[i] = nums[j]
8
i += 1
9
return i

80. Remove Duplicates from Sorted Array II

Leetcode

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:

1
class Solution:
2
def removeDuplicates(self, nums: List[int]) -> int:
3
i = 0
4
for j in range(len(nums)):
5
if j > 1 and nums[j] == nums[j-2]:
6
if j > 1 and nums[j] == nums[i-2]:
7
continue
8
nums[i] = nums[j]
9
i += 1
10
return i