PrevNext

Resources

Resources
CPH

solutions to the problems above

IUSACO

above + mention of max subarray sum

CF EDU

video explanation of two pointers

Two Pointers

The Two Pointers method iterates two pointers across an array to track indices satisfying some condition. There are two common variations:

  1. Two pointers starting at different ends of the array and moving towards each other.
  2. Two pointers moving in the same direction at different speeds. This variation is known as the Sliding Window algorithm.

Sum of Two Values

Focus Problem – try your best to solve this problem before continuing!

View Internal Solution

Solution - Sum of Two Values

The "Opposite Ends" method allows us to find the target pair in linear time if the array is sorted. Instead of checking every possible pair (which would take O(N2)\mathcal{O}(N^2) time), we use the sorted property to narrow down the search space in a single pass.

We want to find two indices ii and jj such that ai+aj=xa_i + a_j = x.

We can start by sorting the array. Then, we can initialize a left pointer at the beginning of the array (l=0l=0) and a right pointer at the end (r=N1r=N-1).

While l<rl < r:

  1. If a[l]+a[r]==xa[l] + a[r] == x, we have found the target sum.
  2. If a[l]+a[r]<xa[l] + a[r] < x, the sum is too small. To increase the sum, we increment ll.
  3. If a[l]+a[r]>xa[l] + a[r] > x, the sum is too large. To decrease the sum, we decrement rr.

Since the array is sorted, moving the left pointer to the right will never decrease the sum, and moving the right pointer to the left will never increase the sum.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N \log N)

C++

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main() {
int n, x;
cin >> n >> x;

Java

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());

Python

n, x = map(int, input().split())
nums = [(int(val), i) for i, val in enumerate(input().split())]
nums.sort()
l = 0
r = n - 1
while l < r:
sum = nums[l][0] + nums[r][0]
if sum == x:

Sliding Window

The Sliding Window method is a variation of the two pointers technique where two pointers move in the same direction to maintain a specific range or "window" of elements. While standard two pointers often move towards each other, the sliding window technique is used to find a contiguous subarray that satisfies a condition.

Focus Problem – try your best to solve this problem before continuing!

Solution - Books

We want to find the longest contiguous segment of books that can be read within tt minutes.

To accomplish this, we can define left\texttt{left} and right\texttt{right} to represent the beginning and end of the segment. Both will start at the beginning of the array. These numbers can be thought of as pointers, hence the name "two pointers."

For every value of left\texttt{left} in increasing order, let's increase right\texttt{right} until the total time for the segment is maximized while being less than or equal to tt.

ans\texttt{ans} will store the maximum value of rightleft+1\texttt{right} - \texttt{left}+1 (segment size) that we have encountered so far.

After incrementing left\texttt{left} by one, the time used decreases, hence the right pointer never has to move leftwards. Thus:

Since both pointers will move at most NN times, the overall time complexity is O(N)\mathcal{O}(N).

As an example, consider the first case in the sample inputs:

Left Pointer
arr[i]\texttt{arr}[i] 3 1 2 1
Right Pointer

We can move the right pointer to index 11:

Left Pointer
arr[i]\texttt{arr}[i] 3 1 2 1
Right Pointer

The sum of the values in this range is 44, and there are 22 values. So, the current maximum segment length is ans=2\texttt{ans}=2. By incrementing the left pointer by 11, we can subtract 33 from the sum of values to get 11. The array then looks like:

Left Pointer
arr[i]\texttt{arr}[i] 3 1 2 1
Right Pointer

Now, we can move the right pointer to the end. This makes the sum of values 1+2+1=41+2+1=4 and the length of the segment equal to 33. So, ans\texttt{ans} is now 33.

Left Pointer
arr[i]\texttt{arr}[i] 3 1 2 1
Right Pointer

Since the right pointer has reached the end of the array, we are done at this point. This leaves us with ans=3\texttt{ans}=3.

Here's an animation of the above example:

Implementation

Time Complexity: O(N)\mathcal{O}(N)

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, T;
cin >> N >> T;
vector<int> A(N);

Java

import java.io.*;
import java.util.*;
public class Books {
public static void main(String[] args) {
Kattio io = new Kattio();
int N = io.nextInt();
int T = io.nextInt();
int[] A = new int[N];

Python

N, T = map(int, input().split())
A = list(map(int, input().split()))
r = -1
window_sum = 0 # sum of A[l ... r inclusive]
ans = 0
for l in range(N):
while r + 1 < N and window_sum + A[r + 1] <= T:
r += 1
window_sum += A[r]
ans = max(ans, r - l + 1)
window_sum -= A[l]
print(ans)

Problems

StatusSourceProblem NameDifficultyTags
CSESEasy
Show TagsSliding Window
CSESEasy
Show Tags2P, Sorting
SilverEasy
Show Tags2P, Sorting
CFEasy
Show Tags2P, Binary Search
CFEasy
Show Tags2P
CFNormal
Show Tags2P, Sliding Window, Sorting
SilverNormal
Show Tags2P, Sorting
SilverNormal
Show Tags2P, Sorting
CFNormal
Show Tags2P
SilverNormal
Show TagsBinary Search, Prefix Sum, Two Pointers

Quiz

What is the two pointers algorithm?

Question 1 of 3

Module Progress:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

PrevNext