CP_SESSIONS

Two Pointers

View on GitHub

Two Pointers and Sliding Window Techniques

Two Pointers

Two pointers is a technique that is often used in competitive programming to solve problems that involve iterating over two or more points in an array or a sequence. The basic idea behind this technique is to use two pointers, one at the start and another at the end of the sequence, and move them towards each other until they meet.

One common problem that can be solved using the two pointers technique is finding a pair of integers in an array that add up to a given target value. To solve this problem, we can first sort the array and then use two pointers to scan the array from both ends. If the sum of the two elements pointed by the two pointers is less than the target value, we move the left pointer to the right. If the sum is greater than the target value, we move the right pointer to the left. If the sum is equal to the target value, we have found a pair of integers that add up to the target value.

Sliding Window

Sliding window is another technique that is often used in competitive programming to solve problems that involve finding a subarray or a substring that satisfies certain conditions. The basic idea behind this technique is to use a window that slides over the sequence, and update the window as we go.

One common problem that can be solved using the sliding window technique is finding the maximum sum of a subarray of size k in an array. To solve this problem, we can first compute the sum of the first k elements of the array. Then we slide the window by one element at a time and update the sum by subtracting the first element of the window and adding the next element of the array. We keep track of the maximum sum we have seen so far, and return it as the answer.

These two techniques are very useful in competitive programming, and can be used to solve a wide range of problems efficiently. By mastering these techniques, you can become a more confident and skilled programmer.

And we are here to learn them in practice and get benefit of using them.
Enjoy Two Pointers and Sliding Window!

My Session @ ICPC SCU

Useful Materials

I highly recommend starting with CodeForces EDU section

Reading Materials

Video Materials

Practice Problems