Skip to main content

Two Pointers

From beginn side and end site to loop. JS and PY3

let fn = arr => {
let left = 0, ans = 0, right = arr.length - 1;

while (left < right) {
// coding here for what is required!
if (CONDITION) {
left++;
} else {
right--;
}
}

return ans;
}
def fn(arr):
left = ans = 0
right = len(arr) - 1

while left < right:
## coding here for what is required!
if CONDITION:
left += 1
else:
right -= 1

return ans

If there are two arrays, run with following template

let fn = (arr1, arr2) => {
let i = 0, j = 0, ans = 0;

while (i < arr1.length && j < arr2.length) {
// coding here for what is required!
if (CONDITION) {
i++;
} else {
j++;
}
}

while (i < arr1.length) {
// coding here for what is required!
i++;
}

while (j < arr2.length) {
// coding here for what is required!
j++;
}

return ans;
}