We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Largest Positive Integer That Exists With Its Negative

Number: 2524

Difficulty: Easy

Paid? No

Companies: Amazon, Microsoft


Problem Description

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 k if found; otherwise, return -1.


Key Insights

  • Use a hash set for quick look-up of elements.
  • Iterate through each number in the array; if the number is positive and its negative is also present, it is a candidate.
  • Keep track of the maximum valid candidate found.
  • The array does not contain zero, which simplifies the checks.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the array (using a set for O(1) look-ups). Space Complexity: O(n), for storing elements in the hash set.


Solution

We start by putting all the numbers in a hash set for O(1) look-up time. Then, we iterate through the array and for each positive number k, we check if -k exists in the set. If it does, we update our answer with the maximum value between the current answer and k. Finally, if no valid k is found, we return -1.


Code Solutions

# Define the function to find the largest positive integer that exists with its negative.
def find_max_k(nums):
    # Convert the list to a set for fast lookup.
    num_set = set(nums)
    
    # Initialize the result with -1 (default when no valid k is found).
    max_k = -1
    
    # Iterate through each number in the list.
    for num in nums:
        # Consider only positive numbers.
        if num > 0:
            # Check if the corresponding negative exists in the set.
            if -num in num_set:
                # Update max_k if this number is larger than the current max_k.
                max_k = max(max_k, num)
    return max_k

# Example usage:
print(find_max_k([-1,2,-3,3]))  # Output: 3
print(find_max_k([-1,10,6,7,-7,1]))  # Output: 7
print(find_max_k([-10,8,6,7,-2,-3]))  # Output: -1
← Back to All Questions