The approach I thought of and was recomended was to try and find a O(n^2) alternative, since this is one of those problems that is not possoible to do in better time. The way we can do this is to recognize that we are looking for a sum of three numbers (one from each row) and that can be either 0 or less than 0 or more than 0. If we simply pick each element in derial order that degenerates into cubic complexity. But what if we sorted each row. Let’s take an example:
classSolution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; if (nums.size() < 3) return res; sort(nums.begin(), nums.end(), [](int a, int b) { return a < b;}); for (int i = 0; i < nums.size() - 2; i++) { // skip duplicates of nums[i] if (i > 0 && nums[i] == nums[i-1]) { continue; } int j = i + 1; int k = nums.size() - 1; while (j < k) { int sum = nums[i]+nums[j]+nums[k]; if (sum == 0) { res.push_back({nums[i], nums[j], nums[k]}); // skip all duplicates for nums[j] and nums[k] while (j < k && nums[k-1] == nums[k]) k--; while (j < k && nums[j+1] == nums[j]) j++;
j++; k--; } if (nums[i]+nums[j+1]+nums[k] > sum) {
k = k - 1;
} else { j = j + 1; } } } return res; } };
This has a side effect and fails the following test case
classSolution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; if (nums.size() < 3) return res; sort(nums.begin(), nums.end(), [](int a, int b) { return a < b;}); for (int i = 0; i < nums.size() - 2; i++) { // skip duplicates of nums[i] if (i > 0 && nums[i] == nums[i-1]) { continue; } int j = i + 1; int k = nums.size() - 1; while (j < k) { int sum = nums[i]+nums[j]+nums[k]; if (sum == 0) { res.push_back({nums[i], nums[j], nums[k]}); // skip all duplicates for nums[j] and nums[k] while (j < k && nums[k-1] == nums[k]) k--; while (j < k && nums[j+1] == nums[j]) j++; j++; k--; } elseif (nums[i]+nums[j+1]+nums[k] > sum) { k--; } else { j++; } } } return res; } };
The issue is that since we are sorting in ascending order and we have the check to skip duplicates of nums[i], we end up skipping all the -1’s! We need to modify that check a bit.