Two Pointers

DSA · Arrays and Searching

Theory

The two-pointer technique uses two indexes that move through the data, either towards each other from both ends or in the same direction at different speeds. Each step uses a simple rule to decide which pointer to move, so the whole array is processed in a single pass. It often replaces a nested loop, reducing O(n²) to O(n).

Why we use it

It solves many pair, partition and in-place problems in linear time with constant extra memory.

When to use it

Use it on sorted arrays (pair sums), for reversing or partitioning in place, for removing duplicates, palindrome checks, and merging two sorted lists.

How it works

  1. Start: left = 0, right = n - 1 (sorted array)
  2. Is left < right? Yes: sum = arr[left] + arr[right]. No: Stop: no pair found.
  3. sum == target? Yes: Return the pair. No: Move one pointer.
  4. sum < target? Yes: left = left + 1 (need bigger). No: right = right - 1 (need smaller).
  5. Repeat

Syntax

left, right = 0, n-1
while left < right:
    if condition met: record answer
    elif need bigger:  left += 1
    else:              right -= 1

Time: O(n)   Space: O(1)

Example

def pair_with_sum(sorted_nums, target):
    left, right = 0, len(sorted_nums) - 1
    while left < right:
        total = sorted_nums[left] + sorted_nums[right]
        if total == target:
            return sorted_nums[left], sorted_nums[right]
        if total < target:
            left += 1
        else:
            right -= 1
    return None

def is_palindrome(s):
    i, j = 0, len(s) - 1
    while i < j:
        if s[i] != s[j]:
            return False
        i += 1
        j -= 1
    return True

print(pair_with_sum([1, 3, 4, 6, 8, 11], 14))
print(is_palindrome("racecar"), is_palindrome("python"))

Key points

DSA topics

Introduction to DSA

Arrays and Searching

Sorting Algorithms

Linked Lists

Stacks and Queues

Hashing

Trees

Heaps

Graphs

Algorithm Techniques

Classic Algorithms

Dynamic Programming

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Data Structures & Algorithms

The complete DSA roadmap: theory, why and when to use every structure and algorithm, Big O complexity, and Python code you can run right here in the browser.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice DSA Online 251 problems across 13 patterns, with hidden tests and step-by-step optimal solutions. Start practising →
Section {{ sec.num }}

{{ sec.label }}

DSA  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ current.why }}

When to use it

{{ current.when }}

Flowchart — how {{ current.name }} works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Step-by-step visualisation
{{ cell.v }}
{{ cell.i }} {{ cell.tag }}
Step {{ vizStepLabel }}: {{ vizNote }}
■ comparing ■ swapping / moving ■ done / found ■ out of range
Complexity & Pseudocode
{{ current.syntax }}
Example Code
{{ current.example }}
▶ Try It Live — runs real Python 3 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic