I’m trying to solve the three sum problem. I’ve come up with a O((n^2)*3log3) solution and O(n) space yet I’m getting a TLE. Can anyone explain me why I’m getting TLE?
Problem Link: https://leetcode.com/problems/3sum/
My approach:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
unordered_map<int, stack<int>> m;
unordered_map<int, bool> v;
int n = nums.size();
vector<vector<int>> ans;
int target = 0;
for(int i = 0; i < n; i++)
m[nums[i]].push(i);
for(int i = 0; i < n; i++)
{
int a = m[nums[i]].top();
m[nums[i]].pop();
for(int j = i + 1; j < n; j++)
{
int b = m[nums[j]].top();
m[nums[j]].pop();
if(!m[target - nums[a] - nums[b]].empty())
{
vector<int> d = {nums[a], nums[b], target - nums[a] - nums[b]};
sort(d.begin(), d.end());
string y = "";
for(int k = 0; k < 3; k++)
y = y + to_string(d[k]) + " ";
if(v.find(y) == v.end())
{
ans.push_back(d);
v[y] = true;
}
}
m[nums[j]].push(b);
}
//m[nums[i]].push(a);
}
return ans;
}
};