🌐
GeeksforGeeks
geeksforgeeks.org › dsa › two-pointers-technique
Two Pointers Technique - GeeksforGeeks
DSA Python · Last Updated : 13 ... is a simple yet powerful strategy where you use two indices (pointers) that traverse a data structure - such as an array, list, or string - either toward each other or in the same direction to solve problems more efficiently ...
Published: February 13, 2026
🌐
Medium
medium.com › @rajsigh717 › python-interview-two-pointer-technique-5c4e3259a909
Python Interview — Two Pointer technique
February 27, 2024 - Python — Two Pointer The two-pointer technique is a pattern where two pointers iterate over the data structure in together or separately until they satisfy a certain condition. This pattern is …
Discussions

Two-Pointer Technique, an In-Depth Guide: Concepts Explained | Questions to Try | Visuals and Animations
I really really need this so much right now thank you for making this I wish u keep making this i love it thank you! More on reddit.com
🌐 r/leetcode
16
273
December 12, 2023
Why python for loop is working faster than two pointer approach for finding max element in list but in while loop two pointer approach is faster? - Stack Overflow
I recently started learning DSA and I came across the idea of using two pointers to iterate our the list so that we can reduce the time for the iteration, and I made this program in python to find ... More on stackoverflow.com
🌐 stackoverflow.com
two pointer approach
Can you elaborate? Python doesn't really have any exposed pointers (unless you count ctypes) , so I'm not sure what you're talking about. More on reddit.com
🌐 r/learnpython
4
1
November 23, 2020
2020 Day 1 (Part 1) [Python] Two Pointers Method

the most optimal

With a boolean table, the problem can be solved in O(n):

Go through the input once, set the table to true at any position corresponding to the inputs. Then go through the input again and check if the table is set at position (2020 - current number). If so, that's the result.

More on reddit.com
🌐 r/adventofcode
3
2
December 8, 2020
🌐
Hello Interview
hellointerview.com › learn › code › two-pointers › overview
Two-Pointer Overview
This continues until either our pointers meet (in which case we did not find a successful pair) or until we find a pair that sums to our target, like we did here. Visualization · Hide Code · PythonFull Screen · Try these examples:Has pairNo pairResetEdit input · def twoSum(nums, target): left, right = 0, len(nums) - 1 ·
🌐
Vets Who Code
vetswhocode.io › blogs › two-pointers-a-practical-technique-for-code-challenges
Two pointers: a practical technique for code challenges - Vets Who Code
July 14, 2025 - Master the Two Pointers technique with practical Python and JavaScript examples designed to help you ace technical interviews.
🌐
ByteByteGo
bytebytego.com › courses › coding-patterns › two-pointers › introduction-to-two-pointers
Introduction to Two Pointers
We discuss all of these techniques in detail throughout the problems in this chapter. A two-pointer algorithm usually requires a linear data structure, such as an array or linked list.
🌐
Towards Data Science
towardsdatascience.com › home › programming › two pointers approach - python code
Two Pointers Approach - Python Code | Towards Data Science
April 17, 2021 - Implementation in Python: text · def maxArea(height): l, r, max_area = 0, len(height)-1, 0 while l<r: base = r-l if height[r] >= height[l]: h = height[l] l+=1 else: h = height[r] r-=1 print(l,r) if h * base > max_area: max_area = h * base return max_area · Note: In the last problem, the array was not sorted but still two pointer approach was applicable.
🌐
AlgoMaster
algomaster.io › home › dsa › introduction to two pointers
Introduction to Two Pointers | DSA | AlgoMaster.io
May 30, 2026 - Which pointer to move depends on the comparison. In sorted arrays: Moving left right increases values (if sorted ascending) Moving right left decreases values (if sorted ascending) Opposite-direction two pointers for pair-sum problems such as Two Sum II and 3Sum requires the array to be sorted.
Find elsewhere
🌐
Reddit
reddit.com › r/leetcode › two-pointer technique, an in-depth guide: concepts explained | questions to try | visuals and animations
r/leetcode on Reddit: Two-Pointer Technique, an In-Depth Guide: Concepts Explained | Questions to Try | Visuals and Animations
December 12, 2023 -

The two-pointer technique I’m referring to here involves using two pointers that start at opposite ends of an array and gradually move towards each other before meeting in the middle.

left                            right
 ↓                                ↓
 --- --- --- --- --- --- --- --- ---
| 2 | 1 | 2 | 0 | 1 | 0 | 1 | 0 | 1 |
 --- --- --- --- --- --- --- --- ---

This technique should be your go-to when you see a question that involves searching for a pair (or more!) of elements in an array that meet a certain criteria.

In this guide, we'll start by understanding how the technique produces the efficient O(n) time-complexity solutions that those questions require (answer: by eliminating pairs). I'll then provide follow-up questions for you to try, with lots of visuals and interactive animations to help along the way.

