Opposite Direction Pointers Template

In this Template, pointers start from opposite ends of the array (one at the beginning, the other at the end).

The pointers move towards each other based on certain conditions until they meet.

Common use cases: checking for palindromes, two-sum in sorted arrays, and merging intervals.

Basic Template Structure: –

Java
int left = 0;
int right = arr.length - 1;
 
while (left < right) {
   //code
       
	     left++;
       right--;
 }

Scenario 1: – Target specific equality check.

If we have a target in our problem and our elemnts sum is equal to target.

 

Java
int left = 0;
int right = arr.length - 1;
 
 while (left < right) {
   //code

    if (currentSum == target) {
       
	     left++;
       right--;
    }
}

Scenario 2: – Less than check.
If we have a target in our problem and our elemnts sum is less than target.

 

Java
int left = 0;
int right = arr.length - 1;
 
while (left < right) {
   //code

    if (currentSum < target) {
       left++;
    }
}

Scenario 3: – Greater than check.
If we have a target in our problem and our elemnts sum is greater than target.

 

Java
int left = 0;
int right = arr.length - 1;
 
while (left < right) {
   //code

    if (currentSum > target) {
       right--;
    }
}

Final Template: – combined all the scenarios into a single structure with generic parameters

 

Java
int left = 0;
int right = arr.length - 1;
 
 while (left < right) {
   //code

    if (param1 == param2) {
       // code 
  
	     left++;
       right--;
    } else if (param1 < param2) {
       left++;
    } else {
       right--;
    }
}
Scroll to Top