Skip to main content

Guidelines

If there is a specific order (e.g. array is sorted) always think how you can utilize the two pointer approach, by comparing both ends of the array and making the decision based on their comparison. If the array is not sorted think if you can get an optimal solution by first sorting the array and then using the two pointer approach.

General approach on how to use it shown below:

int i = 0, j = arr.length - 1, calculation = 0;
while(i < j){
if(arr[i] < arr[j]){
++i;
}else if(arr[i] > arr[j]){
--j;
}else{
++i;
--j;
}
}

Under this category you will also find examples of problems that are using multiple pointers (remember two pointer approach is just general name for using two pointers to solve the problem) and each iteration we're making a decision on how to move the pointer by comparing the elements they're currently pointing at (e.g Sort Color). It's common to have a writer and iterator pointer when traversing through array that way we can discard some elements based on the problem requirements.