-
Notifications
You must be signed in to change notification settings - Fork 4
Two Pointer Technique
The two pointer technique is a near necessity in any competitive toolkit. Since there are a lot of ways and situations where this technique can be used, this Wiki will just get you started with the basics.
The name two pointers
does justice in this case, as it is exactly as it sounds. It's the use of two different pointers (usually to keep track of array or string indices) to solve a problem involving said indices with the benefit of saving time and space. Here the term pointer
is used in a general sense, it can be anything that references a value allocated in the computer memory like an index of an array or a pointer to an object.
In many problems involving collections such as arrays or lists, we have to analyze each element of the collection compared to its other elements.
There are many approaches to solving problems like these. For example, we usually start from the first index and iterate through the data structure one or more times depending on how we implement our code.
Sometimes we may even have to create an additional data structure depending on the problem's requirements. This approach might give us the correct result, but it likely won't give us the most space and time-efficient result.
Here is just one of the many ways you could use the two-pointer technique to optimize your solution.
Another great application of this practice is the Window Sliding Technique.
As an exercise to get a better understanding of this concept you can try reversing a string using this technique.