Library.

1def is_palindrome(s: str) -> bool:
2 i, j = 0, len(s) - 1
3 while i < j:
4 if not s[i].isalpha():
5 i += 1
6 continue
7 if not s[j].isalpha():
8 j -= 1
py
Valid PalindromeOptimal

Two pointer approach

1let lo = 0, hi = arr.length - 1;
2​
3while (lo <= hi) {
4 const mid = (lo + hi) >> 1;
5 if (arr[mid] === target) return mid;
6 arr[mid] < target ? (lo = mid + 1) : (hi = mid - 1);
7}
8return -1;
js
Binary Search

Binary search and the off-by-one that always gets you

1const pairs = { ")": "(", "]": "[", "}": "{" };
2const stack = [];
3​
4for (const ch of s) {
5 if (ch in pairs) {
6 if (stack.pop() !== pairs[ch]) return false;
7 } else stack.push(ch);
8}
js
Valid Parentheses

Balanced brackets, and the stack nobody mentions

1function twoSum(nums, target) {
2 const s = nums.map((v, i) => [v, i])
3 .sort((a, b) => a[0] - b[0]);
4 let lo = 0, hi = s.length - 1;
5 while (lo < hi) {
6 const sum = s[lo][0] + s[hi][0];
7 if (sum === target)
8 return [s[lo][1], s[hi][1]];
js
Two SumBetter

Two Sum with sorting and two pointers

1function twoSum(nums, target) {
2 const seen = new Map();
3 for (let i = 0; i < nums.length; i++) {
4 const need = target - nums[i];
5 if (seen.has(need))
6 return [seen.get(need), i];
7 seen.set(nums[i], i);
8 }
js
Two SumOptimal

Two Sum, and why the hash map is obvious in hindsight

1function twoSum(nums, target) {
2 const n = nums.length;
3 for (let i = 0; i < n; i++)
4 for (let j = i + 1; j < n; j++)
5 if (nums[i] + nums[j] === target)
6 return [i, j];
7}
js
Two SumBrute force

Two Sum the honest way: start with brute force