DEV Community

Cover image for Python - Use Two-Pointer Technique for Efficient Array and String Manipulation
Keyur Ramoliya
Keyur Ramoliya

Posted on

Python - Use Two-Pointer Technique for Efficient Array and String Manipulation

The Two-Pointer Technique involves using two-pointers that traverse an array or string to solve problems efficiently. It is especially useful for tasks like searching for pairs, reversing elements, or checking for specific conditions. Here's an example:

def find_pairs(nums, target):
    left, right = 0, len(nums) - 1
    pairs = []

    while left < right:
        current_sum = nums[left] + nums[right]

        if current_sum == target:
            pairs.append((nums[left], nums[right]))
            left += 1
            right -= 1
        elif current_sum < target:
            left += 1
        else:
            right -= 1

    return pairs

# Example usage:
sorted_nums = [1, 2, 3, 4, 5, 6, 7]
target_sum = 9
result = find_pairs(sorted_nums, target_sum)
print(result)  # Output: [(2, 7), (3, 6), (4, 5)]
Enter fullscreen mode Exit fullscreen mode

In this example, we use the Two-Pointer Technique to find pairs of elements in a sorted array that sum up to a target value. By maintaining two pointers (left and right) and adjusting them based on the current sum, we efficiently identify pairs that meet the desired condition.

The Two-Pointer Technique can also be applied to other problems, such as removing duplicates from a sorted array, checking for palindromes in strings, or solving related tasks efficiently without the need for nested loops. It's a versatile strategy for optimizing array and string manipulation algorithms.

Top comments (0)