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
The Mirror Number Hunt+3Person A-3Person BPAIR!Your NotebookSeen numbers:+3 โœ“-3 โœ“Max found: 3Algorithm Steps:1. ๐Ÿ‘‹ Meet person with +3 โ†’ Check notebook for -3 (not found)2. ๐Ÿ“ Add +3 to notebook3. ๐Ÿ‘‹ Meet person with -3 โ†’ Check notebook for +3 (found!)4. ๐ŸŽฏ Record pair: max = 35. ๐Ÿ“ Add -3 to notebook6. โœ… Continue until all people are processed๐ŸŽฏ Key Insight: Use a hash set to instantly check if the opposite number exists!
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).
Asked in
Google 34 Amazon 28 Meta 22 Microsoft 18
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen