Largest Positive Integer That Exists With Its Negative Problem
#2441
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2441.
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.
Example 1:
Input: nums = [-1,2,-3,3]
Output: 3
Explanation: 3 is the only valid k we can find in the array.
Example 2:
Input: nums = [-1,10,6,7,-7,1]
Output: 7
Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
Example 3:
Input: nums = [-10,8,6,7,-2,-3]
Output: -1
Explanation: There is no a single valid k, we return -1.
Constraints:
1 <= nums.length <= 1000-1000 <= nums[i] <= 1000nums[i] != 0
Solution
Approach: Hash Set
Put every number into a set. Then go through the set: whenever x is in it and so is -x, x is a candidate, and we keep the largest one. If no pair exists, the answer stays -1.
Complexity: O(n) time and O(n) space, where n is the length of the array.
class Solution:
def findMaxK(self, nums: List[int]) -> int:
s = set(nums)
return max((x for x in s if -x in s), default=-1)