0

I am trying to solve the question at:

Problem statement

Given the array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0. Find all unique triplets in the array which gives the sum of zero.

Given array nums = [-1, 0, 1, 2, -1, -4]

A solution set is:

[
  [-1, 0, 1],

  [-1, -1, 2]
]

I am trying to use a HashSet approach instead of a Head and Tail approach, but I am unable to detect duplicate values before adding them to the List of Lists using a HashSet.

public class Solution
{
    public IList < IList < int >> ThreeSum(int[] nums)
    {
        IList < IList < int >> parentList = new List < IList < int >> ();
        IList < int > childList = new List < int > ();
        HashSet < IList < int >> hashSetOfLists = new HashSet < IList < int >> ();
        if (nums.Length > 0)
        {
            for (int i = 0; i < nums.Length; i++)
            {
                int sum = -1 * nums[i];
                HashSet < int > tracker = new HashSet < int > ();
                for (int j = i + 1; j < nums.Length; j++)
                {
                    if (!tracker.Contains(sum - nums[j]))
                        tracker.Add(nums[j]);
                    else
                    {
                        childList.Add( - 1 * sum);
                        childList.Add(sum - nums[j]);
                        childList.Add(nums[j]);
                        if (!hashSetOfLists.Contains(childList)) //this condition is not working as expected to detect duplicate values
                        {
                            parentList.Add(childList);
                            hashSetOfLists.Add(childList);
                        }
                        childList = new List < int > ();
                    }
                }
            }
        }
        return parentList;
    }
}
Community
  • 1
  • 1

0 Answers0