DEV Community

Cover image for What I Wish I Knew Before Learning the Two Pointer Algorithm
M Umair Ullah
M Umair Ullah

Posted on

What I Wish I Knew Before Learning the Two Pointer Algorithm

🚀 Mastering the Two Pointers Technique in DSA

The Two Pointers technique is one of the most efficient and elegant solutions for solving array and string problems that involve searching, partitioning, or comparison. This guide will walk you through the complete concept of the Two Pointers technique, its motivation, real-world applications, variations, problem patterns, and code examples.

🔍 What is the Two Pointers Technique?

The Two Pointers technique involves using two variables (usually indices) that move through the data structure (like an array or string) in a coordinated way to solve a problem in linear or near-linear time.

  • Usually applied to sorted arrays or strings.
  • Used to avoid nested loops and reduce time complexity from O(n^2) to O(n) or O(n log n).
  • Pointers can move:

    • From both ends toward the center (inward)
    • From start to end (one slow, one fast)
    • Sliding over a fixed or dynamic window

🎯 Motivation

Two Pointers is widely used because:

  • It reduces brute-force complexity
  • It is elegant, easy to debug, and memory efficient
  • It covers core patterns for sliding window, partitioning, merging, etc.

đź”§ Variations of Two Pointers

Type Description Examples
Opposite Ends One pointer from start, one from end Container With Most Water, Two Sum II
Same Direction Both pointers start from one end Remove Duplicates, Move Zeroes
Sliding Window Two pointers define window Longest Substring Without Repeating Characters

📚 Common Problem Examples

1. Two Sum II (Sorted Array)

vector<int> twoSum(vector<int>& numbers, int target) {
    int i = 0, j = numbers.size() - 1;
    while (i < j) {
        int sum = numbers[i] + numbers[j];
        if (sum == target) return {i + 1, j + 1};
        else if (sum > target) j--;
        else i++;
    }
    return {};
}
Enter fullscreen mode Exit fullscreen mode

2. Container With Most Water

int maxArea(vector<int>& height) {
    int l = 0, r = height.size() - 1, maxWater = 0;
    while (l < r) {
        int area = (r - l) * min(height[l], height[r]);
        maxWater = max(maxWater, area);
        if (height[l] < height[r]) l++;
        else r--;
    }
    return maxWater;
}
Enter fullscreen mode Exit fullscreen mode

3. Move Zeroes

void moveZeroes(vector<int>& nums) {
    int i = 0;
    for (int j = 0; j < nums.size(); j++) {
        if (nums[j] != 0) swap(nums[i++], nums[j]);
    }
}
Enter fullscreen mode Exit fullscreen mode

4. 4Sum Problem (Nested Two Pointers)

vector<vector<int>> fourSum(vector<int>& nums, long long target) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> res;
    int n = nums.size();

    for (int i = 0; i < n; i++) {
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        for (int j = i + 1; j < n; j++) {
            if (j > i + 1 && nums[j] == nums[j - 1]) continue;
            int l = j + 1, r = n - 1;
            long long sum = target - nums[i] - nums[j];
            while (l < r) {
                long long curr = nums[l] + nums[r];
                if (curr < sum) l++;
                else if (curr > sum) r--;
                else {
                    res.push_back({nums[i], nums[j], nums[l], nums[r]});
                    while (l < r && nums[l] == res.back()[2]) l++;
                    while (l < r && nums[r] == res.back()[3]) r--;
                }
            }
        }
    }
    return res;
}
Enter fullscreen mode Exit fullscreen mode

đź§  Pattern Recognition

  • Partitioning Arrays: Move all negative/positive/zero elements to one side.
  • Sorting Problems: Merge sorted arrays, sort colors (Dutch National Flag).
  • Searching Problems: Two Sum, 3Sum, 4Sum, Closest Sum.
  • Window-based problems: Longest substring with no repeating characters.

🌎 Real-World Applications

  • Network Buffers: Optimizing streaming packet flow.
  • Image Processing: Windowed filtering, edge detection.
  • Bioinformatics: DNA strand comparison.
  • Finance: Max profit window in stock prices.

🔥 Bonus: Open Source Contributions

If you're looking to contribute to open source using Two Pointers logic:


🧑‍💻 Final Thoughts

Two Pointers is a cornerstone of your DSA foundation. Once you master it:

  • You reduce unnecessary complexity.
  • Improve runtime drastically.
  • Get closer to acing coding interviews at FAANG and top startups.

"Elegance in problem-solving often starts with two simple pointers."

Open Conntribution

Check out my Github Repo


Happy Coding 👨‍💻🎯

Top comments (0)