Running through an example
One usage is while searching for pairs in an array. Let us consider a practical example: assume that you have a sorted array arr
.
You're tasked with figuring out the pair of elements where arr[p]
+ arr[q]
add up to a certain number. (To try this problem out, check the Two Sum and Sorted Two Sum problems here.)
The brute force solution is to compare each element with every other number, but that's a time complexity of O(n^2)
. We can do better!
So let's optimize. You need to identify the indices pointer_one
and pointer_two
whose values sum to the integer target
.
Let's initialize two variables, pointer_one
and pointer_two
, and consider them as our two pointers.
1const pointerOne = 0;
2const pointerTwo = arr.length - 1;
These snippets declare two pointers, typically used to traverse an array or a similar data structure. In C++, the calculation of pointerTwo
assumes that arr
is a statically defined array. If it were a dynamic array or a standard container like std::vector
, you would use arr.size()
instead.