Combine sorting and two pointers to find triples without duplicates.
For each first value, every pair that uses a value outside left..right has been recorded or ruled out, and no triple has been recorded twice.
Use it when you need three values with a total, closest to a total, or under a limit, and the order of the values does not matter. Signal words: three values, add up to, every distinct triple, closest to, how many triples.
Start: sort a copy. For each first value at i, put left at i + 1 and right at the last index.
Step: add the three values. Too small: move left. Too large: move right. Equal: record the triple, and move both pointers past equal values.
Stop: when left meets right. Then move to the next first value, skipping a repeated one.
It does not need extra memory for the search. A hash set can also find triples, but it needs more memory and care with repeats.
Cost: n first values times at most n pointer moves: O(n^2) time, and O(n) for the sorted copy.
def triples_to_target(values, target):
# [1] Sort a copy, so the pair search can move its pointers by size and equal values sit together.
ordered = sorted(values)
n = len(ordered)
found = []
for i in range(n - 2):
# [2] Skip a first value equal to the one before it: it would only repeat the same triples.
if i > 0 and ordered[i] == ordered[i - 1]:
continue
# [3] Search the values after i from both ends for the pair that completes the target.
left = i + 1
right = n - 1
while left < right:
total = ordered[i] + ordered[left] + ordered[right]
# [4] Too small: every pair with this left and a smaller right is smaller still, so rule out left.
if total < target:
left += 1
# [5] Too large: every pair with this right and a larger left is larger still, so rule out right.
elif total > target:
right -= 1
else:
# [6] Equal: record the triple, then step both pointers past their equal values so it is not recorded twice.
found.append([ordered[i], ordered[left], ordered[right]])
left += 1
right -= 1
while left < right and ordered[left] == ordered[left - 1]:
left += 1
while left < right and ordered[right] == ordered[right + 1]:
right -= 1
# [7] Report the triples, found in order.
return foundpublic int[][] triplesToTarget(int[] values, int target) {
// [1] Sort a copy, so the pair search can move its pointers by size and equal values sit together.
int[] ordered = values.clone();
java.util.Arrays.sort(ordered);
int n = ordered.length;
java.util.List<int[]> found = new java.util.ArrayList<>();
for (int i = 0; i < n - 2; i++) {
// [2] Skip a first value equal to the one before it: it would only repeat the same triples.
if (i > 0 && ordered[i] == ordered[i - 1]) {
continue;
}
// [3] Search the values after i from both ends for the pair that completes the target.
int left = i + 1;
int right = n - 1;
while (left < right) {
int total = ordered[i] + ordered[left] + ordered[right];
// [4] Too small: every pair with this left and a smaller right is smaller still, so rule out left.
if (total < target) {
left++;
}
// [5] Too large: every pair with this right and a larger left is larger still, so rule out right.
else if (total > target) {
right--;
} else {
// [6] Equal: record the triple, then step both pointers past their equal values so it is not recorded twice.
found.add(new int[] {ordered[i], ordered[left], ordered[right]});
left++;
right--;
while (left < right && ordered[left] == ordered[left - 1]) {
left++;
}
while (left < right && ordered[right] == ordered[right + 1]) {
right--;
}
}
}
}
// [7] Report the triples, found in order.
return found.toArray(new int[0][]);
}vector<vector<int>> triplesToTarget(vector<int>& values, int target) {
// [1] Sort a copy, so the pair search can move its pointers by size and equal values sit together.
vector<int> ordered(values);
sort(ordered.begin(), ordered.end());
int n = (int) ordered.size();
vector<vector<int>> found;
for (int i = 0; i < n - 2; i++) {
// [2] Skip a first value equal to the one before it: it would only repeat the same triples.
if (i > 0 && ordered[i] == ordered[i - 1]) {
continue;
}
// [3] Search the values after i from both ends for the pair that completes the target.
int left = i + 1;
int right = n - 1;
while (left < right) {
int total = ordered[i] + ordered[left] + ordered[right];
// [4] Too small: every pair with this left and a smaller right is smaller still, so rule out left.
if (total < target) {
left++;
}
// [5] Too large: every pair with this right and a larger left is larger still, so rule out right.
else if (total > target) {
right--;
} else {
// [6] Equal: record the triple, then step both pointers past their equal values so it is not recorded twice.
found.push_back({ordered[i], ordered[left], ordered[right]});
left++;
right--;
while (left < right && ordered[left] == ordered[left - 1]) {
left++;
}
while (left < right && ordered[right] == ordered[right + 1]) {
right--;
}
}
}
}
// [7] Report the triples, found in order.
return found;
}function triplesToTarget(values, target) {
// [1] Sort a copy, so the pair search can move its pointers by size and equal values sit together.
const ordered = [...values].sort((a, b) => a - b);
const n = ordered.length;
const found = [];
for (let i = 0; i < n - 2; i++) {
// [2] Skip a first value equal to the one before it: it would only repeat the same triples.
if (i > 0 && ordered[i] === ordered[i - 1]) {
continue;
}
// [3] Search the values after i from both ends for the pair that completes the target.
let left = i + 1;
let right = n - 1;
while (left < right) {
const total = ordered[i] + ordered[left] + ordered[right];
// [4] Too small: every pair with this left and a smaller right is smaller still, so rule out left.
if (total < target) {
left++;
}
// [5] Too large: every pair with this right and a larger left is larger still, so rule out right.
else if (total > target) {
right--;
} else {
// [6] Equal: record the triple, then step both pointers past their equal values so it is not recorded twice.
found.push([ordered[i], ordered[left], ordered[right]]);
left++;
right--;
while (left < right && ordered[left] === ordered[left - 1]) {
left++;
}
while (left < right && ordered[right] === ordered[right + 1]) {
right--;
}
}
}
}
// [7] Report the triples, found in order.
return found;
}def count_under(values, limit):
# [1] Sort a copy: reordering the values does not change how many triples fit.
ordered = sorted(values)
n = len(ordered)
count = 0
for i in range(n - 2):
# [2] Fix the first value at i and search the values after it from both ends.
left = i + 1
right = n - 1
while left < right:
# [3] Under the limit: left fits with every value from left + 1 to right, so count them all and rule out left.
if ordered[i] + ordered[left] + ordered[right] < limit:
count += right - left
left += 1
# [4] Not under the limit: this right is too large for every left, so rule out right.
else:
right -= 1
# [5] Report the count.
return countpublic long countUnder(int[] values, long limit) {
// [1] Sort a copy: reordering the values does not change how many triples fit.
int[] ordered = values.clone();
java.util.Arrays.sort(ordered);
int n = ordered.length;
long count = 0; // up to about n^3 / 6 triples, beyond a 32-bit int
for (int i = 0; i < n - 2; i++) {
// [2] Fix the first value at i and search the values after it from both ends.
int left = i + 1;
int right = n - 1;
while (left < right) {
// [3] Under the limit: left fits with every value from left + 1 to right, so count them all and rule out left.
if ((long) ordered[i] + ordered[left] + ordered[right] < limit) {
count += right - left;
left++;
}
// [4] Not under the limit: this right is too large for every left, so rule out right.
else {
right--;
}
}
}
// [5] Report the count.
return count;
}long long countUnder(vector<int>& values, long long limit) {
// [1] Sort a copy: reordering the values does not change how many triples fit.
vector<int> ordered(values);
sort(ordered.begin(), ordered.end());
int n = (int) ordered.size();
long long count = 0; // up to about n^3 / 6 triples, beyond a 32-bit int
for (int i = 0; i < n - 2; i++) {
// [2] Fix the first value at i and search the values after it from both ends.
int left = i + 1;
int right = n - 1;
while (left < right) {
// [3] Under the limit: left fits with every value from left + 1 to right, so count them all and rule out left.
if ((long long) ordered[i] + ordered[left] + ordered[right] < limit) {
count += right - left;
left++;
}
// [4] Not under the limit: this right is too large for every left, so rule out right.
else {
right--;
}
}
}
// [5] Report the count.
return count;
}function countUnder(values, limit) {
// [1] Sort a copy: reordering the values does not change how many triples fit.
const ordered = [...values].sort((a, b) => a - b);
const n = ordered.length;
let count = 0; // up to about n^3 / 6 triples, exact in a JavaScript number
for (let i = 0; i < n - 2; i++) {
// [2] Fix the first value at i and search the values after it from both ends.
let left = i + 1;
let right = n - 1;
while (left < right) {
// [3] Under the limit: left fits with every value from left + 1 to right, so count them all and rule out left.
if (ordered[i] + ordered[left] + ordered[right] < limit) {
count += right - left;
left++;
}
// [4] Not under the limit: this right is too large for every left, so rule out right.
else {
right--;
}
}
}
// [5] Report the count.
return count;
}if ordered[i] == ordered[i + 1]: # bug: looks forward
continuefound.append([ordered[i], ordered[left], ordered[right]])
left += 1
right -= 1 # bug: an equal value may match againA tempting shortcut is to run the pointers on the raw list, because it saves the sort.
Your team lead asks for blocks of any size: choose as many tracks as you like, with a total of exactly 12 minutes. For [3, 5, 4, 2, 6, 3, 7, 1], that includes 5 + 7 and 1 + 2 + 3 + 6.
systemdesignmastery.dev/dsa/cheatsheets/three-sum