pointers
) to traverse an array
, string
, or linked list
from different directions or at different speeds.
O(n)
instead of O(n²)
.
Two Sum
in sorted array etc).
Remove Duplicates
, Sliding Window
etc).
O(n²)
→ O(n)
or O(n log n)
.
O(1)
).
arrays
, strings
, and linked lists
.
array
/string
is sorted (most common case).
arrays
, strings
,
linked lists
etc.
O(n²)
).
subarrays
/substrings
(sliding window is an extension of this).
sum
, difference
, etc.).
window size
, distance
).
public class MainApp1
{
public static void main(String[] args)
{
int[] arr = {2, 3, 4, 7, 11, 15};
int target = 10;
int left = 0, right = arr.length - 1;
boolean found = false;
while (left < right)
{
int sum = arr[left] + arr[right];
if (sum == target)
{
System.out.println("Pair found at "+left+" and "+right+" index positions");
found = true;
break;
}
else if (sum < target)
{
left++; // Move left pointer forward
}
else
{
right--; // Move right pointer backward
}
}
if (!found)
System.out.println("No pair found");
}
}
Pair found at 1 and 3 index positions
public class MainApp2
{
public static void main(String[] args)
{
int[] arr = {1, 1, 2, 2, 3, 3, 4, 5};
int n = arr.length;
int left = 0; // points to last unique element
int right = 1; // used to scan the array
while (right < n)
{
if (arr[right] != arr[left])
{
left++; // move left to next position
arr[left] = arr[right]; // place unique element at left
}
right++; // always move right pointer
}
// Print unique elements (first left+1 elements are unique)
System.out.print("Array after removing duplicates: ");
for (int i = 0; i <= left; i++)
{
System.out.print(arr[i] + " ");
}
}
}
Array after removing duplicates: 1 2 3 4 5
Here are some popular problems solved using Two Pointers:
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.