πΉ Problem: 1304 Find N Unique Integers Sum up to Zero
Difficulty: #Easy
Tags: #Math, #Constructive
π Problem Summary
Given an integer
n
, return an array ofn
unique integers such that they sum up to 0.
π§ My Thought Process
Brute Force Idea:
Generate random numbers and try to adjust until their sum is zero. This would be messy and inefficient.-
Optimized Strategy:
- Pair positive and negative integers:
(1, -1), (2, -2), ...
- If
n
is even, the pairs are enough. - If
n
is odd, just add0
to balance everything out. - This guarantees uniqueness and ensures the sum is always 0.
- Pair positive and negative integers:
Algorithm Used:
Constructive Math (pairing positives and negatives).
βοΈ Code Implementation (Python)
class Solution:
def sumZero(self, n: int) -> List[int]:
ans = []
for i in range(1, n // 2 + 1):
ans.append(i)
ans.append(-i)
if n % 2 == 1:
ans.append(0)
return ans
β±οΈ Time & Space Complexity
-
Time: O(n) β we generate
n
elements. - Space: O(n) β storing the result array.
π§© Key Takeaways
- β Learned how constructive math can directly give the answer without brute force.
- π‘ The βpairingβ trick is a powerful way to balance sums.
- π If a problem asks for sums = 0 (or balanced counts), think about symmetry.
π Reflection (Self-Check)
- [x] Could I solve this without help?
- [x] Did I write code from scratch?
- [x] Did I understand why it works?
- [x] Will I be able to recall this in a week?
π Progress Tracker
Metric | Value |
---|---|
Day | 76 |
Total Problems Solved | 440 |
Confidence Today | π |
Leetcode Rating | 1530 |
Top comments (0)