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:
- Java
- JavaScript
- Python
- C++
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;
}
}
let 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;
}
}
i = 0
j = len(arr) - 1
calculation = 0
while i < j:
if arr[i] < arr[j]:
i += 1
elif arr[i] > arr[j]:
j -= 1
else:
i += 1
j -= 1
int i = 0, j = arr.size() - 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.