Blogs Hub

by Sumit Chourasia | Jun 08, 2020 | Category :coding | Tags : arrayalgorithmडेटा-संरचनाआसानc-sharpleetcode

Find N Unique Integers Sum up to Zero - Array - Easy - LeetCode - मिनी टीवी

Given an integer n, return any array containing n unique integers such that they add up to 0.

Example 1:

Input: n = 5

Output: [-7,-1,1,3,4]

Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Example 2:

Input: n = 3

Output: [-1,0,1]

Example 3:

Input: n = 1

Output: [0]

Constraints:

1 <= n <= 1000

Solution:

``````using System;
using System.Collections.Generic;
using System.Text;

{
public class SumZeroSoln
{
public int[] SumZero(int n)
{
var res = new int[n];
if (n == 0)
{
return null;
}

for (int i = 0, j = n - 1; i < j; i++, j--)
{
res[i] = (i+1);
res[j] = (i+1) * -1;
}

if (n % 2 != 0)
{
res[n / 2] = 0;
}

return res;
}
}
}
``````

Time Complexity: O(n)

Space Complexity: O(n) To Store result

Unit Tests:

``````using LeetCode.AskGif.Easy.Array;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.Array
{
[TestClass]
public class SumZeroSolnTests
{
[TestMethod]
public void SumZeroSoln_First()
{
var n = 5;
var res = new SumZeroSoln().SumZero(n);

IsSumZero(res);
}

private void IsSumZero(int[] res)
{
var map = new Dictionary<int, int>();
for (int i = 0; i < res.Length; i++)
{
if (map.ContainsKey(res[i]))
{
map[res[i]]++;
}
else
{
}
}

foreach (var item in map)
{
Assert.AreEqual(item.Value, 1);
}

var sum = 0;
for (int i = 0; i < res.Length; i++)
{
sum += res[i];
}

Assert.AreEqual(sum, 0);
}
}
}
``````

Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia