Many array and string problems look like they need two nested loops, checking every pair or every slice. That is O(n²) and gets slow very quickly. Two simple patterns often bring the time down to O(n). With two pointers, two indexes move through the array, and each step rules out many answers at once. With a sliding window, you keep a running total for a slice and slide it along instead of adding everything up again. This lesson shows both in Java with six tested examples.
In this lesson you will learn
- Finding a pair with a given sum in a sorted array
- Removing duplicates and moving zeros in place
- A fixed-size sliding window for the best k-day total
- A variable window for the longest substring with no repeats
- The shortest run with a sum of at least a target
You should know Java arrays and HashMap. The same ideas in C are in the two pointer technique.
Two Pointers
import java.util.*;
public class Main {
// Pair in a SORTED array that adds up to target: O(n) with two pointers
static int[] pairWithSum(int[] a, int target) {
int left = 0, right = a.length - 1;
while (left < right) {
int sum = a[left] + a[right];
System.out.println(" check a[" + left + "]+a[" + right + "] = " + a[left] + "+" + a[right] + " = " + sum);
if (sum == target) return new int[]{a[left], a[right]};
if (sum < target) left++; // need a bigger sum
else right--; // need a smaller sum
}
return null;
}
// Remove duplicates from a sorted array in place; returns the new length
static int removeDuplicates(int[] a) {
if (a.length == 0) return 0;
int write = 1;
for (int read = 1; read < a.length; read++) {
if (a[read] != a[write - 1]) a[write++] = a[read];
}
return write;
}
// Move all zeros to the end, keeping the order of the other numbers
static void moveZeros(int[] a) {
int write = 0;
for (int x : a) if (x != 0) a[write++] = x;
while (write < a.length) a[write++] = 0;
}
public static void main(String[] args) {
int[] prices = {120, 150, 200, 250, 310, 400};
System.out.println("Find two items costing exactly 450 Tk:");
System.out.println(" found " + Arrays.toString(pairWithSum(prices, 450)));
int[] rolls = {1, 1, 2, 3, 3, 3, 5, 8, 8};
int n = removeDuplicates(rolls);
System.out.println("Unique: " + Arrays.toString(Arrays.copyOf(rolls, n)));
int[] data = {0, 4, 0, 7, 2, 0, 9};
moveZeros(data);
System.out.println("Zeros moved: " + Arrays.toString(data));
}
}
Output
Find two items costing exactly 450 Tk:
check a[0]+a[5] = 120+400 = 520
check a[0]+a[4] = 120+310 = 430
check a[1]+a[4] = 150+310 = 460
check a[1]+a[3] = 150+250 = 400
check a[2]+a[3] = 200+250 = 450
found [200, 250]
Unique: [1, 2, 3, 5, 8]
Zeros moved: [4, 7, 2, 9, 0, 0, 0]
- Pair with a sum. The array is sorted.
leftstarts at the cheapest item andrightat the dearest. If the sum is too big, the only way to make it smaller is to moverightdown. If it is too small, moveleftup. The printed checks show it took 5 steps to find 200 + 250 = 450, while checking all pairs could take 15. - Why is this safe? When 120 + 400 is too big, 400 is also too big with every other item, since they all cost at least 120. So dropping 400 loses nothing.
- Remove duplicates. Here the two pointers move in the same direction.
readvisits every number;writemarks where the next unique number should go. The array is changed in place, with no second array. - Move zeros. The same read and write idea copies every non-zero number forward, in order, then fills the rest with zeros.
Sliding Window
import java.util.*;
public class Main {
// Best total of k consecutive days: fixed-size sliding window, O(n)
static int bestWindow(int[] sales, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += sales[i];
int best = sum;
for (int i = k; i < sales.length; i++) {
sum += sales[i] - sales[i - k]; // add the new day, drop the oldest
best = Math.max(best, sum);
}
return best;
}
// Longest substring without repeating characters: variable-size window
static String longestUnique(String s) {
Map<Character, Integer> lastSeen = new HashMap<>();
int start = 0, bestStart = 0, bestLen = 0;
for (int end = 0; end < s.length(); end++) {
char c = s.charAt(end);
if (lastSeen.containsKey(c) && lastSeen.get(c) >= start) {
start = lastSeen.get(c) + 1; // shrink past the repeat
}
lastSeen.put(c, end);
if (end - start + 1 > bestLen) { bestLen = end - start + 1; bestStart = start; }
}
return s.substring(bestStart, bestStart + bestLen);
}
// Shortest run of positive numbers whose sum is at least target
static int shortestAtLeast(int[] a, int target) {
int left = 0, sum = 0, best = Integer.MAX_VALUE;
for (int right = 0; right < a.length; right++) {
sum += a[right];
while (sum >= target) {
best = Math.min(best, right - left + 1);
sum -= a[left++];
}
}
return best == Integer.MAX_VALUE ? 0 : best;
}
public static void main(String[] args) {
int[] sales = {5, 2, 8, 1, 9, 7, 3};
System.out.println("Best 3-day sales : " + bestWindow(sales, 3));
System.out.println("Longest unique part : " + longestUnique("abcabcbb"));
System.out.println("Longest unique part : " + longestUnique("pwwkew"));
System.out.println("Shortest run >= 15 : " + shortestAtLeast(new int[]{2, 3, 1, 2, 4, 3, 8, 5}, 15));
}
}
Output
Best 3-day sales : 19
Longest unique part : abc
Longest unique part : wke
Shortest run >= 15 : 3
- Fixed window. The first 3-day total is 5 + 2 + 8 = 15. To slide one day on, add the new day and subtract the oldest:
sum += sales[i] - sales[i - k]. Each step is one addition and one subtraction, not k additions. The best window is 9 + 7 + 3 = 19. - Longest unique substring. The window grows to the right with
end. When a character repeats inside the window,startjumps past its last position. The map remembers where each character was last seen. For “abcabcbb” the answer is “abc”; for “pwwkew” it is “wke”. - Shortest run of at least 15. Grow the window until the sum reaches the target, then shrink it from the left as long as it still does. Each number enters and leaves the window at most once, so the whole thing is O(n). The answer is 3, from 4 + 3 + 8.
| Pattern | Pointers move | Good for |
|---|---|---|
| Opposite ends | Towards each other | Sorted pair sums, palindromes, reversing |
| Read and write | Same way, different speeds | Removing items in place, partitioning |
| Fixed window | Both by one each step | Best total or average of k items |
| Variable window | Right grows, left shrinks | Longest or shortest slice with a rule |
Common Mistakes
- Using opposite-end pointers on an unsorted array. The pair-sum trick depends on sorting.
- Using
left <= rightfor pairs. That can pair an item with itself; useleft < right. - Recomputing the whole window sum each step. That brings back O(n·k) time.
- Moving
startbackwards in the unique-substring problem. The checklastSeen.get(c) >= startstops this. - Using a sum-based shrinking window with negative numbers. The “shrink while big enough” rule only works when all numbers are positive.
Practice Exercises
Exercise 1. Find the highest average temperature over any 4 days in {31, 33, 29, 35, 36, 34, 30}.
Show answer
Use bestWindow(temps, 4) and divide by 4.0. The four windows total 128, 133, 134 and 135. The best is the last one, 35 + 36 + 34 + 30 = 135, an average of 33.75.
Exercise 2. Check whether a sorted array has two numbers whose difference is exactly k.
Show answer
static boolean hasDiff(int[] a, int k) {
int i = 0, j = 1;
while (j < a.length) {
int d = a[j] - a[i];
if (i != j && d == k) return true;
if (d < k) j++; // difference too small: move the right pointer
else i++; // too big: move the left pointer
if (i == j) j++;
}
return false;
}
// hasDiff(new int[]{1, 4, 7, 12}, 5) is true (7 and 12)
Both pointers move in the same direction here, so it is still O(n).
Frequently Asked Questions
What is the difference between two pointers and sliding window?
A sliding window is a special kind of two pointers. Both use two indexes, but in a sliding window the two indexes mark the start and end of a slice, and you keep a running value such as a sum or a count for everything between them.
When should I use the sliding window technique?
Use it when a problem asks about a continuous slice of an array or string, such as the longest, shortest, or best-scoring slice that follows some rule. If the items do not have to be next to each other, a sliding window usually does not apply.
Summary
- Two pointers and sliding windows turn many O(n²) searches into O(n).
- Opposite-end pointers need a sorted array; move the side that fixes the sum.
- Read and write pointers change an array in place.
- A fixed window adds the new item and drops the oldest.
- A variable window grows on the right and shrinks on the left.
Next: SOLID Principles in Java.
