Largest Positive Integer That Exists With Its Negative - Problem
Imagine you're organizing a list of numbers, and you notice that some positive numbers have their negative counterparts hiding in the same list. Your task is to find the largest positive integer k such that its negative twin -k also exists in the array.
Given an integer array nums that contains no zeros, return the largest positive integer k where both k and -k are present in the array. If no such pair exists, return -1.
Example: In array [3, 2, -2, 5, -3], both 2 and -2 exist, and both 3 and -3 exist. The largest positive integer with its negative counterpart is 3.
Input & Output
example_1.py โ Python
$
Input:
[3, 2, -2, 5, -3]
โบ
Output:
3
๐ก Note:
We have pairs (2, -2) and (3, -3). The largest positive integer with its negative counterpart is 3.
example_2.py โ Python
$
Input:
[-1, 2, -3, 3]
โบ
Output:
3
๐ก Note:
We have the pair (3, -3). The number 2 doesn't have its negative counterpart -2, so we return 3.
example_3.py โ Python
$
Input:
[-1, 10, 6, 7, -7, 1]
โบ
Output:
7
๐ก Note:
We have pairs (1, -1) and (7, -7). The largest positive integer is 7.
Constraints
- 1 โค nums.length โค 1000
- -1000 โค nums[i] โค 1000
- nums[i] โ 0
Visualization
Tap to expand
Understanding the Visualization
1
Meet Someone
You encounter person wearing jersey #3
2
Check Your Notes
Look in your notebook - have you seen someone with #-3?
3
Record the Pair
If you find both #3 and #-3, record 3 as a valid pair
4
Update Maximum
Keep track of the highest number that has both versions
5
Add to Notes
Write down #3 in your notebook for future reference
Key Takeaway
๐ฏ Key Insight: Instead of searching for each number's opposite repeatedly, we use a hash set to store seen numbers and check opposites in O(1) time, making the entire solution O(n).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code