Find N Unique Integers Sum up to Zero

Gulshan KumarGulshan Kumar
1 min read

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

LeetCode Problem - 1304

class Solution {
    // Method to generate an array of n integers with a sum of zero
    public int[] sumZero(int n) {
        // Creating an array to store the result
        int[] result = new int[n];
        // Setting the limit for positive and negative numbers
        int limit = 1000;
        // Calculating the number of symmetric elements
        int symmetric = n / 2;

        // Filling the first half of the array with positive integers decreasing from limit
        int idx = 0;
        for (int i = 0; i < symmetric; i++) {
            result[idx] = limit;
            limit--;
            idx++;
        }

        // Resetting the limit for negative numbers
        limit = 1000;
        // Filling the second half of the array with negative integers increasing from -limit
        for (int i = 0; i < symmetric; i++) {
            result[idx] = (limit * (-1));
            limit--;
            idx++;
        }

        // Adding zero if n is odd
        if (n % 2 != 0) {
            result[n - 1] = 0;
        }

        // Returning the result array
        return result;
    }
}
0
Subscribe to my newsletter

Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gulshan Kumar
Gulshan Kumar

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.