1. Two pointers technique#
When solving problems with sorted arrays that require fulfilling certain constraints with a specific set of elements, the two pointers technique becomes quite handy. The set of elements could be a pair, a triplet, or even a subarray.
Take a look at this example problem:
Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target.
To solve this problem, a naive approach is to use two nested loops and check all the possible pairs to find the one whose sum is equal to the target value. Each of the nested loops will be running to the full length of the array. Thus, the time complexity of this algorithm is O(N2), where N is the number of elements in the input array.
You could do much better than the above approach using the two pointers technique. Let’s assume that the input array is sorted starting with the first pointer at the beginning and the second pointer at the end.
At every step, you will see if the numbers pointed by the two pointers add up to the target sum. If so, then you return the two values pointed out by them. Otherwise, you will do one of two things:
- If the sum of the two numbers pointed by the two pointers is greater than the target sum, this means that you need a pair with a smaller sum. So, to try more pairs, you can move the second pointer toward the left side of the array.
- If the sum of the two numbers pointed by the two pointers is smaller than the target sum, this means that you need a pair with a larger sum.
So, to try more pairs, you can move the first pointer toward the right side of the array.
The two pointers technique has decreased the time complexity of the approach to O(N). Thus, it is a more efficient approach to finding a pair with the target sum in an array.
2. Sliding windows#
In many problems dealing with an array or linked list, you are asked to find or calculate something among all the subarrays of a given size. A window is a sublist formed over a part of an iterable data structure. It can be used to slide over the data in chunks corresponding to the window size. For example, take a look at this problem:
Given an array, find the average of each subarray of ‘K’ contiguous elements in it.
Let’s understand this problem with an example:
Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5
Here, you are asked to find the average of all subarrays of 5 contiguous elements in the given array. Let’s solve this:
For the first 5 numbers (subarray from index 0-4), the average is:
(1+3+2+6-1)/5 => 2.2
The average of the next 5 numbers (subarray from index 1-5) is:
(3+2+6-1+4)/5 => 2.8
For the next 5 numbers (subarray from index 2-6), the average is:
(2+6-1+4+1)/5 => 2.4
And so on.