Same Direction Pointers Template

In this Template, both pointers start from the same side (often the beginning) and move forward in the same direction.

One pointer usually lags behind while the other explores ahead.

Common use cases: sliding window problems, removing duplicates, and substring/sequence matching.

Java
int left = 0;
int right = 1;

 while (right < arr.size()) {
   //code
  
	  left++;
    right++;  
}

Scenario 1: – Target specific equality check.

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

 

Java
int left = 0;
int right = 1;

 while (right < arr.size()) {
   //code
   if(currentDiff == target) {
	   //code
		left++;
		right++;
   } 
}

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

 

Java
int left = 0;
int right = 1;

 while (right < arr.size()) {
   //code
   if(currentDiff < target) {
	   //code
		right++;
   } 
}

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

 

Java
int left = 0;
int right = 1;

 while (right < arr.size()) {
   //code
   if(currentDiff > target) {
	   //code
		left++;
   } 
}

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

 

Java
int left = 0;
 int right = 1;

 while (right < arr.size()) {
   //code

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