👶Explain Like I'm 5
🎯 Real-Life Example: Finding Two Friends in a Line
Imagine kids lined up by height (shortest to tallest). You need to find two kids whose combined heights equal a target height. Instead of checking every possible pair (which takes forever!), you do this smart trick:
- Start: Point to the shortest kid (left) and tallest kid (right)
- Too Short? If their combined height is less than target, move left pointer right (pick a taller kid on left)
- Too Tall? If combined height is more than target, move right pointer left (pick a shorter kid on right)
- Perfect? If heights match the target, you found them! 🎉
💡 Key Insight: This ONLY works because the array is sorted! You know moving left makes numbers bigger, moving right makes them smaller. This lets you eliminate half the possibilities with each move!
⏱️ Time Saved: Instead of checking all pairs (n² comparisons), you only need n comparisons!
🔍 Code Debugger
→ EXECUTING
1public int[] twoSum(int[] arr, int target) {
2int left = 0;
3int right = arr.length - 1;
4...
5while (left < right) {
6int sum = arr[left] + arr[right];
7...
8if (sum == target) {
9return new int[]{left, right}; // Found!
10} else if (sum < target) {
11left++; // Need larger sum
12} else {
13right--; // Need smaller sum
14}
15}
16return new int[]{-1, -1}; // Not found
17}
📊 Variables:
left:0
right:8
sum:0
target:10
🎯 Array Visualization
1
2
3
4
5
6
7
8
9
Left = 0 (arr[0] = 1)
Right = 8 (arr[8] = 9)
Current Sum:
1 + 9 = 0
Target: 10 ⬆️ Too Low
Click "Start" to begin visualization
1.0x (3.0s per step)
🐌 0.3x (Very Slow)1.0x (Normal)🚀 2.0x (Fast)
☕ Complete Java Solution
Two Pointers Patternpublic int[] twoSum(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
return new int[]{left, right}; // Found pair!
} else if (sum < target) {
left++; // Need larger sum
} else {
right--; // Need smaller sum
}
}
return new int[]{-1, -1}; // Not found
}
// Time Complexity: O(n) - single pass
// Space Complexity: O(1) - constant space🎯 When to Use Two Pointers?
✅
Keywords: “sorted array”, “pair”, “opposite ends”, “two elements”
✅
Classic Problems: Two Sum II (sorted), 3Sum, Container With Most Water, Trapping Rain Water, Remove Duplicates
💡
Pro Tip: Reduces O(n²) brute force to O(n) by eliminating redundant checks!
🚫
Don't Use If: Array is unsorted (use HashMap instead!)