Hello! In our previous lesson, we mastered the Comparable and Comparator interfaces, giving you the power to sort collections of any object in Java. That was a crucial step, because sorting data is often the prerequisite for applying highly efficient algorithms. Today, we'll explore one of the most powerful of these algorithms.
This lesson introduces the two-pointer technique, a fundamental pattern for solving array-based problems that is a favorite in technical interviews. You'll learn how to leverage a sorted array to find solutions in a single pass, drastically improving performance compared to more naive approaches. We will focus on the core logic and apply it to classic problems, solidifying your ability to recognize and implement this pattern.
1. The Core Idea: From Brute Force to Efficiency
Imagine you're given a sorted array and asked to find two numbers that meet a certain conditionāfor example, summing up to a target value. The most straightforward approach is to use nested loops: pick the first number, then loop through all the other numbers to see if you can form a pair that works. Then, pick the second number and repeat. This is the brute-force method.
With an array of size , this approach takes roughly operations, leading to a time complexity of . For large arrays, this is too slow. The two-pointer technique offers a brilliant optimization that reduces the time complexity to just .
The idea is simple: instead of iterating with two nested loops, we use two pointers (which are just integer indices) and move them intelligently through the array in a single pass.
šāāļøšāāļø Two Pointer Technique in Java ā The Ultimate ...
This article from dev.to provides a concise introduction to the concept.
First, read the section "What is the Two Pointer Technique?" to get a high-level definition. Then, scroll down to the "Comparison Table" to see the dramatic improvement in time complexity this technique offers over a brute-force approach.
There are a few variations of this pattern. We'll start with the most common one for sorted arrays, where one pointer starts at the beginning of the array and the other starts at the end.

