### General - technique that involves indices left and right, on an array/string - extremely common ### First Implementation - start pointers at edges of the array, move them towards each other until they meet ``` function fn(arr): left = 0 right = arr.length - 1 while left < right: Do some logic here depending on the problem Do some more logic here to decide on one of the following: 1. left++ 2. right-- 3. Both left++ and right-- ``` - strength of this technique is you always get $O(n)$ runtime - the pointers start $n$ away from each other, and at least one of them will move closer each iteration - given work in each iteration is $O(1)$ - we also only have to use $O(1)$ space, you only ever store 2 indices ### Second Implementation - we have two arrays in input, put a pointer at both's starting index - push one or both pointers forward each iteration - use a while loop until one pointer reaches its iterable's end ``` function fn(arr1, arr2): i = j = 0 while i < arr1.length AND j < arr2.length: Do some logic here depending on the problem Do some more logic here to decide on one of the following: 1. i++ 2. j++ 3. Both i++ and j++ // Step 4: make sure both iterables are exhausted // Note that only one of these loops would run while i < arr1.length: Do some logic here depending on the problem i++ while j < arr2.length: Do some logic here depending on the problem j++ ``` - runtime is linear time complexity at $O(n + m)$ ### Merge Sorted Arrays (Second Implementation) ``` def merge(l1, l2): i1 = i2 = 0 l3 = [] while i1 < len(l1) and i2 < len(l2): if l1[i1] > l2[i2]: l3.append(l2[i2]) i2 += 1 else: l3.append(l1[i1]) i1 += 1 while i1 < len(l1): l3.append(l1[i1]) i1 += 1 while i2 < len(l2): l3.append(l2[i2]) i2 += 1 return l3 ``` ### Final Tips - sometimes you might find a problem that starts pointers at different indices - or maybe with only one input array you initialize both pointers at the first index and move both of them forward - three pointers is another possibility - two pointers just refers to using two index variables to move along some iterable(s)