Sample Problem: Two Sum (easy)

Starting with a sorted array of integers, find a pair of numbers that sum to the given target.

Let’s walkthrough how the two-pointer technique eliminates unnecessary pairs from the search when the input array is [1, 3, 4, 6, 8, 10, 13] and target = 13

Step 1: Initialize pointers at opposite ends of array and sum the two elements together. This represents the first pair we are considering in our search.

left                     right
 ↓                         ↓
 --- --- --- --- --- ---- ----   
| 1 | 3 | 4 | 6 | 8 | 10 | 13 |     current_sum = array[left] + array[right] = 14
 --- --- --- --- --- ---- ----   

Step 2: Compare current_sum with target. Since current_sum > target, move the right pointer backwards.

To see why, notice that all other pairs that use 13 are also greater than our current_sum.So by moving the right pointer to 10, we can eliminate those unnecessary pairs from our search.

left                 right
 ↓                     ↓
 --- --- --- --- --- ---- ----
| 1 | 3 | 4 | 6 | 8 | 10 | 13 |          by moving right pointer back...
 --- --- --- --- --- ---- ----



		   21--------
                  |         | 
           17-----|-------- | 
          |       |       | | 
 --- --- --- --- --- ---- ----
| 1 | 3 | 4 | 6 | 8 | 10 | 13 |     we eliminated these pairs from our search  
 --- --- --- --- --- ---- ---- 
      |       |       |   | | |
       16-----|-------|---- | |
              |       |     | |
               19-----|------ |
                      |       |
                       23------

Step 3: Compare current_sum with target. Since current_sum < target, move the left pointer forwards. This follows similar reasoning to the step above: all other pairs that use element 1 are less than our target, so we should move our left pointer forward to eliminate those pairs.

left                 right
 ↓                     ↓
 --- --- --- --- --- ---- ----
| 1 | 3 | 4 | 6 | 8 | 10 | 13 |                move left pointer forwards
 --- --- --- --- --- ---- ----

============= TO =============

     left            right
      ↓                ↓
 --- --- --- --- --- ---- ----
| 1 | 3 | 4 | 6 | 8 | 10 | 13 |                   current_sum = 13
 --- --- --- --- --- ---- ----

Termination: Repeat process until current_sum == target, like it does here. Or, if the pointers meet at the same index, then a pair was not found.

Time Complexity: O(n). This is done in a single pass. By using the two-pointer technique, we avoid the nested for-loop required by the brute force solution.

Click here for a more in-depth breakdown of this question, including an interactive animation of the Python solution.

Try It Yourself: Follow-up Questions

  • Container With Most Water (medium)

Hint: Instead of summing the elements at each pointer, compare their values instead. Which containers can you eliminate?

Stuck? This link helps you visualize each step alongside the Python implementation.

  • 3Sum (medium)

                     i, left, right represent current triplet      

          i  left              right 
          ↓   ↓                  ↓              
         ---- ---- ---- --- --- ---                   
        | -4 | -1 | -1 | 0 | 1 | 2 |             can you use two sum?
         ---- ---- ---- --- --- ---              

                   ...

               i   left         right
               ↓    ↓            ↓              
         ---- ---- ---- --- --- ---             
        | -4 | -1 | -1 | 0 | 1 | 2 |         can you use two sum again?    
         ---- ---- ---- --- --- ---              

Hint: sort the array, iterate over each item, repeatedly apply two sum.

This link helps you visualize each step of the implementation (without showing the Python implementation)

  • Valid Triangle Number (medium)

Hint: sort the array, then use the triangle inequality, which states that if a triangle has sides of lengths a, b, and c, then all three of (1) a + b > c (2) a + c > b (3) c + b > a must be true.

                   i, left, right represent current triplet
        

        left              right  i
         ↓                  ↓    ↓              
         --- --- --- ---- ---- ----                   
        | 4 | 6 | 9 | 11 | 15 | 18 |        which triplets can you eliminate?
         --- --- --- ---- ---- ----         

This link helps you visualize each step of the implementation (without showing the Python implementation)

  • 3Sum Closest

A variation of 3Sum.

Summary

  • If a question involves searching for a pair (or more!) items in an array that meet a certain criteria, see if you can use the two-pointer technique to come up with an efficient solution.

  • The questions linked here use the two-pointer technique to eliminate unnecessary pairs from the search, producing O(n) solutions compared to the O(n2) brute-force solutions.

  • To use the technique: initialize the pointers (typically at opposite ends of the array, but not always). Look at the values at each pointer. From those values, think about how to move each pointer so that you can eliminate unecessary pairs from the search.

Bonus! Partitioning Arrays

