Implementing Two-Pointer Algorithms for Sequence Problems
A common pattern in two-pointer algorithms involves iterating through a sequence while adjusting a second pointer to maintain a specific condition.
for (int left = 0, right = 0; right < n; right++) {
while (left < right && condition(left, right)) left++;
// Process the current window
}
Finding the Longest Subarray Without Duplicates
Given an integer array of length n, determine the length of the longest contiguous subarray containing no duplicate elemnets.
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX_SIZE = 100010;
int arr[MAX_SIZE];
int frequency[MAX_SIZE];
int main() {
int n;
cin >> n;
for (int idx = 0; idx < n; idx++) {
cin >> arr[idx];
}
int maxLength = 0;
for (int right = 0, left = 0; right < n; right++) {
frequency[arr[right]]++;
while (frequency[arr[right]] > 1 && left < right) {
frequency[arr[left]]--;
left++;
}
maxLength = max(maxLength, right - left + 1);
}
cout << maxLength;
return 0;
}
This approach ensures that for each position right, the window [left, right] represents the longest unique subarray ending at right. The left pointer moves only to eliminate duplicates, maintaining monotonic progression.
Pair Sum in Sorted Arrays
Given two sorted arrays A and B, and a target value x, find indices (i, j) such that A[i] + B[j] = x. The solution is guaranteed to be unique.
#include <iostream>
using namespace std;
const int MAX_LEN = 100010;
long long first[MAX_LEN], second[MAX_LEN];
int main() {
int n, m;
long long target;
cin >> n >> m >> target;
for (int i = 0; i < n; i++) {
cin >> first[i];
}
for (int j = 0; j < m; j++) {
cin >> second[j];
}
int ptrA = 0, ptrB = m - 1;
for (ptrA = 0; ptrA < n; ptrA++) {
while (ptrB >= 0 && first[ptrA] + second[ptrB] > target) {
ptrB--;
}
if (first[ptrA] + second[ptrB] == target) {
break;
}
}
cout << ptrA << " " << ptrB;
return 0;
}
Starting with one pointer at the beginning of the first array and the other at the end of the second, the algorithm adjusts the pointers based on the sum comparison to efficiently locate the target pair.