Largest Positive Integer That Exists With Its Negative - Problem

Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.

Return the positive integer k. If there is no such integer, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [-1,2,-3,3]
Output: 3
💡 Note: 3 is the largest positive integer that has its negative -3 in the array. Both 2 and 3 have their negatives, but 3 is larger.
Example 2 — No Valid Pairs
$ Input: nums = [-1,10,6,7,-7,1]
Output: 7
💡 Note: Only 7 has its negative -7 in the array. Numbers like 10, 6 don't have their negatives present.
Example 3 — No Pairs Exist
$ Input: nums = [-10,8,6,7,4,2,3]
Output: -1
💡 Note: None of the positive integers have their negative counterparts in the array.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000
  • nums[i] ≠ 0

Visualization

Tap to expand
Largest Positive Integer With Its Negative INPUT nums = [-1, 2, -3, 3] -1 idx 0 2 idx 1 -3 idx 2 3 idx 3 Find pairs: num and -num -1, 1 1 missing -3, 3 Both exist! Hash Set Stores: {-1, 2, -3, 3} Goal: Find largest k where both k and -k exist ALGORITHM STEPS 1 Initialize HashSet seen = {} result = -1 2 Loop Through Array For each num in nums: 3 Check Negative If -num in seen: result = max(result, abs(num)) 4 Add to Set seen.add(num) Trace: -1: seen={-1}, res=-1 2: seen={-1,2}, res=-1 -3: seen={-1,2,-3}, res=-1 3: -3 found! res=max(-1,3)=3 FINAL RESULT Valid Pair Found: 3 & -3 3 and -3 both exist in array Output: 3 OK - Largest k found! Why 3? Only valid pair: (3, -3) 1 doesn't exist, so -1 invalid Key Insight: Using a HashSet allows O(1) lookup to check if the negative counterpart exists. Single pass through array: for each number, check if its negation is already in the set, then add current number. Track maximum absolute value found. Time: O(n), Space: O(n) TutorialsPoint - Largest Positive Integer That Exists With Its Negative | Hash Set - Single Pass
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.5K Views
Medium Frequency
~15 min Avg. Time
890 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