2. The Classic Problem: "Two Sum" on a Sorted Array
Let's ground this in a concrete, famous interview problem: Given a sorted array of integers, find two numbers that add up to a specific target.
Problem:
- Input:
numbers = [2, 7, 11, 15],target = 9 - Output: The indices of the two numbers, e.g.,
[0, 1](becausenumbers[0] + numbers[1] == 9).
The Two-Pointer Algorithm:
- Initialize Pointers: Create a
leftpointer at index0and arightpointer at the last index (numbers.length - 1). - Loop and Check: While
leftis less thanright:
a. Calculate thesumof the values at the pointers:sum = numbers[left] + numbers[right].
b. Compare the sum to the target:
* Ifsum == target, you've found your pair! Return the indices.
* Ifsum < target, the sum is too small. To increase it, you must move theleftpointer one step to the right (left++), as the array is sorted and all values to the right are larger.
* Ifsum > target, the sum is too large. To decrease it, you must move therightpointer one step to the left (right--), as all values to the left are smaller. - End Condition: If the loop finishes (i.e.,
leftcrossesright) and no pair has been found, it means no such pair exists.
This logic works because the sorted nature of the array gives us a critical piece of information with every step. We always know which way to move a pointer to get closer to our target sum.
The following article walks through this exact problem, showing the brute-force method first and then the optimized two-pointer solution.
Mastering Coding Interview Patterns: Two Pointers (Java ...
This Medium article provides an excellent breakdown of the "Two Sum II" problem (the version on a sorted array).
Read section "1. Two Sum II ā Input Array Is Sorted". First, review the naive O(n²) solution to understand the baseline. Then, focus on the "Optimized Approach: Two Pointers" section. Study the explanation and the accompanying Java code carefully.
This next video provides a fantastic visual walkthrough, comparing the brute-force, a binary search approach, and finally the optimal two-pointer solution.
Visual introduction Two Pointer Algorithm | Data Structure and Algorithm for Coding Interviews
This video from Josh's DevBox clearly illustrates why the two-pointer approach is so effective.
Watch from the brute-force solution to understand the O(n^2) runtime. Then, see how it's improved to O(n \log n) using binary search. Finally, watch the explanation of the optimal two-pointer solution, which provides a step-by-step code walkthrough.
3. A Different Flavor: Merging Two Sorted Arrays
The two-pointer technique isn't limited to pointers moving from opposite ends. Another common variant involves pointers moving in the same direction across one or more arrays. A great example is merging two sorted arrays into a single sorted array.
Problem:
- Input:
array1 = [10, 15, 22, 80],array2 = [5, 8, 11, 70, 90] - Output:
[5, 8, 10, 11, 15, 22, 70, 80, 90]
The Algorithm:
- Initialize: Create a pointer for each input array,
p1forarray1andp2forarray2, both starting at index 0. Create a new result array large enough to hold all elements. - Compare and Copy: While both
p1andp2are within the bounds of their respective arrays:
a. Comparearray1[p1]andarray2[p2].
b. Copy the smaller of the two elements into the result array.
c. Increment the pointer of the array from which you just copied the element. - Copy Remainder: Once one of the loops finishes, one of the arrays will still have elements left. Copy all remaining elements from that array to the end of the result array.

This video demonstrates the merging process along with other applications of the two-pointer pattern.
Coding Interview Patterns - Two Pointers
This video from Nikhil Lohia explains how two pointers moving in the same direction can be used to merge sorted lists efficiently.
Watch the segment from this timestamp where the presenter explains how to merge two sorted lists. The visualization clearly shows how the pointers advance as elements are compared and added to the result.
Here's a sample Java implementation for merging two sorted arrays:
public int[] mergeSortedArrays(int[] arr1, int[] arr2) {
int n1 = arr1.length;
int n2 = arr2.length;
int[] result = new int[n1 + n2];
int p1 = 0; // Pointer for arr1
int p2 = 0; // Pointer for arr2
int pResult = 0; // Pointer for result array
// Compare elements and fill the result array
while (p1 < n1 && p2 < n2) {
if (arr1[p1] <= arr2[p2]) {
result[pResult++] = arr1[p1++];
} else {
result[pResult++] = arr2[p2++];
}
}
// Copy remaining elements from arr1, if any
while (p1 < n1) {
result[pResult++] = arr1[p1++];
}
// Copy remaining elements from arr2, if any
while (p2 < n2) {
result[pResult++] = arr2[p2++];
}
return result;
}
4. How to Spot the Pattern
As you prepare for interviews, the key is not just to know the pattern, but to recognize when to use it. Here are some clues in a problem description that should make you think "two-pointers":
- "Sorted array" or "sorted sequence": This is the biggest hint. The sorted property is what allows you to make intelligent decisions about moving the pointers.
- Finding pairs or triplets with a certain property: Problems like "Two Sum," "Three Sum," or finding a pair that is closest to a target value are prime candidates.
- Comparing elements from opposite ends: Any problem that involves looking at the first and last elements simultaneously, like checking if a string is a palindrome.
- Needing an in-place modification: Problems like "Remove Duplicates from Sorted Array" or "Move Zeroes to End" can be solved efficiently by using a slow and a fast pointer to overwrite the array.
Coding Interview Patterns - Two Pointers
This section of the video gives excellent advice on identifying when the two-pointer pattern is applicable.
Watch the segment on identifying keywords. The presenter lists several clues, such as seeing a sorted sequence, needing a target sum, or having to compare and combine elements, that suggest the two-pointer approach might be the optimal solution.
Conclusion
You've now learned one of the most versatile and efficient algorithmic patterns for interviews. The two-pointer technique transforms problems that seem to require quadratic time complexity into linear time solutions, a massive performance gain.
Here are the main takeaways:
- The two-pointer technique uses two indices to process an array in a single pass, achieving time complexity.
- For sorted arrays, the "opposite ends" approach is perfect for finding pairs that sum to a target, by intelligently shrinking the search space.
- The "same direction" approach is effective for problems like merging two sorted arrays.
- The key to the technique is leveraging the array's sorted property to decide which pointer to move next.
In our next lesson, we will explore a related pattern: the sliding window technique. It also uses two pointers, but in a different way to solve a different class of problems, typically involving finding optimal subarrays within a larger array.