Algorithm Patterns & Data Structures Reference
A practical guide for problem solving and coding interviews.
1. Array Patterns
Sliding Window
• Maintain a window of elements over an array or string to reduce O(n²) to O(n).
• Use when asked for: subarrays, substrings, max/min of contiguous range.
• Fixed window: move both pointers together. Variable window: expand right,
shrink left when invalid.
• Examples: Longest substring without repeating characters, max sum subarray of
size k.
Two Pointers
• Use two indices moving toward each other or in the same direction.
• Classic use: sorted array pair sum, removing duplicates, merging sorted arrays.
• Often combined with sorting as a preprocessing step.
Prefix Sums & Difference Arrays
• Prefix sum: precompute cumulative sums to answer range sum queries in O(1).
• Difference array: apply range updates in O(1), reconstruct in O(n).
• 2D prefix sums extend this to matrices for submatrix sum queries.
2. Searching Patterns
Binary Search
• Classic: search a sorted array in O(log n).
• Binary search on the answer: when asked for min/max satisfying a condition,
binary search the answer space.
• Template trigger: 'find the minimum X such that...' or 'what is the smallest/largest
valid value'.
• Examples: Koko eating bananas, minimum days to ship packages, peak element.
Modified Binary Search
• Rotated sorted arrays: determine which half is sorted, search accordingly.
• Search in 2D matrix: treat as flattened 1D array.
• Finding first/last occurrence: adjust boundaries instead of returning immediately.