π Day 4: Array Patterns β Two Pointers and Sliding Window
π§ Concept Deep Dive
Many array problems involve finding subarrays, pairs, or patterns that follow a rule. Instead of using brute-force nested loops (which are slow), we use optimized pointer techniques.
βοΈ Two Pointers
Two variables (pointers) scan the array from different directions or at different speeds. Ideal for sorted arrays or problems with conditions between pairs.
πͺ Sliding Window
A window (subarray) moves through the array, adjusting its size dynamically to meet certain criteria. Best for tracking sums, averages, or unique elements.
π§ When to Use
| Pattern | Best For |
|---|---|
| Two Pointers | Sorted arrays, finding pairs, removing duplicates |
| Sliding Window | Subarray problems, dynamic constraints, strings |
βοΈ Two Pointers Example: Pair Sum
π§© Problem:
Given a sorted array and a target, find if any two numbers sum to the target.
π TypeScript Code
function hasPairWithSum(arr: number[], target: number): boolean {
let left = 0;
let right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) return true;
if (sum < target) left++;
else right--;
}
return false;
}
// Test
console.log(hasPairWithSum([1, 2, 4, 7, 11, 15], 15)); // Output: trueπ§ Why It Works
- The array is sorted.
- Increasing
leftincreases the sum, decreasingrightdecreases the sum.
πͺ Sliding Window Example: Max Sum of Subarray of Size K
π§© Problem:
Given an array of numbers and a number k, find the maximum sum of any contiguous subarray of size k.
π TypeScript Code
function maxSubarraySum(arr: number[], k: number): number {
let maxSum = 0;
let windowSum = 0;
for (let i = 0; i < k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
for (let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
// Test
console.log(maxSubarraySum([2, 1, 5, 1, 3, 2], 3)); // Output: 9π§ Why It Works
- First calculate the sum of the first window of size
k. - Then, slide the window one index at a time by adding the next element and removing the first element of the previous window.
π§ Visual Representation
Array: [1, 2, 3, 4, 5, 6]
Window (k=3): β [1,2,3] β [2,3,4] β [3,4,5] β [4,5,6]
Two Pointers: β β
left rightπ Real-world Application
π§ Sliding Window:
- Streaming temperature sensors: track rolling averages over 10 seconds.
- Data packets: max throughput over fixed-size timeframes.
π§ Two Pointers:
- Detecting fraud: find if any two transactions sum to a suspicious amount.
- Video processing: comparing frames forward/backward.
π§ͺ Example Practice: Longest Substring with K Unique Characters
Problem
Find the length of the longest substring with at most k distinct characters.
Code
function longestKSubstr(s: string, k: number): number {
let start = 0;
let maxLength = 0;
const charMap = new Map<string, number>();
for (let end = 0; end < s.length; end++) {
const endChar = s[end];
charMap.set(endChar, (charMap.get(endChar) || 0) + 1);
while (charMap.size > k) {
const startChar = s[start];
charMap.set(startChar, charMap.get(startChar)! - 1);
if (charMap.get(startChar) === 0) charMap.delete(startChar);
start++;
}
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
// Test
console.log(longestKSubstr("eceba", 2)); // Output: 3 ("ece")π§ Big O Recap
| Pattern | Time Complexity | Space Complexity |
|---|---|---|
| Two Pointers | O(n) | O(1) or O(n) |
| Sliding Window | O(n) | O(k) |
π Homework (LeetCode-style)
Problem: Minimum Size Subarray Sum
Given an array of positive integers
numsand a positive integertarget, return the minimal length of a subarray of which the sum is greater than or equal totarget. If there is no such subarray, return 0.
Function Signature:
function minSubArrayLen(target: number, nums: number[]): number;Example 1
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2 // [4,3]Example 2
Input: target = 15, nums = [1,2,3,4,5]
Output: 5 // entire arrayπ Hint: Use sliding window and adjust window size until sum β₯ target
π§Ύ Summary
- Two Pointers = simple but powerful way to reduce nested loops.
- Sliding Window = excellent for contiguous subarray/string problems.
- Know the difference: Two Pointers often compares ends, while Sliding Window grows/shrinks a range.
π Coming Up
π Day 4: Strings β Manipulation and Common Techniques
We'll explore string traversal, building, comparing, and efficient pattern checks like palindromes, anagrams, and reversals.