codekofi
← All problems

Problem 133

Medium

1 · Worked examples

0 / 4

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 4 outputs correctly.

The accepted solution

1vector<vector<int>> solution(vector<int> nums) {
2
3 sort(nums.begin(), nums.end());
4
5 int n = nums.size();
6 vector<vector<int>> ans;
7
8 for (int i = 0; i < n; i++) {
9
10 if (i > 0 && nums[i] == nums[i - 1]) {
11 continue;
12 }
13
14 int lo = i + 1;
15 int hi = n - 1;
16
17 while (lo < hi) {
18
19 int sum = nums[i] + nums[lo] + nums[hi];
20
21 if (sum < 0) {
22 lo++;
23
24 } else if (sum > 0) {
25 hi--;
26
27 } else {
28
29 ans.push_back({nums[i], nums[lo], nums[hi]});
30 lo++;
31
32 while (lo < hi && nums[lo] == nums[lo - 1]) {
33 lo++;
34 }
35 }
36 }
37 }
38
39 return ans;
40}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.