The two-pointer technique can also be used to solve problems that involve partition arrays into different regions. For these questions, each pointer represents where the next element belonging to that region should go.

     (next 0 here!)  (next 2 here!)   
         left           right                      Sorting array of 0, 1, 2s
          ↓               ↓
 --- --- --- --- --- --- --- --- --- ---
| 0 | 0 | 1 | 1 | 2 | 1 | 1 | 2 | 2 | 2 |
 --- --- --- --- --- --- --- --- --- ---
|______||_______||__________||______|       
    0s     1s      unsorted     2s

Example: Sort Colors (medium)

Given an unsorted array nums with n integers that are either 0, 1, or 2.
Sort the array in-place in ascending order. 

Solve this problem in one-pass without any extra space.

We'll actually initialize 3 pointers:

  • left and right at opposite ends of the array. The left pointer represents the position of the next 0, and the right pointer represents the position of the next 2.

  • i at the beginning of the array. This pointer represents the current element we are trying to sort, as well as the boundary of the "ones" region.

These three pointers split our array into four regions, an unsorted region, and 0s, 1s, and 2s regions, which are all empty and not shown.

         i
        left                right
         ↓                    ↓
         --- --- --- --- --- --- 
        | 2 | 1 | 2 | 0 | 1 | 0 |
         --- --- --- --- --- --- 
        |_______unsorted________|

The idea here is that we iterate until i crosses right. At each iteration:

  • if nums[i] == 0, we swap i with the element at the left pointer, move left pointer forward and increment i

  • if nums[i] == 1, we increment i

  • if nums[i] == 2, we swap i with the element at the right pointer, move right pointer backward.

         i
        left                right
         ↓                    ↓
         --- --- --- --- --- --- 
        | 2 | 1 | 2 | 0 | 1 | 0 |        Start 
         --- --- --- --- --- ---         (empty regions not shown)
        |_______unsorted________|   
    
      
         i
        left            right
         ↓                ↓              Step 1: nums[i] == 2
         --- --- --- --- --- --- 
        | 0 | 1 | 2 | 0 | 1 | 2 |        swap i with right
         --- --- --- --- --- ---         move right pointer back
        |______unsorted_____||__|   
                              2s

              i
             left       right
              ↓           ↓             Step 2: nums[i] == 0
         --- --- --- --- --- ---
        | 0 | 1 | 2 | 0 | 1 | 2 |       swap i with left
         --- --- --- --- --- ---        move left pointer forward
        |__||___unsorted____||__|       increment i
         0s                   2s


             left i     right
              ↓   ↓       ↓             Step 3: nums[i] == 1
         --- --- --- --- --- ---
        | 0 | 1 | 2 | 0 | 1 | 2 |       increment i
         --- --- --- --- --- ---     
        |___||__||_unsorted_||__|       
          0s  1s              2s


             left i  right
              ↓   ↓   ↓                  Step 4: nums[i] == 2
         --- --- --- --- --- ---
        | 0 | 1 | 1 | 0 | 2 | 2 |       swap i with right
         --- --- --- --- --- ---        move right pointer back
        |___||__||______||______|       
          0s  1s unsorted   2s


                    ...


               left right i 
                  ↓   ↓   ↓               Termination (i > right)
         --- --- --- --- --- ---
        | 0 | 0 | 1 | 1 | 2 | 2 |         return sorted array
         --- --- --- --- --- ---
        |_______||______||______|
           0s       1s      2s

Time Complexity: Single pass, O(n).Space Complexity: O(1).

Click here a more in-depth breakdown of this question, including an interactive animation of the Python solution.

Try It Yourself

  • Move Zeroes (easy)

Not exactly the two-pointer technique described here, but good practice for using a pointer to represent a region of an array.

         what goes here? 
          nextNonZero i
              ↓       ↓  
         --- --- --- --- ---- 
        | 1 | 0 | 0 | 3 | 12 | 
         --- --- --- --- ---- 

Hint: use a pointer to represent the position of the next non-zero you find.

This link helps you visualize each step of the implementation (without showing the Python implementation)

  • Partition Array According to Given Pivot (medium)

Hint: follow a similar approach to sort colors, but copy items to a new output array to maintain relative ordering.

Summary

  • If a question calls for partitioning an array into different regions: initialize one pointer for each region you need to create.

  • Then iterate over the array and place each element in the correct position (as dictated by the pointer).

  • Move the pointer to indicate where the next element that belongs in that region should go.

I love breaking down the algorithm patterns that will help you land your next dream job in tech. There will be many more coming in the near future. If you found this guide helpful, or if there is anything you would like me to cover in the future, please leave a comment! It means a lot :)

