2.0 Introduction
Last updated
Last updated
Two pointer approach is an essential part of a programmer’s toolkit, especially in technical interviews. The name does justice in this case, it involves using two pointers to save time and space. (Here, pointers are basically array indexes).
The idea here is to iterate two different parts of the array simultaneously to get the answer faster.
Implementation
There are primarily two ways of implementing the two-pointer technique:
1. One pointer at each end
One pointer starts from beginning and other from the end and they proceed towards each other
Example : In a sorted array, find if a pair exists with a given sum S
Brute Force Approach: We could implement a nested loop finding all possible pairs of elements and adding them.
Time complexity: O(n²)
Efficient Approach
Time Complexity: O(n)
2. Different Paces
Example: Find the middle of a linked list
Brute Force Approach: We can find the length of the entire linked list in one complete iteration and then iterate till half-length again.
Efficient Approach: Using a two-pointer technique allows us to get the result in one complete iteration
How does this technique save space?
There are several situations when a naive implementation of a problem requires additional space thereby increasing the space complexity of the solution. Two-pointer technique often helps to decrease the required space or remove the need for it altogether
Example: Reverse an array
Naive Solution: Using a temporary array and fillings elements in it from the end
Space Complexity: O(n)
Efficient Solution: Moving pointers towards each other from both ends and swapping elements at their positions
Some popular examples of two pointer approach
Pseudo code: Merge two sorted array
Both pointers are moving forward in the same direction and each step of iteration we are moving one pointer forward. Time Complexity = O(n1 + n2) (Think!)
Pseudo code: Partition function in quick sort
Both pointers are moving forward in the same direction with different pace i.e. j is incrementing by 1 after each iteration but i is incrementing if (A[j] < pivot). Time complexity = O(n)
Both pointers start from the beginning but one pointer moves at a faster pace than the other one.