Leetcode 4Sum problem solution in C# programming

In the Leetcode 4Sum problem solution in C# programming Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.

Leetcode 4Sum problem solution in C# programming

public class Solution {
    public IList<IList<int>> FourSum(int[] a, int target) {
        int n = a.Length;
        Array.Sort(a);
        Dictionary<int, IList<int[]>> map = new Dictionary<int, IList<int[]>>();
        
        // compute possible two sums and store them in a hashtable
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                if(j>i+1 && a[j-1] == a[j]) continue; // skip duplicates
                int sum = a[i]+a[j];
                if(map.ContainsKey(sum))
                {
                    map[sum].Add(new int[]{i,j});
                }
                else
                {
                    IList<int[]> pair = new List<int[]>();
                    pair.Add(new int[]{i,j});
                    map.Add(sum, pair);
                }
            }
        }
        
        FourSumResult result = new FourSumResult();
        foreach(int key in map.Keys)
        {
            foreach(int[] fp in map[key])
            {
                if(map.ContainsKey(target-key))
                {
                    foreach(int[] sp in map[target-key])
                    {
                        if(fp[0] != sp[0] && fp[1] != sp[0] && fp[0] != sp[1] && fp[1] != sp[1])
                        {
                            result.Insert(new int[]{a[fp[0]],a[fp[1]],a[sp[0]],a[sp[1]]});
                        }
                    }
                }
            }
        }
        
        return result.uPairs;
    }
}

// This class makes sure of unique quadruplets
class FourSumResult
{
    public IList<IList<int>> uPairs;
    public FourSumResult()
    {
        uPairs = new List<IList<int>>();
    }
    public void Insert(int[] q)
    {
        Array.Sort(q);
        foreach(IList<int> quad in uPairs)
        {
            int i=0;
            while(i<4)
            {
                if(quad[i] != q[i])
                {
                    break;
                }
                i++;
            }
            if(i>=4) return;
        }
        uPairs.Add(q);
    }
}

Also read,

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.

Leave a Reply

Your email address will not be published. Required fields are marked *