Find N Unique Integers Sum up to Zero - Array - Easy - LeetCode
💻 coding

Find N Unique Integers Sum up to Zero - Array - Easy - LeetCode

1 min read 241 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to return an array of n unique integers that sum to zero.
  • 2For odd n, the array includes zero; for even n, it does not.
  • 3The solution has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to return an array of n unique integers that sum to zero."

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;

namespace LeetCode.AskGif.Easy.Array
{
 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
 {
 map.Add(res[i], 1);
 }
 }

 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);
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 8 June 2020 · 1 min read · 241 words

Part of AskGif Blog · coding

You might also like