Arrays Mastery Guide
Welcome to the complete hub for Array. Here youโll find guides, templates, and curated problems for interviews and mastery.
Sliding Window Technique
Two Pointer Technique
๐ Practice Problems
โก View All Arrays Problems โโญ 1. Array Concepts You Must Master
๐น Basic Operations
-
Traversal
-
Searching
-
Prefix sums
-
Suffix sums
-
Sorting techniques
-
Using hash maps to optimize
๐น Core Patterns
Arrays revolve around 10 major patterns:
1. Sliding Window
2. Two Pointers
3. Prefix Sum
4. Binary Search on Sorted Array
5. Binary Search on Answer
6. Kadaneโs Algorithm
7. Sorting + Greedy
8. Intervals
9. Matrix as Array of Arrays
10. Hashmap + Array Combo
We will cover each with template + example.
โญ Pattern โ Template โ Example
๐ถ Pattern 1: Sliding Window
Sliding Window is used when we deal with contiguous subarrays or substrings.
๐ Template (Variable-size window)
int left = 0;
for (int right = 0; right < n; right++) {
// expand window using arr[right]
while (window_invalid) {
// shrink window
left++;
}
// track best window
}
๐ Example
๐ถ Pattern 2: Two Pointers
Used when array is sorted, or when youโre searching for pairs.
๐ Template
int left = 0, right = n - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) { ... }
else if (sum < target) left++;
else right--;
}
๐ Example
Two Sum (sorted)
3-sum
Container With Most Water
๐ถ Pattern 3: Prefix Sum
Instant sum queries from index l to r.
๐ Template
vector<int> pref(n+1, 0);
for (int i = 0; i < n; i++) pref[i+1] = pref[i] + arr[i];
// sum of l..r
int sum = pref[r+1] - pref[l];
๐ Example
Subarray sum equals K
Range sum queries
๐ถ Pattern 4: Kadaneโs Algorithm
Max subarray sum in O(n).
๐ Template
int max_ending_here = 0, best = INT_MIN;
for (int x : arr) {
max_ending_here = max(x, max_ending_here + x);
best = max(best, max_ending_here);
}
๐ถ Pattern 5: Sorting + Greedy
Used in:
Meeting rooms
Task scheduling
Minimum arrows to burst balloons
๐ถ Pattern 6: Binary Search
Used on sorted arrays.
๐ Standard Template
int l = 0, r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) l = mid + 1;
else r = mid - 1;
}
๐ถ Pattern 7: Binary Search on Answer
Used when the array is not sorted but the answer lies in a monotonic search space.
Examples:
Koko eating bananas
Minimum pages allocation
Aggressive cows
๐ถ Pattern 8: Intervals (Important!)
Many array problems are actually interval problems.
Steps:
-
Sort by start
-
Merge or process based on end
๐ถ Pattern 9: Matrix as Array of Arrays
2D array concepts:
-
Row-wise traversal
-
Column-wise traversal
-
Diagonal traversal
-
Simulation problems
๐ถ Pattern 10: Hashmap + Array Combo
Most-used pattern in arrays.
Examples:
-
Two sum
-
Group anagrams
-
Top K frequent
-
Subarray sum K