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

Function tripletSum

cpp/Two Pointers/triplet_sum.cpp:7–28  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5std::vector<std::vector<int>> pairSumSortedAllPairs(std::vector<int>& nums, int start, int target);
6
7std::vector<std::vector<int>> tripletSum(std::vector<int>& nums) {
8 std::vector<std::vector<int>> triplets;
9 std::sort(nums.begin(), nums.end());
10 for (int i = 0; i < nums.size(); i++) {
11 // Optimization: triplets consisting of only positive numbers
12 // will never sum to 0.
13 if (nums[i] > 0) {
14 break;
15 }
16 // To avoid duplicate triplets, skip 'a' if it's the same as
17 // the previous number.
18 if (i > 0 && nums[i] == nums[i - 1]) {
19 continue;
20 }
21 // Find all pairs that sum to a target of '-a' (-nums[i]).
22 std::vector<std::vector<int>> pairs = pairSumSortedAllPairs(nums, i + 1, -nums[i]);
23 for (auto& pair : pairs) {
24 triplets.push_back({nums[i], pair[0], pair[1]});
25 }
26 }
27 return triplets;
28}
29
30std::vector<std::vector<int>> pairSumSortedAllPairs(std::vector<int>& nums, int start, int target) {
31 std::vector<std::vector<int>> pairs;

Callers

nothing calls this directly

Calls 1

pairSumSortedAllPairsFunction · 0.70

Tested by

no test coverage detected