Skip to content

Two Pointers & Sliding Window

Two pointers (opposite ends): start l = 0 and r = n - 1. Based on a comparison, move one of them inward. Each step rules out a whole set of candidates, which is why it works on sorted data.

Sliding window (same direction): r expands the window, and l shrinks it when the window becomes invalid. Both only move forward, so it’s O(n) total.

// Opposite-ends two pointers (sorted input)
int l = 0, r = nums.length - 1;
while (l < r) {
int sum = nums[l] + nums[r];
if (sum == target) { /* record */ l++; r--; }
else if (sum < target) l++;
else r--;
}
// Variable sliding window: longest valid window
int l = 0, best = 0;
for (int r = 0; r < n; r++) {
// 1. add s[r] to the window state
while (/* window is invalid */ false) {
// 2. remove s[l] from the window state
l++;
}
best = Math.max(best, r - l + 1); // 3. window [l..r] is valid
}
// Fixed-size window of k
int windowSum = 0;
for (int i = 0; i < n; i++) {
windowSum += nums[i];
if (i >= k) windowSum -= nums[i - k];
if (i >= k - 1) { /* window [i-k+1 .. i] is ready */ }
}
Problem: Valid Palindrome (Easy) — LC 125

Approach (say out loud): “Two pointers from both ends. Skip anything that isn’t a letter or digit, compare lowercase versions, and move inward.”

Java:

class Solution {
public boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) {
return false;
}
l++;
r--;
}
return true;
}
}

Complexity: O(n) time, O(1) space

Edge cases: an empty string or only punctuation → true.

Problem: Two Sum II, Input Array Is Sorted (Medium) — LC 167

Approach (say out loud): “It’s sorted, so two pointers. If the sum is too small, move left forward to get a bigger number. If it’s too big, move right back. The answer uses 1-based indices.”

Java:

class Solution {
public int[] twoSum(int[] numbers, int target) {
int l = 0, r = numbers.length - 1;
while (l < r) {
int sum = numbers[l] + numbers[r];
if (sum == target) return new int[]{l + 1, r + 1};
if (sum < target) l++;
else r--;
}
return new int[]{-1, -1};
}
}

Complexity: O(n) time, O(1) space

Edge cases: negative numbers, duplicate values.

Problem: 3Sum (Medium) — LC 15

Approach (say out loud): “Sort first. Fix one number nums[i], then run Two Sum II on the rest for target -nums[i]. To avoid duplicate triplets, skip repeated values for i and also after finding a match.”

Java:

class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // skip duplicate i
if (nums[i] > 0) break; // the smallest is positive, so no sum can be 0
int l = i + 1, r = nums.length - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
res.add(Arrays.asList(nums[i], nums[l], nums[r]));
l++;
r--;
while (l < r && nums[l] == nums[l - 1]) l++; // skip duplicate l
} else if (sum < 0) {
l++;
} else {
r--;
}
}
}
return res;
}
}

Complexity: O(n²) time, O(1) extra space (ignoring sort and output)

Edge cases: all zeros [0,0,0,0] → one triplet, fewer than 3 elements → empty.

Problem: Container With Most Water (Medium) — LC 11

Approach (say out loud): “Start with the widest container. The area is limited by the shorter wall. Moving the taller wall inward can only make things worse, so I always move the shorter one.”

Java:

class Solution {
public int maxArea(int[] height) {
int l = 0, r = height.length - 1, best = 0;
while (l < r) {
int area = Math.min(height[l], height[r]) * (r - l);
best = Math.max(best, area);
if (height[l] < height[r]) l++;
else r--;
}
return best;
}
}

Complexity: O(n) time, O(1) space

Edge cases: two elements, equal heights (moving either side is fine).

Problem: Best Time to Buy and Sell Stock (Easy) — LC 121

Approach (say out loud): “As I scan, I track the lowest price so far, which is the best day to have bought. Today’s profit is price minus that minimum. I keep the max.”

Java:

class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE, best = 0;
for (int p : prices) {
minPrice = Math.min(minPrice, p);
best = Math.max(best, p - minPrice);
}
return best;
}
}

Complexity: O(n) time, O(1) space

Edge cases: prices only going down → 0, a single day → 0.

Problem: Longest Substring Without Repeating Characters (Medium) — LC 3

Approach (say out loud): “Variable sliding window. I expand with r. If s[r] is already in the window, I shrink from the left until it isn’t. I can jump l straight past the last index where that char appeared, using a map from char to last index.”

Java:

class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> lastSeen = new HashMap<>();
int l = 0, best = 0;
for (int r = 0; r < s.length(); r++) {
char c = s.charAt(r);
if (lastSeen.containsKey(c) && lastSeen.get(c) >= l) {
l = lastSeen.get(c) + 1; // jump past the duplicate
}
lastSeen.put(c, r);
best = Math.max(best, r - l + 1);
}
return best;
}
}

Complexity: O(n) time, O(k) space, where k is the charset size

Edge cases: empty string → 0, all the same char "bbbb" → 1. The >= l check matters for "abba": without it, l would jump backwards.

Problem: Longest Repeating Character Replacement (Medium) — LC 424

Approach (say out loud): “A window is valid if windowLength - countOfMostFrequentChar <= k, meaning I can replace the rest. Expand r. If it’s invalid, move l forward once. I don’t have to lower maxFreq when shrinking, because only a bigger maxFreq can give a longer answer.”

Java:

class Solution {
public int characterReplacement(String s, int k) {
int[] count = new int[26];
int l = 0, maxFreq = 0, best = 0;
for (int r = 0; r < s.length(); r++) {
maxFreq = Math.max(maxFreq, ++count[s.charAt(r) - 'A']);
while ((r - l + 1) - maxFreq > k) {
count[s.charAt(l) - 'A']--;
l++;
}
best = Math.max(best, r - l + 1);
}
return best;
}
}

Complexity: O(n) time, O(26) = O(1) space

Edge cases: k = 0, k ≥ length (the answer is the length).

Problem: Minimum Window Substring (Hard) — LC 76

Approach (say out loud): “I need the smallest window of s that contains all chars of t, counting duplicates. I count what t needs and keep missing = how many required chars are still missing. Expanding r over a still-needed char lowers missing. While missing == 0 the window is valid, so I record it and shrink from the left.”

Java:

class Solution {
public String minWindow(String s, String t) {
if (t.length() > s.length()) return "";
int[] need = new int[128];
for (char c : t.toCharArray()) need[c]++;
int missing = t.length(); // chars still missing
int l = 0, bestStart = 0, bestLen = Integer.MAX_VALUE;
for (int r = 0; r < s.length(); r++) {
if (need[s.charAt(r)] > 0) missing--;
need[s.charAt(r)]--; // can go negative for extra chars
while (missing == 0) {
if (r - l + 1 < bestLen) {
bestLen = r - l + 1;
bestStart = l;
}
need[s.charAt(l)]++;
if (need[s.charAt(l)] > 0) missing++; // removed a required char
l++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + bestLen);
}
}

Complexity: O(|s| + |t|) time, O(1) space (fixed array of 128)

Edge cases: t longer than s, no valid window → "", duplicate chars in t ("aa").