Patterns (two pointers, windows, prefix sums) · O(n)
Two pointers
Pair sum from both ends of a sorted array, and in-place dedupe with read and write pointers.
The full explanation, derivation and practice are in the lesson Two pointers: opposite ends and read/write.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
namespace Bekadan.Dsa.Examples.ArrayPatterns;
/// <summary>
/// The two-pointer technique on an array sorted in ascending order.
/// Both methods run in O(n) time and O(1) extra space; neither checks that
/// the input is sorted.
/// </summary>
public static class TwoPointers
{
/// <summary>
/// Opposite ends: returns indices (i, j), i < j, with
/// values[i] + values[j] == target, or (-1, -1). The sum is computed in
/// <see cref="long"/>: two ints near int.MaxValue would overflow an int.
/// </summary>
public static (int Left, int Right) PairWithSum(ReadOnlySpan<int> values, long target)
{
int left = 0, right = values.Length - 1;
while (left < right)
{
long sum = (long)values[left] + values[right];
if (sum == target)
return (left, right);
if (sum < target)
left++; // values[left] is too small even with the largest partner left
else
right--; // values[right] is too large even with the smallest partner left
}
return (-1, -1);
}
/// <summary>
/// Same direction: removes duplicates in place and returns the new length k.
/// values[0..k) then holds each distinct value once, in order; the slots
/// after it keep leftover values.
/// </summary>
public static int RemoveDuplicates(Span<int> values)
{
if (values.Length == 0) return 0;
int write = 1; // values[0..write) are distinct
for (int read = 1; read < values.Length; read++)
{
if (values[read] != values[write - 1])
{
values[write] = values[read];
write++;
}
}
return write;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/ArrayPatterns/TwoPointers.cs
"""The two-pointer technique on a list sorted in ascending order.
Both functions run in O(n) time and O(1) extra space. Neither checks that the
input is sorted. Python ints never overflow, so sums need no widening.
"""
from collections.abc import MutableSequence, Sequence
def pair_with_sum(values: Sequence[int], target: int) -> tuple[int, int]:
"""Opposite ends: indices (i, j), i < j, with values[i] + values[j] == target, or (-1, -1)."""
left, right = 0, len(values) - 1
while left < right:
total = values[left] + values[right]
if total == target:
return left, right
if total < target:
left += 1 # values[left] is too small even with the largest partner left
else:
right -= 1 # values[right] is too large even with the smallest partner left
return -1, -1
def remove_duplicates(values: MutableSequence[int]) -> int:
"""Same direction: remove duplicates in place and return the new length k.
values[:k] then holds each distinct value once, in order; the slots after
it keep leftover values (the list is not shortened).
"""
if not values:
return 0
write = 1 # values[:write] are distinct
for read in range(1, len(values)):
if values[read] != values[write - 1]:
values[write] = values[read]
write += 1
return write
Tested on CPython 3.14.0 · examples/python/dsa_examples/two_pointers.py
package dev.bekadan.dsa.patterns;
/**
* The two-pointer technique on an array sorted in ascending order. Both
* methods run in O(n) time and O(1) extra space; neither checks that the input
* is sorted.
*/
public final class TwoPointers {
private TwoPointers() {
}
/**
* Opposite ends: returns {i, j}, i < j, with values[i] + values[j] == target,
* or {-1, -1}. The sum is computed in {@code long}: two ints near
* Integer.MAX_VALUE would overflow an int.
*/
public static int[] pairWithSum(int[] values, long target) {
int left = 0, right = values.length - 1;
while (left < right) {
long sum = (long) values[left] + values[right];
if (sum == target) {
return new int[] {left, right};
}
if (sum < target) {
left++; // values[left] is too small even with the largest partner left
} else {
right--; // values[right] is too large even with the smallest partner left
}
}
return new int[] {-1, -1};
}
/**
* Same direction: removes duplicates in place and returns the new length k.
* values[0..k) then holds each distinct value once, in order; the slots
* after it keep leftover values.
*/
public static int removeDuplicates(int[] values) {
if (values.length == 0) {
return 0;
}
int write = 1; // values[0..write) are distinct
for (int read = 1; read < values.length; read++) {
if (values[read] != values[write - 1]) {
values[write] = values[read];
write++;
}
}
return write;
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/patterns/TwoPointers.java
#pragma once
#include <cstddef>
#include <cstdint>
#include <span>
#include <utility>
namespace bekadan::dsa {
// The two-pointer technique on a span sorted in ascending order. Both functions
// run in O(n) time and O(1) extra space; neither checks that the input is sorted.
// Opposite ends: indices {i, j}, i < j, with values[i] + values[j] == target, or
// {-1, -1}. The sum is computed in std::int64_t: two ints near INT_MAX would
// overflow an int, which is undefined behaviour in C++.
// Signed indices: with right = size - 1, an empty span must give right = -1.
inline std::pair<std::ptrdiff_t, std::ptrdiff_t> pair_with_sum(std::span<const int> values, std::int64_t target) {
std::ptrdiff_t left = 0, right = std::ssize(values) - 1;
while (left < right) {
const std::int64_t sum = std::int64_t{values[left]} + values[right];
if (sum == target) {
return {left, right};
}
if (sum < target) {
++left; // values[left] is too small even with the largest partner left
} else {
--right; // values[right] is too large even with the smallest partner left
}
}
return {-1, -1};
}
// Same direction: removes duplicates in place and returns the new length k.
// values[0, k) then holds each distinct value once, in order (what std::unique
// does); the slots after it keep leftover values.
inline std::size_t remove_duplicates(std::span<int> values) {
if (values.empty()) return 0;
std::size_t write = 1; // values[0, write) are distinct
for (std::size_t read = 1; read < values.size(); ++read) {
if (values[read] != values[write - 1]) {
values[write] = values[read];
++write;
}
}
return write;
}
} // namespace bekadan::dsa
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/two_pointers.hpp