Skip to content

Latest commit

 

History

History
42 lines (32 loc) · 1.1 KB

two_pointer_technique.md

File metadata and controls

42 lines (32 loc) · 1.1 KB

Two-pointer Technique

It is one of the main techniques used for in-place Array algorithms. We can use it to iterate over the Array in two different places at the same time.

And it is also used in the

Example

Reverse an Array

def reverse_array(arr):
    left = 0
    right = len(arr) - 1
    while left < right:
        arr[left], arr[right] = arr[right], arr[left]
        left += 1
        right -= 1

Remove Duplicates from Sorted Array

def remove_duplicates(arr):
    if len(arr) == 0:
        return 0
    left = 0
    for right in range(1, len(arr)):
        if arr[left] != arr[right]:
            left += 1
            arr[left] = arr[right]
    return left + 1

Practice