One of the most common approaches to solve many algoritm problems is to apply some type of 2-Pointer approach. The 2-Pointer approach is used to search over a list (or multiple list) in such a way that the time complexity can be minimised. Consider the following problem:
Problem Statement: Given an array of positive integers and a positive target integer, return the minimal length of a contiguous sub-array of which the sum is greater than or equal to the target.
This article visually explains how we can use a two-pointer algorithm with a sliding window to solve this problem with \(O(n)\) time complexity.
One solution to solve this kind of problem is to use the 2-Pointer approach with a sliding window. The diagram below illustrates this solution with the inputs nums = [1,2,2,3,3,2,3,4,1,2] and target = 7.
Using a sliding window ensures that we do not check sub-arrays which we know are larger than the smallest sub-array we have found so far. We can end our search when either the length of the sub-array is equal to two (since the only better solution is if the target is in the array) or we have traversed the whole array.