DEV Community

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

Posted on

1 1

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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay