π‘ Summary: Avoiding Re-Counting the Same Numbers Again and Again
Suppose you track daily sales or sensor readings and keep answering questions like "What is the total from Day 3 to Day 8?" or "What is the highest sum across any 7-day stretch?" Re-adding every range from scratch wastes work.
Prefix sums store running totals ahead of time so any range sum is a quick subtraction. A sliding window moves a fixed or flexible span across an array by adding one incoming item and dropping one outgoing item. Two pointers scan from opposite ends or at different speeds to solve pair, partitioning, or reversal tasks cleanly.
1. Prefix Sums & Sliding Window Mechanics
Both patterns eliminate redundant inner loops over contiguous subarrays:
- Prefix Sum Array: Build
pref[i+1] = pref[i] + arr[i]in $O(n)$ time; then sum of range $[L, R]$ (inclusive, 0-based) ispref[R + 1] - pref[L]in $O(1)$ time (using $O(n)$ extra space). - Fixed-Size Sliding Window (size $k$): Compute the first window of $k$ elements, then shift right by adding
arr[i]and subtractingarr[i - k]in $O(n)$ total time and $O(1)$ space. - Variable-Size Sliding Window: Expand the right pointer to include elements and advance the left pointer when a constraint (such as a sum budget or uniqueness rule) is violated.
| Technique | Best Fit | Typical Time / Extra Space |
|---|---|---|
| Prefix Sum | Many static range-sum / cumulative queries | $O(n)$ build, $O(1)$ query / $O(n)$ space |
| Sliding Window | Contiguous subarrays/substrings of size $k$ or max/min valid span | $O(n)$ time / $O(1)$ to $O(k)$ space |
Python (prefix_and_sliding_window.py)
def build_prefix(arr):
pref = [0] * (len(arr) + 1)
for i, val in enumerate(arr):
pref[i + 1] = pref[i] + val
return pref
def range_sum(pref, left, right):
return pref[right + 1] - pref[left]
def max_window_sum(arr, k):
if k <= 0 or k > len(arr):
return None
window_sum = sum(arr[:k])
best = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i - k]
if window_sum > best:
best = window_sum
return best
daily_sales = [120, 200, 150, 300, 250, 180]
pref = build_prefix(daily_sales)
print("Range sum [1..3]:", range_sum(pref, 1, 3))
print("Max 3-day sales sum:", max_window_sum(daily_sales, 3))
Output:
Range sum [1..3]: 650
Max 3-day sales sum: 700
2. Two-Pointer Technique
Two pointers use index variables (often
left and right, or slow and fast) to inspect elements in a single pass:
- Opposite-Ends Pointers: Start at
0andn - 1, moving inward based on comparison or swap rulesβuseful for pair sums on sorted arrays, palindrome checks, and in-place reversals. - Read/Write (Slow/Fast) Pointers: One pointer scans ahead while the other marks where to place kept or filtered elements in-place without extra arrays.
C++ (two_pointers_sorted_pair.cpp)
#include
#include
using namespace std;
// Finds indices of two elements in a sorted vector summing to target
pair twoSumSorted(const vector& nums, int target) {
int left = 0;
int right = static_cast(nums.size()) - 1;
while (left < right) {
long long sum = static_cast(nums[left]) + nums[right];
if (sum == target) {
return {left, right};
} else if (sum < target) {
++left;
} else {
--right;
}
}
return {-1, -1};
}
int main() {
vector prices = {100, 250, 400, 650, 900};
auto ans = twoSumSorted(prices, 1050);
cout << "Pair indices: " << ans.first << ", " << ans.second << "\n";
return 0;
}
Output:
Pair indices: 1, 4
3. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Five real-world scenarios show prefix sums, sliding windows, and two pointers in action:
- 1. Dashboard Revenue / Traffic Totals Between Two Dates (Prefix Sum): Quickly computes total orders or page views across any start-to-end date range.
- 2. Rolling 7-Day Average Sales or Temperature (Sliding Window): Updates a moving average smoothly as each new day arrives and the oldest day exits.
- 3. Network Rate-Limiter / Request Burst Check (Sliding Window): Counts events inside a rolling time or request window to detect traffic spikes.
- 4. Pairing Two Items Within a Budget on a Sorted Price List (Two Pointers): Moves left/right pointers inward in $O(n)$ time instead of checking all pairs in $O(n^2)$.
- 5. Palindrome / Coupon / ID Symmetry Verification (Two Pointers): Compares characters from both ends moving toward the center.
Python (realtime_array_tech_1_to_5.py)
# 2. Rolling 3-hour latency average
latencies = [120, 140, 135, 210, 150, 130]
k = 3
win_sum = sum(latencies[:k])
avgs = [round(win_sum / k, 1)]
for i in range(k, len(latencies)):
win_sum += latencies[i] - latencies[i - k]
avgs.append(round(win_sum / k, 1))
print("2. 3-hr rolling averages:", avgs)
# 5. Two-pointer palindrome check
def is_palindrome(s):
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
print("5. Is 'level' palindrome?:", is_palindrome("level"))
Output:
2. 3-hr rolling averages: [131.7, 161.7, 165.0, 163.3]
5. Is 'level' palindrome?: True
4. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-time examples highlight data cleanup, longest valid spans, and cumulative metrics:
- 6. Removing Duplicate Entries In-Place from a Sorted Log/List (Two Pointers): Overwrites duplicate slots using a write index while scanning with a read index.
- 7. Longest Consecutive Session Within a Time Budget (Variable Sliding Window): Expands right while total duration stays within limit, shrinking left when exceeded.
- 8. Longest Substring Without Repeated Characters (Sliding Window): Maintains a window of unique characters for autocomplete, text search, or stream parsing.
- 9. Cumulative Marks / Energy Usage Milestones (Prefix Sum): Tracks running totals across checkpoints or billing intervals.
- 10. Reversing an Array or Packet Buffer In-Place (Two Pointers): Swaps elements from outer ends inward using $O(1)$ extra memory.
Python (realtime_array_tech_6_to_10.py)
# 6. Deduplicate sorted IDs in-place (returns unique count)
def dedup_sorted(arr):
if not arr:
return 0
write = 1
for read in range(1, len(arr)):
if arr[read] != arr[write - 1]:
arr[write] = arr[read]
write += 1
return write
sorted_ids = [10, 10, 20, 30, 30, 30, 40]
uniq_len = dedup_sorted(sorted_ids)
print("6. Unique items:", sorted_ids[:uniq_len])
# 10. Reverse list in-place with two pointers
buf = [1, 2, 3, 4, 5]
l, r = 0, len(buf) - 1
while l < r:
buf[l], buf[r] = buf[r], buf[l]
l += 1
r -= 1
print("10. Reversed buffer:", buf)
Output:
6. Unique items: [10, 20, 30, 40]
10. Reversed buffer: [5, 4, 3, 2, 1]
5. Exam & Interview Summary
Follow these selection cues when tackling array problems in labs, exams, and interviews:
- Use Prefix Sums when answering many range-sum/query questions on a mostly static array (note: prefix-sum difference works cleanly for sum queries, whereas min/max range queries often need other structures).
- Use Sliding Window for contiguous subarrays or substrings where you track a window sum, count, or uniqueness condition.
- Use Two Pointers when comparing/swapping from both ends (especially on sorted sequences) or compacting elements in-place.
Python (technique_picker.py)
guides = [
"Prefix sum: fast range sums via pref[r+1] - pref[l].",
"Sliding window: maintain a moving subarray/substring state in O(n).",
"Two pointers: move two indices cleanly without nested loops."
]
for line in guides:
print("*", line)
Output:
* Prefix sum: fast range sums via pref[r+1] - pref[l].
* Sliding window: maintain a moving subarray/substring state in O(n).
* Two pointers: move two indices cleanly without nested loops.