Skip to content
Learn Netverks

Lesson

Step 13/36 36% through track

two-pointers

Two pointers

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Two pointers: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

These patterns turn O(n²) scans into O(n log n) or O(n)—core interview toolkit.

You will apply Two pointers in contexts like: Interview loops, performance tuning, and foundational CS courses.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on. Also trace indices on paper for a small example input.

When you can explain the previous lesson's ideas in your own words.

The two-pointer technique uses two indices on a sorted array (or string) to find pairs or partitions in O(n) instead of O(n²).

When to use

  • Sorted array — pair with target sum
  • Remove duplicates in-place
  • Partition array (quickselect preview)

Sorted pair sum

#include 
#include 

int main() {
    std::vector a = {1, 2, 4, 6, 10};
    int target = 10;
    int lo = 0, hi = (int)a.size() - 1;
    while (lo < hi) {
        int s = a[lo] + a[hi];
        if (s == target) {
            std::cout << lo << ", " << hi << "\n";
            break;
        }
        if (s < target) ++lo;
        else --hi;
    }
    return 0;
}

Invariant

If sum too small, advance lo; if too large, shrink hi. Works because sorting orders possibilities.

Important interview questions and answers

  1. Q: Why sorted?
    A: Monotonic move of pointers proves we never skip the only valid pair.
  2. Q: Two pointers vs hash map?
    A: Sorted + two pointers O(n) time O(1) space; hash map O(n) time O(n) space for unsorted.

Self-check

  1. What is time complexity of two-pointer scan?
  2. When does moving lo vs hi?

Pitfall: Two pointers on unsorted data for pair-sum usually needs sorting first or a hash map.

Interview prep

When use?

Sorted arrays—pair sum, remove duplicates, partition.

Complexity?

O(n) single pass with two indices.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Sorted pair sum?
  • Opposite ends?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump