MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / triplet_sum

Function triplet_sum

rust/Two Pointers/triplet_sum.rs:1–27  ·  view source on GitHub ↗
(mut nums: Vec<i32>)

Source from the content-addressed store, hash-verified

1fn triplet_sum(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
2 let mut triplets: Vec<Vec<i32>> = vec![];
3 nums.sort();
4 let len = nums.len();
5
6 for i in 0..len {
7 // Optimization: triplets consisting of only positive numbers
8 // will never sum to 0.
9 if nums[i] > 0 {
10 break;
11 }
12
13 // To avoid duplicate triplets, skip 'a' if it's the same as
14 // the previous number.
15 if i > 0 && nums[i] == nums[i - 1] {
16 continue;
17 }
18
19 // Find all pairs that sum to a target of '-a' (-nums[i]).
20 let pairs = pair_sum_sorted_all_pairs(&nums, i + 1, -nums[i]);
21 for pair in pairs {
22 triplets.push(vec![nums[i], pair[0], pair[1]]);
23 }
24 }
25
26 triplets
27}
28
29fn pair_sum_sorted_all_pairs(nums: &Vec<i32>, start: usize, target: i32) -> Vec<Vec<i32>> {
30 let mut pairs = Vec::new();

Callers

nothing calls this directly

Calls 1

Tested by

no test coverage detected