Learn the Two Pointer Approach with Me – Beginner Friendly Guide

Hey there! 👋 In this blog, we’re going to learn one of the most powerful techniques used to solve array and string problems — the Two Pointer Approach.
This approach allows us to look at different parts of an array or string from two ends or positions to find the answer faster.
I’m going to explain this using a famous LeetCode problem called "Container With Most Water."
We have some vertical lines standing next to each other. Each line has a height.
Our goal is to pick two lines that can hold the most water between them. You can imagine these two lines and the ground forming a container — and the water fills up to the height of the shorter line.
The amount of water depends on two things:
The height of the shorter line (if one line is taller, the water can’t go higher than the short one — or it would overflow).
The distance between the two lines (this is like the width of the container).
So, our task is to find the two lines that, together, form the container that holds the maximum water.
Example:
If the heights are [1, 8, 6, 2, 5, 4, 8, 3, 7]
,
the lines at index 1 (height 8) and index 8 (height 7) form the container that holds the most water.
The distance between these two lines is (8 - 1) = 7
.
The shorter line is height 7, so the water area is:
7 (height) × 7 (distance) = 49 units of water
Solutions
Brute Force Approach:
This is the most basic way to solve the problem.
we need to check every possible pair of lines, calculate the area, and keep track of the maximum.
Logic:
Use two nested loops
For every pair
(i, j)
, calculate:width = j - i
height = min(height[i], height[j])
area = width * height
Return the maximum area found
Time Complexity:
O(n²) — because you're checking every possible pair
This is slow for big arrays
let max = 0;
for (let i = 0; i < height.length; i++) {
for (let j = i + 1; j < height.length; j++) {
let area = (j - i) * Math.min(height[i], height[j]);
max = Math.max(max, area);
}
}
Two Pointer Approach:
This is a smart and optimized way.
we need to place one pointer at the start and one at the end of the array. Then, move the pointer that's at the shorter line to try and find a better answer.
Logic:
Start with two pointers:
left = 0
,right = height.length - 1
While
left < right
:Calculate the area between
height[left]
andheight[right]
Move the pointer at the shorter line (because a taller line might give a bigger area)
Time Complexity:
O(n) — you only go through the array once
Much faster and better for large inputs
let left=0,right=height.length-1
let max = 0;
while(left <=right){
w=right-left
h=Math.min(height[left],height[right])
a=w*h
max = Math.max(max, area);
if (height[left] < height[right]){
left++
}
else{
right--
}
}
Subscribe to my newsletter
Read articles from Ajay A directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
