Two Pointers — [Notes]

Tarun Jain
3 min readJun 19, 2022

--

Refer this link for all DSA articles

· Important points
· Types of Two Pointers
· Sample Problem
· Problems
· 3.1 Collision
· 3.2 Forward
· 3.3 Parallel
· References

Why use two-pointer

  • By reducing nested loops, the two-pointers strategy reduces time complexity.
  • The fundamental requirement for employing the two-pointers technique to solve a problem effectively is that each pointer travels independently in a single direction.
  • They can travel in opposite directions, but the direction should not change.

The two-pointer technique can be expanded to more sophisticated techniques such as sliding windows and dynamic programming.

🌟 Important points

  1. The physical significance of the pointer
    → range
    → pair (i, j)
  2. How to initialize the pointer
  3. How to change the pointer / move the pointer
  4. When to stop

Types of Two Pointers

Sample Problem

Given a sorted (in ascending order) integer array nums of n elements and a target value, find if there exists any pair of elements (nums[i], nums[j], i!=j) such that their sum is equal to target.

// Two pointers, O(n)
public boolean isPairSum(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return false;
}
int start = 0;
int end = nums.length - 1;

while (start < end) {
int sum = nums[start] + nums[end];
if (sum == target) {
return true; // pair exists
} else if (sum < target) {
start++; // move start forward to get larger value
} else {
end--; // move end backward to get smaller value
}
}

// not found
return false;
}

Problems

3.1 Collision

Sub type: Two Sum

Sub type: Partition

3.2 Forward

Sub type: Window

Sub type: fast and slow

3.3 Parallel

Two arrays, one pointer each.

Others- Todo

--

--