Two Pointers & Sliding Window
Learn how inward-moving pointers eliminate O(N²) quadratic loops in sorted sequences and how expanding/contracting windows process contiguous subarrays in linear O(N) time.
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.
Examples
- 1 <= s.length <= 2 * 10^5
- s consists only of printable ASCII characters.
class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return TrueTwo Sum II (Sorted Input)
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Return the indices of the two numbers, index1 and index2, as an integer array [index1, index2] of length 2.
Examples
- 2 <= numbers.length <= 3 * 10^4
- -1000 <= numbers[i] <= 1000
- numbers is sorted in non-decreasing order.
- Exactly one solution exists.
class Solution:
def twoSum(self, numbers: list[int], target: int) -> list[int]:
left, right = 0, len(numbers) - 1
while left < right:
curr = numbers[left] + numbers[right]
if curr == target:
return [left + 1, right + 1]
elif curr < target:
left += 1
else:
right -= 1
return []Container With Most Water
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store.
Examples
- n == height.length
- 2 <= n <= 10^5
- 0 <= height[i] <= 10^4
class Solution:
def maxArea(self, height: list[int]) -> int:
left, right = 0, len(height) - 1
max_water = 0
while left < right:
width = right - left
max_water = max(max_water, width * min(height[left], height[right]))
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_water