Category: Sliding Window, Hashing
Trick: Use two pointers with a sliding window and hash set for O(n).
Given a string, find the length of the longest substring without repeating characters.
def length_of_longest_substring(s):
char_set = set()
l, res = 0, 0 for r in range(len(s)):
while s[r] in char_set:
char_set.remove(s[l])
l += 1 char_set.add(s[r])
res = max(res, r - l + 1)
return res
Use a sliding window approach with two pointers. Expand the window with the right pointer and shrink it when encountering a repeating character.
Category: Two Pointers
Trick: Maximize area by shrinking the pointer with a smaller height.
Given n non-negative integers representing heights, find two lines that together with the x-axis form a container that holds the most water.
def max_area(height):
l, r = 0, len(height) - 1 max_area = 0 while l < r:
max_area = max(max_area, (r - l) * min(height[l], height[r]))
if height[l] < height[r]:
l += 1 else:
r -= 1 return max_area