Shows Time limit exceed in 3Sum leetcode problem if i write it in function but it didn't show TLE without function

This code shows TLE.

vector<vector<int>> twoSum(vector<int>& nums ,int index,int target,vector<vector<int>>& res){

    int left = index;
    int right = nums.size()-1;
    
    while(left < right){
        
        
        int sum = nums[left] + nums[right];
        if(sum < target){
            left++;
        }
        else if(sum > target){
            right--;
        }
        else{
            res.push_back({-target,nums[left],nums[right]});
            while(left < right && res.back()[1] == nums[left]) left++;
            while(left < right && res.back()[2] == nums[right]) right--;
        }
    }
    return res;
}



 vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> res;
    sort(nums.begin(),nums.end());
    for(int i=0 ; i < nums.size() - 2; ++i){
        if(i > 0 && nums[i-1] == nums[i]) continue;
        res = twoSum(nums,i+1,-nums[i],res);
    }
     
    return res;
    
 }

This code not shows TLE.

vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> res;
    sort(nums.begin(),nums.end());
    for(int i=0 ; i < nums.size() - 2; ++i){
        if(i > 0 && nums[i-1] == nums[i]) continue;
        int left = i + 1;
        int right = nums.size()-1;
        int target = -nums[i];

        while(left < right){
            int sum = nums[left] + nums[right];
            if(sum < target){
                left++;
            }
            else if(sum > target){
                right--;
            }
            else{
                res.push_back({-target,nums[left],nums[right]});
                while(left < right && res.back()[1] == nums[left]) left++;
                while(left < right && res.back()[2] == nums[right]) right--;
            }
        }
    }

    return res;

}

why ??

hi @khushmanglani31217_7de9bf16f9c8f286 u r returning res and copying back to res in main function again and again thats why
try this – https://ide.codingblocks.com/s/667656

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.