Leetcode 3Sum problem solution in C#

Feb 18, 2023

In the Leetcode 3Sum problem solution in C# programming Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Leetcode 3Sum problem solution in C# programming

``````public class Solution {
public IList<IList<int>> ThreeSum(int[] nums)
{
Array.Sort(nums);
var res = new List<IList<int>>();
for (int i = 0; i < nums.Length && nums[i] <= 0; ++i)
{
if (i == 0 || nums[i - 1] != nums[i])
{
TwoSum(nums, i, res);
}
}
return res;
}

private void TwoSum(int[] nums, int i, List<IList<int>> res)
{
var a = i + 1;
var b = nums.Length - 1;
while (a < b)
{
var sum = nums[i] + nums[a] + nums[b];
if (sum < 0 || (a > i + 1 && nums[a] == nums[a - 1]))
++a;
else if (sum > 0 || (b < nums.Length - 1 && nums[b] == nums[b + 1]))
--b;
else
{
var item = new List<int>();
}
}
}
}``````

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.