Two Pointers Technique/Approach

Two pointers

Welcome learners. Here in this Two Pointers Technique/Approach you will know about what is two pointer technique. And you will also learn how to implement it. You can refer to my previous posts binary search and DSA if needed.

Two pointers Technique

Two pointer technique maintains two pointers to proceed with the algorithm. You can implement two pointer technique in two ways. One is to use one pointer at beginning and the other at end. These two pointers move towards each other. The other way is to move two pointers with different speeds. One moves fast and the other slow. But there are different scenarios to use two pointers. You can use these two ways in different ways of solving problems. You can apply this technique for the suitable solution.

Two pointer Technique is a way of implementing your algorithms. It is very easy to implement and also works effectively.

Two pointer implementation

Pair with given sum

You are given an array and a number. You need to find a pair of numbers in the given array whose sum is equal to the given number.

Two pointer Approach
  1. Sort the given Array
  2. Initialize two pointers. One at the beginning and one at the end.
  3. compare the sum of elements at pointers with given no.
  4. If the sum is less than given no., move the left pointer.
  5. And if the sum is greater than the given no., move the right pointer
  6. If sum equals to the given no., return True.
Visualization

let us consider an example array as 5 4 3 8 9 6 1
given number is 12
so you need to find pair with sum 11
after sorting the array: 1 3 4 5 6 8 9
initially your pointers are at 1 and 9
1 3 4 5 6 8 9 sum= 10 and 10<11
move left pointer
1 3 4 5 6 8 9 sum= 12 and 12>11
move right pointer
1 3 4 5 6 8 9 sum= 11 and 11=11
so return True. Because You found the required pair.

Implementation in python

on implementation for given problem

Two pointers Technique Practice

Two pointers Technique practice problems.