🌐
CodeSignal
codesignal.com › learn › courses › master-dictionaries-two-pointers-and-more-algorithms-in-python › lessons › manipulating-arrays-with-hashing-and-two-pointers-technique
Manipulating Arrays with Hashing and Two Pointers ...
This Python function iteratively replaces each element in array A according to the defined logic and returns the modified array. ... It's vital to have an understanding of the computational complexity of our Two-Pointer approach and why it's effective for this problem.
🌐
Kaggle
kaggle.com › code › liamhealy › python-algorithms-two-pointer
Python Algorithms: Two-Pointer
December 22, 2023 - Python Algorithms: Two-PointerSummary · This Notebook has been released under the Apache 2.0 open source license. Input1 file · arrow_right_alt · Output0 files · arrow_right_alt · Logs13.2 second run - successful · arrow_right_alt · Comments0 comments ·
🌐
Medium
mrmuhammadazeemrao.medium.com › the-two-pointers-technique-in-python-a-deep-dive-c556875565f2
The Two Pointers Technique in Python: A Deep Dive | by MUHAMMAD AZEEM RAO | Medium
August 9, 2023 - Move the right pointer one step left to the number 4. New sum = 1 + 4 = 5, which matches our target. Voila! Our desired pair is (1, 4). When using the two-pointers technique, it’s essential to consider the possibility of no valid pair adding up to the target sum.
🌐
CodeSignal
codesignal.com › learn › courses › master-dictionaries-two-pointers-and-more-algorithms-in-python › lessons › efficient-pair-sum-identification-with-the-two-pointer-technique
Efficient Pair Sum Identification with the Two-Pointer ...
Envision the problem at hand: we've been given an array of distinct integers and a target value. The task is to find all pairs of integers from the given array that sum up to the target value using the two-pointer technique. The function find_pairs should take this array of integers and a target value as parameters.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python3-program-for-two-pointers-technique
Python3 Program for Two Pointers Technique - GeeksforGeeks
July 23, 2025 - We take two pointers, one representing the first element and other representing the last element of the array, and then we add the values kept at both the pointers. If their sum is smaller than X then we shift the left pointer to right or if ...
🌐
AlgoDaily
algodaily.com › lessons › using-the-two-pointer-technique
AlgoDaily - Using the Two Pointer Technique
Once we're set up, what we want to do is check if the current pointers already sum up to our target. This might happen if the correct ones are on the exact opposite ends of the array. ... These snippets implement the logic to check if the sum of two numbers from an array equals the target value, returning the appropriate result. In Python, the code snippet returns a boolean value, while the other languages return the indices or values of the two numbers that add up to the target.
🌐
LinkedIn
linkedin.com › pulse › two-pointer-technique-guide-visual-learners-jimmy-zhang-toxie
Two-Pointer Technique: A Guide for Visual Learners
December 12, 2023 - Hint: Instead of summing the elements at each pointer, compare their values instead. Which containers can you eliminate? Stuck? This link helps you visualize each step alongside the Python implementation. 3Sum (medium)Hint: sort the array, iterate over each item, repeatedly apply two sum.
🌐
Stack Overflow
stackoverflow.com › questions › 73389838 › why-python-for-loop-is-working-faster-than-two-pointer-approach-for-finding-max
Why python for loop is working faster than two pointer approach for finding max element in list but in while loop two pointer approach is faster? - Stack Overflow
A 2-pointer 'windowing' solution is for speeding up particular problems that might otherwise has quadratic runtimes (e.g. loop within a loop). ... @Stuart yes I know the data is already sorted but that's not the issue, what I am not able to ...
🌐
DEV Community
dev.to › charlesamakoye › dissecting-the-two-pointer-technique-2lb4
Dissecting the two pointer technique - DEV Community
August 10, 2024 - This approach involves two pointers starting from opposite ends of the data structure and moving toward each other, meaning the pointers move in opposite directions. This type of two-pointer technique is particularly useful in scenarios where you want to find a pair of elements that meet certain conditions or when comparing elements from both ends.
🌐
YouTube
youtube.com › watch
2 Pointers Algorithm - DSA Course in Python Lecture 12 - YouTube
Master Data Structures & Algorithms for FREE at https://AlgoMap.io/Code solutions in Python, Java, C++ and JS for this can be found at my GitHub repo here: h...
Published: July 19, 2024
🌐
Codú
codu.co › home › scott böning › the two-pointers approach for array and string problems
The two-pointers approach for array and string problems | by Scott Böning | Codú
March 23, 2023 - One common method to implement two-pointers is to start one pointer at the first index 0, and the other pointer at the last index iterable.length – 1. In a while loop, move the pointers towards each other until they are equal to each other.
🌐
AlgoMonster
algo.monster › problems › two_pointers_intro
Two Pointers Introduction
When the pointers meet in the middle, every pair matched, so the word is a palindrome. A sliding window keeps the two pointers a set distance apart and works with all the values between them, not just the two endpoints. The simplest version uses a fixed-size window.