š„ Two Pointers
When to Use
- Sorted arrays Find pairs with target sum
- Palindromes Check from both ends
- Remove duplicates In-place operations
- Container problems Max water, areas
def two_sum(arr, target):
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return []
šŖ Sliding Window
When to Use
- Subarray/Substring Contiguous elements
- Fixed size window K elements
- Variable size Min/max conditions
- String patterns Anagrams, permutations
def max_sum_subarray(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum = window_sum - arr[i-k] + arr[i]
max_sum = max(max_sum, window_sum)
return max_sum
š¢š Fast & Slow Pointers
When to Use
- Cycle detection Linked list cycles
- Middle element Find middle of list
- Happy number Cycle problems
- Palindrome List palindrome
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
š² Tree Traversal Patterns
Types
- DFS Preorder Root ā Left ā Right
- DFS Inorder Left ā Root ā Right
- DFS Postorder Left ā Right ā Root
- BFS Level Order Level by level
def inorder(root):
result = []
def traverse(node):
if not node:
return
traverse(node.left)
result.append(node.val)
traverse(node.right)
traverse(root)
return result
āŖ Backtracking
When to Use
- Permutations All arrangements
- Combinations All selections
- Subsets Power set
- N-Queens Constraint problems
def subsets(nums):
result = []
def backtrack(start, path):
result.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1, path)
path.pop()
backtrack(0, [])
return result
šÆ Binary Search Variations
Common Variations
- First occurrence Leftmost position
- Last occurrence Rightmost position
- Search in rotated Modified binary search
- Search insert position Where to insert
def first_occurrence(arr, target):
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
result = mid
right = mid - 1
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result