Learning Objectives
- Identify monotonic subarray/substring constraints suited for Sliding Window.
- Maintain frequency/last-seen invariants accurately while advancing `left` and `right` pointers.
Prerequisites
- Arrays, Strings, HashMap / Set lookup complexity
Why Two Pointers Collapse Nested Loops
Brute-force scanning every (i, j) pair across an array of size 100,000 executes ~5 billion steps and fails HackerRank OAs with Time Limit Exceeded. Whenever shrinking/expanding a contiguous window `[left, right]` preserves a monotonic invariant, each pointer moves forward at most `N` times total — yielding O(N) worst-case time complexity.
Practice more interview patterns with Java Collections or join our Java Backend 150-Problem Coding Lab (+ 3 Months OA/HackerRank Support).
Practical Programming Examples
Longest Substring Without Repeating Characters in O(N) (Java 21)
Given a string s, find the length of the longest contiguous substring containing all distinct characters in O(N) time.
import java.util.HashMap;
import java.util.Map;
public class SlidingWindowDemo {
public static int longestUniqueLength(String s) {
Map<Character, Integer> lastSeen = new HashMap<>();
int left = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);
if (lastSeen.containsKey(ch)) {
left = Math.max(left, lastSeen.get(ch) + 1);
}
lastSeen.put(ch, right);
best = Math.max(best, right - left + 1);
}
return best;
}
public static void main(String[] args) {
System.out.println("Longest unique length = " + longestUniqueLength("abcabcbb"));
}
}
Longest unique length = 3
- `right` advances across every character once, storing its latest index inside `lastSeen`.
- Using `Math.max(left, lastSeen.get(ch) + 1)` ensures `left` never moves backward past already excluded duplicates.
- Total iterations equal `s.length()` (O(N) time, O(min(N, alphabet)) space).
Common Mistakes to Avoid
- Writing `left = lastSeen.get(ch) + 1` without `Math.max(left, ...)`, accidentally rewinding `left` backward on earlier duplicate chars.
- Trying to apply standard Sliding Window when negative array values allow non-monotonic sum recovery.
Production Best Practices
- Always state the exact window invariant in one sentence before coding (`window [left..right] contains zero duplicate chars`).
Technical Interview Relevance
Top 3 most repeated coding screen pattern across TCS Digital, Amazon, Flipkart, and product SDE-1 interviews.
Practice & Self-Check Questions
Why does a subarray sum target problem with BOTH positive and negative numbers fail two-pointer Sliding Window?
Negative integers mean expanding right can shrink the sum and shrinking left can raise it, breaking window monotonicity; solve with Prefix Sum + HashMap.